前后端添加ba认证

codecraft

spring security

maven依赖

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>

config

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled=true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .csrf().disable()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
                .authorizeRequests()
                .antMatchers("/**").authenticated()
                .anyRequest().anonymous()
                .and()
                .httpBasic()
                .realmName("known");
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth
                .inMemoryAuthentication()
                .withUser("xixicat").password("xixicat").roles("USER");
    }
}

jquery配置

$.ajax({
                beforeSend: function (xhr) {
                    xhr.setRequestHeader ("Authorization", "Basic " + btoa('xixicat' + ":" + 'xixicat'));
                },
                url: '/demo',
                type: 'POST',
                dataType:"json",
                contentType:"application/json",
                data:JSON.stringify(saveData),
                success: function (res, status) {
                    window.location.reload();
                },
                error: function (data, status) {
                    if (data.status == 200) {
                        window.location.reload();
                    }else{
                        dangerDialog(data.statusText);

                    }
                }
            });

android的retrofit配置

OkHttpClient httpClient = new OkHttpClient();
        httpClient.interceptors().clear();
        httpClient.interceptors().add(new Interceptor() {
            @Override
            public Response intercept(Interceptor.Chain chain) throws IOException {
                Request original = chain.request();
                Request.Builder requestBuilder = original.newBuilder()
                        .header("Authorization", basic)
                        .method(original.method(), original.body());
                Request request = requestBuilder.build();
                return chain.proceed(request);
            }
        });

        Gson gson = builder.create();
        this.retrofit = new Retrofit.Builder()
                .baseUrl(API)
                .client(httpClient)
                .addConverterFactory(GsonConverterFactory.create(gson))
                .build();

docs

阅读 3.9k

code-craft
spring boot , docker and so on 欢迎关注微信公众号: geek_luandun

当一个代码的工匠回首往事时,不因虚度年华而悔恨,也不因碌碌无为而羞愧,这样,当他老的时候,可以很...

11.6k 声望
1.9k 粉丝
0 条评论
你知道吗?

当一个代码的工匠回首往事时,不因虚度年华而悔恨,也不因碌碌无为而羞愧,这样,当他老的时候,可以很...

11.6k 声望
1.9k 粉丝
文章目录
宣传栏