前后端添加ba认证

615 查看

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