1.关于Spring Security
Spring Security is a powerful and highly customizable authentication and access-control framework. It is the de-facto standard for securing Spring-based applications.
Spring Security is a framework that focuses on providing both authentication and authorization to Java applications. Like all Spring projects, the real power of Spring Security is found in how easily it can be extended to meet custom requirements
这是Spring Security的官方说明,大概是说Spring Security是一个功能强大且高度可定制的用于认证(authentication)和访问控制(access-control)的框架。该框架致力于为java应用提供认证(authentication)和授权(authorization),并且非常容易根据需要进行扩展,总之就是说Spring Security很diao啦。
2.在Spring boot中的基本使用
1)继承WebSecurityConfigurerAdapter,并重写configure(AuthenticationManagerBuilder auth) 和 configure(HttpSecurity http)方法。
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private AuthUserService authUserService;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(authUserService).passwordEncoder(new BCryptPasswordEncoder());
}
@Override
protected void configure(HttpSecurity http) throws Exception {
//定义/login /upload不需要登录
//定义登录页面为/login
http.authorizeRequests()
.antMatchers("/login","/register").permitAll()
.antMatchers("/css/**","/js/**").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.successForwardUrl("/")
.permitAll()
.and()
.logout()
.permitAll();
}
}
@EnableWebSecurity和@Configuration注解表名了这是一个Spring Security配置类,有了这两个注解,Spring Security会自动去识别加载。
configure(HttpSecurity http)方法定义了哪些地方需要权限控制以及定义了自定义登录页(否则就会加载Spring Security的自带登录页)。
configure(AuthenticationManagerBuilder auth) 方法定义了通过mybatis方式实现登录认证,以及规定了加密方法为:BCrypt。AuthenticationManagerBuilder
用于创建一个 AuthenticationManager
,让我们能够轻松的实现内存验证、LADP验证、基于JDBC的验证、添加 UserDetailsService
、添加 AuthenticationProvider
。
其中AuthUserService如下:
@Service public class AuthUserService implements UserDetailsService { @Autowired private UserService userService; @Override public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException { var user=userService.login(s); if(user==null){ throw new UsernameNotFoundException("User "+s+" not found."); } System.out.println(user.toString()); List<SimpleGrantedAuthority> simpleGrantedAuthorities=new ArrayList<>(); simpleGrantedAuthorities.add(new SimpleGrantedAuthority("USERADMIN")); return new User(user.getAccount(),user.getPassword(),simpleGrantedAuthorities); } }
UserService是调用mybatis方法获取user。
UserDetailsService是Spring Security内置的用户信息接口,实现此接口的loadUserByUsername方法后,和上面的SecurityConfig类结合起来,Spring Security会自动去验证账号密码,认证通过后就会跳转到预设的地址。
3.Spring Security认证原理
参考:Spring4all:Spring-Security-入门