目录
WebSecurityConfigurerAdapter 类是个适配器, 在配置SecurityConfig时需要我们自己写个配置类去继承这个适配器,根据需求重写适配器的方法.
@Configuration
@EnableWebSecurity
public class WebSecurityConfigextends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/resources/**", "/signup", "/about").permitAll()
.antMatchers("/admin/**").hasRole("ADMIN")
.antMatchers("/db/**").access("hasRole('ADMIN') and hasRole('DBA')")
.anyRequest().authenticated()
.and()
.formLogin()
.usernameParameter("username")
.passwordParameter("password")
.failureForwardUrl("/login?error")
.loginPage("/login")
.permitAll()
.and()
.logout()
.logoutUrl("/logout")
.logoutSuccessUrl("/index")
.permitAll()
.and()
.httpBasic()
.disable();
}
}
程序说明一
Security的认证策略, 每个模块配置使用and结尾。
- authorizeRequests()配置路径拦截,表明路径访问所对应的权限,角色,认证信息。
- formLogin()对应表单认证相关的配置
- logout()对应了注销相关的配置
- httpBasic()可以配置basic登录
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("admin").password("admin").roles("USER");
}
程序说明二
这段 配置是认证信息,
AuthenticationManagerBuilder 类是AuthenticationManager的建造者, 我们只需要向这个类中, 配置用户信息, 就能生成对应的AuthenticationManager, 这个类也提过,是用户身份的管理者, 是认证的入口, 因此,我们需要通过这个配置,想security提供真实的用户身份。 如果我们是使用UserDetailsService来配置用户身份的话, 这段配置改为如下:
@Override
protected void configure(AuthenticationManagerBuilder builder) throws Exception{
builder.userDetailsService(dbUserDetailsService);
}
dbUserDetailsService就是你自己写的类, 这个类的作用就是去获取用户信息,比如从数据库中获取。 这样的话,AuthenticationManager在认证用户身份信息的时候,就回从中获取用户身份,和从http中拿的用户身份做对比。
本文详细解析Spring Security的配置过程,包括如何使用WebSecurityConfigurerAdapter进行路径拦截配置,设置认证策略,以及如何通过AuthenticationManagerBuilder配置用户信息。涵盖了表单认证、注销配置和基本HTTP认证的设置。
1351

被折叠的 条评论
为什么被折叠?



