Spring Security 授权认证部分学习记录

Spring Security官方文档

 Spring Security和Shiro都是安全框架,其中包含了很多内容本文主要记录一下自己理解的授权认证部分希望能表达的尽量简洁和完整,欢迎交流。

 formlogin主体流程

Spring Security 授权认证部分学习记录

其中认证相关Filter负责构建Token实体(未认证),并交给AuthenticationProvider进行验证Token并重新构建Token实体(已认证)。具体可参见org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter内源码。

还包含其它认证流程如BasicAuthenticationFilter,DigestAuthenticationFilter等,官方给的formlogin就是UsernamePasswordAuthenticationFilter相关的一整套流程,有兴趣的话可以看下formlogin这个方法对应的源码,其中包含了很多内容这里主要记录的是认证授权。

配置说明

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
 /**
  * 配置认证相关信息自定义AuthenticationProvider,UserDetailsService等
  * @param auth
  * @return void
  * @author mjm
  * @date 2020/1/20 16:08
  */

 @Override
 protected void configure(AuthenticationManagerBuilder auth) throws Exception {
  super.configure(auth);
 }

 /**
  * 整体设置,异常处理,需忽略的url等
  * @param web
  * @return void
  * @author mjm
  * @date 2019/12/30 14:07
  */
 @Override
 public void configure(WebSecurity web) {
  web.ignoring().antMatchers(HttpMethod.OPTIONS, "/**")
    .antMatchers("/css/**", "/fonts/**",
      "/img/**", "/js/**", "/plugins/**");
 }
 /**
  * 请求过程相关配置,formlogin,权限验证,cors,自定义过滤器等
  * @author mjm
  * @date 2020/1/20 16:13
 * @param http
  * @return void
  */
 @Override
 protected void configure(HttpSecurity http) throws Exception {
  http.cors().disable().csrf().disable().headers().frameOptions().disable();
  http.formLogin();
  http.authorizeRequests().antMatchers("/**").access("@sysAuthorize.check(authentication,request)");
 }
}

HttpSecurity说明:

1. 匹配url的顺序是从上至下

  1. access是自定义权健部分具体可参见官网中"Referring to Beans in Web Security Expressions"这一段,其中能传递的参数只有authentication(认证信息),request
  2. 自定义过滤器通过http.addFilterXXXX来添加可以指定过滤器的顺序
  3. 配置了formlogin SpringSecurity会通过默认配置实现一整套的认证流程,包含页面,但需要实现UserDetailsService

这里列举的是我认为比较重要的三个配置,WebSecurityConfigurerAdapter中包含很多其他的配置具体具体可参见源码

其它

1.自定义认证过程如何处理

继承AbstractAuthenticationProcessingFilter

public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) {
    //   token = xxx  
    return this.getAuthenticationManager().authenticate(token);
}
上一篇:大厂面试必问的Spring全家桶 4 大开源框架,思维脑图全总结,终于出来了


下一篇:angular基本知识学习笔记 - Component的基本概念