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


codecraft
11.9k 声望2k 粉丝

当一个代码的工匠回首往事时,不因虚度年华而悔恨,也不因碌碌无为而羞愧,这样,当他老的时候,可以很自豪告诉世人,我曾经将代码注入生命去打造互联网的浪潮之巅,那是个很疯狂的时代,我在一波波的浪潮上留下...