Spring Security(十六):5.7 Multiple HttpSecurity
Posted 帅S俊
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Spring Security(十六):5.7 Multiple HttpSecurity相关的知识,希望对你有一定的参考价值。
We can configure multiple HttpSecurity instances just as we can have multiple <http>
blocks. The key is to extend the WebSecurityConfigurerAdapter
multiple times. For example, the following is an example of having a different configuration for URL’s that start with /api/
.
@EnableWebSecurity public class MultiHttpSecurityConfig { @Bean public UserDetailsService userDetailsService() throws Exception { InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager(); manager.createUser(User.withUsername("user").password("password").roles("USER").build()); manager.createUser(User.withUsername("admin").password("password").roles("USER","ADMIN").build()); return manager; } @Configuration @Order(1) 1 public static class ApiWebSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter { protected void configure(HttpSecurity http) throws Exception { http .antMatcher("/api/**") 2 .authorizeRequests() .anyRequest().hasRole("ADMIN") .and() .httpBasic(); } } @Configuration 3 public static class FormLoginWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .anyRequest().authenticated() .and() .formLogin(); } } }
Configure Authentication as normal
1、Create an instance of WebSecurityConfigurerAdapter that contains @Order to specify which WebSecurityConfigurerAdapter should be considered first.
2、The http.antMatcher states that this HttpSecurity will only be applicable to URLs that start with /api/
3、Create another instance of WebSecurityConfigurerAdapter. If the URL does not start with /api/ this configuration will be used. This configuration is considered after
ApiWebSecurityConfigurationAdapter since it has an @Order value after 1 (no @Order defaults to last).
以上是关于Spring Security(十六):5.7 Multiple HttpSecurity的主要内容,如果未能解决你的问题,请参考以下文章
如何将自定义密码编码器添加到 Spring Security?