SpringSecurity从入门到精通

快速入门

SpringSecurity是spring家族中的一个安全管理框架,核心功能是认证和授权

认证:验证当前访问系统的是不是系统的用户,并且要确认具体是哪个用户
授权:经过认证后判断当前用户时候有权限进行某个操作

1、引入依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

新建一个简单的helloController,然后我们访问hello接口,就需要先登录才能访问

认证

前后端分离spring security开启csrf springsecurity前后端分离登录认证_spring

基本原理

SpringSecurity的原理其实就是一个过滤器链,内部包含了提供各种功能的过滤器,如下展示几个重要的过滤器

前后端分离spring security开启csrf springsecurity前后端分离登录认证_spring_02

SpringSecurity过滤器链如图

前后端分离spring security开启csrf springsecurity前后端分离登录认证_自定义_03

其中最常用的三个过滤器:

  1. UsernamePasswordAuthenticationFilter:负责处理我们在登录页面填写了用户名和密码后的登录请求。默认的账号密码认证主要是他来负责
  2. ExceptionTranslationFilter:处理过滤器链中抛出的任何AccessDeniedException和AuthenticationException
  3. FilterSecurityInterceptor:负责权限校验的过滤器

前后端分离spring security开启csrf springsecurity前后端分离登录认证_ide_04


Authentication接口:它的实现类,表示当前访问系统的用户,封装了前端传入的用户相关信息

AuthenticationManager接口:定义了认证Authentication的方法

UserDetailsService接口:加载用户特定数据的核心接口。里面定义了一个更具用户名查询用户信息的方法

UserDetails接口:提供核心用户信息。通过UserDetailService根据用户名获取处理的用户信息要封装成UserDetails对象放回。然后将这些信息封装到Authentication对象中

认证配置讲解

@Override
protected void configure(HttpSecurity httpSecurity) throws Exception{
    httpSecurity
            //关闭csrf
            .csrf().disable()
            //不通过Session获取SecurityContext
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .and()
            .authorizeRequests()
            //对于登录接口,允许匿名访问
            .antMatchers("/login").anonymous()
            //除上面外的所有请求全部需要鉴权认证
            .anyRequest().authenticated();

    httpSecurity.addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
}

授权

不同的用户可以有不同的功能

在SpringSecurity中,会使用默认的FilterSecurityInterceptor来进行权限校验,在FilterSecurityInterceptor中会从SecurityContextHolder获取其中的Authentication,然后获取其中的权限信息,当前用户是否拥有访问当前资源所需要的权限,所以我们在项目中只需要把当前用户的权限信息存入Authentication

限制访问资源所需要的权限

// 放在配置类上
@EnableGlobalMethodSecurity(prePostEnable=true)
@RestController
public class LoginController {

    @RequestMapping("/login")
    // 有test权限才可以访问
    @PreAuthorize("hasAuthority('test')")
    // 有test和admin中的任意权限即可
    @PreAuthorize("hasAnyAuthority('test','admin')")
    // 必须有ROLE_test和ROLE_admin两个权限,hasRole会默认给角色添加前缀
    @PreAuthorize("hasRole('ROLE_test','ROLE_admin')")
    // 有ROLE_test和ROLE_admin中的任意权限即可,hasRole会默认给角色添加前缀
    @PreAuthorize("hasAnyRole('ROLE_test','ROLE_admin')")
    public String login(@RequestBody User user){
        // 登录
        return loginService.login(user);
    }
}

正常企业开发是不会选择在代码中控制权限的,而是从数据库中,通过用户、角色、权限来配置(RBAC权限模型)

前后端分离spring security开启csrf springsecurity前后端分离登录认证_前端_05

自定义权限校验方法

@Component("ex")
public class SGExpressionRoot {
    public boolean hasAuthority(String authority){
        // 获取当前用户权限
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser)authentication.getPrincipal();
        List<String> permissions = loginUser.getPermissions();
        return permissions.contains(authority);
    }
}

调用我们自定义的检查规则

@RequestMapping("/login")
// SPEL表达式,@ex相当于获取容器中bean的名字是ex的对象
@PreAuthorize("@ex.hasAuthority('test')")
//    @PreAuthorize("hasAuthority('test')")
public String login(@RequestBody User user){
    // 登录
    return loginService.login(user);
}

配置文件配置访问权限

httpSecurity
                //关闭csrf
                .csrf().disable()
                //不通过Session获取SecurityContext
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                //对于登录接口,允许匿名访问
                .antMatchers("/login").anonymous()
                //具有admin权限才能访问helloController
                .antMatchers("/hello").hasAuthority("admin")
                //除上面外的所有请求全部需要鉴权认证
                .anyRequest().authenticated();

自定义失败提示

SpringSecurity自定义的异常过滤器,ExceptionTranslationFilter
认证过程出现异常,会被封装成AuthenticationException然后调用AuthenticationEntryPoint对象的方法
授权过程中出现异常会被封装成AccessDeniedException然后调用AccessDeniedHandler对象的方法

所以如果我们想要自定义异常处理,只需要自定义AuthenticationEntryPoint和AccessDeniedHandler然后配置给SpringSecurity即可

@Component
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        ResponseResult responseResult = new ResponseResult(HttpStatus.UNAUTHORIZED.value(),"用户认证失败,请重新登录");
        String s = JSON.toJSONString(responseResult);
        try {
            response.setStatus(200);
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            response.getWriter().print(s);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
@Component
public class AccessDeniedHandlerImpl implements AccessDeniedHandler {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        ResponseResult responseResult = new ResponseResult(HttpStatus.FORBIDDEN.value(),"权限不足");
        String s = JSON.toJSONString(responseResult);
        try {
            response.setStatus(200);
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            response.getWriter().print(s);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

在SpringSecurity的配置文件中,配置上我们自定义的异常处理器

@Configuration
@EnableGlobalMethodSecurity(prePostEnable=true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;
    @Autowired
    private AuthenticationEntryPoint authenticationEntryPoint;
    @Autowired
    private AccessDeniedHandler accessDeniedHandler;
    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }
    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception{
        httpSecurity
                //关闭csrf
                .csrf().disable()
                //不通过Session获取SecurityContext
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                //对于登录接口,允许匿名访问
                .antMatchers("/login").anonymous()
                //除上面外的所有请求全部需要鉴权认证
                .anyRequest().authenticated();

        // 添加过滤器
        httpSecurity.addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);

        // 配置异常处理器
        httpSecurity.exceptionHandling()
                // 配置认证失败处理器
                .authenticationEntryPoint(authenticationEntryPoint)
                // 配置授权失败过滤器
                .accessDeniedHandler(accessDeniedHandler);
    }
}

跨域

SpringBoot配置跨域

@Configuration
public class CorsConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry){
        // 设置允许跨域的路径
        registry.addMapping("/**")
                // 设置允许跨域请求的域名
                .allowedOriginPatterns("*")
                // 是否允许cookie
                .allowCredentials(true)
                // 设置允许的请求方式
                .allowedMethods("GET","POST","DELETE","PUT")
                // 设置允许的header属性
                .allowedHeaders("*")
                // 跨域允许时间
                .maxAge(3600);
    }
}

SpringSecurity的配置类

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;
    @Autowired
    private AuthenticationEntryPoint authenticationEntryPoint;
    @Autowired
    private AccessDeniedHandler accessDeniedHandler;
    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }
    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception{
        httpSecurity
                //关闭csrf
                .csrf().disable()
                //不通过Session获取SecurityContext
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                //对于登录接口,允许匿名访问
                .antMatchers("/login").anonymous()
                //除上面外的所有请求全部需要鉴权认证
                .anyRequest().authenticated();

        // 添加过滤器
        httpSecurity.addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);

        // 配置异常处理器
        httpSecurity.exceptionHandling()
                // 配置认证失败处理器
                .authenticationEntryPoint(authenticationEntryPoint)
                // 配置授权失败过滤器
                .accessDeniedHandler(accessDeniedHandler);

        // 允许跨域
        httpSecurity.cors();
    }
}

CSRF

CSRF是指跨站请求伪造,是web常见的攻击之一

SPringSecurity去防止CSRF工具的方式就是通过csrf_token,后端生成一个csrf_token,前端发起请求的时候要携带这个csrf_token,后端会有过滤器进行校验,如果没有携带过着是伪造就不允许访问

我们可以发现CSRF工具依靠的是cookie中所携带的认证信息,但是在前后端分析的项目中我们的认证信息其实是token,而token并不是存储cookie中,并且需要前端代码去把token设置到请求头中才可以,所以CSRF工具也就不用担心了

前后端分离spring security开启csrf springsecurity前后端分离登录认证_spring_06

源码分析

认证成功处理器AuthenticationSuccessHandler,进行成功后的相应的操作
我们也可以自定义成功后的处理器

@Component
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        System.out.println("认证成功");
    }
}



// 添加到SpringSecurity的配置类
httpSecurity.formLogin().successHandler(authenticationSuccessHandler);

认证失败处理器AuthenticationFailureHandler,进行失败后的相应的操作
我们也可以自定义失败后的处理器

@Component
public class MyAuthenticationFailureHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        System.out.println("认证失败");
    }
}


// 添加到SpringSecurity的配置类
httpSecurity.formLogin().failureHandler(authenticationFailureHandler);

注销成功过滤器

@Component
public class MyLogoutSuccessHandler implements LogoutSuccessHandler {
    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        System.out.println("注销成功");
    }
}

// 添加到SpringSecurity的配置类
httpSecurity.logout().logoutSuccessHandler(myLogoutSuccessHandler);

认证代码示例

基于SpringSecurity基础上,修改代码实现我们自定义的授权验证流程

前后端分离spring security开启csrf springsecurity前后端分离登录认证_前端_07

前后端分离spring security开启csrf springsecurity前后端分离登录认证_spring_08

思路分析:
登录部分:
自定义登录接口
调用providerManager的方法进行认证,如果认证通过生成jwt
把用户信息存入redis中
自定义UserDetailsService
在这个实现列中去查询数据库

校验部分:
定义jwt认证过滤器
获取token
解析token获取其中的userid
从redis中获取用户信息
存入SecurityContextHolder

1、引入启动器和依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.47</version>
</dependency>

<dependency>
    <groupId>io.jsonwebtoken</groupId>
    <artifactId>jjwt</artifactId>
    <version>0.9.0</version>
</dependency>

2、前端代码、连接数据库代码忽略

3、核心代码
创建UserDetails实现类,用于保存从数据库获取到用户信息

@Data
@NoArgsConstructor
@AllArgsConstructor
public class LoginUser implements UserDetails {
    // 存储用户账号密码
    private User user;

    // 存储权限信息
    private List<String> permissions;

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        if(permissions!=null){
            return permissions;
        }
        // 把permissions中String类型的权限信息封装成SimpleGrantedAuthority对象
        List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
        for (String permission : permissions) {
            SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(permission);
            grantedAuthorities.add(simpleGrantedAuthority);
        }
        return grantedAuthorities;
    }

    @Override
    public String getPassword() {
        return user.getPassword();
    }

    @Override
    public String getUsername() {
        return user.getUsername();
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }
}

实现UserDetailsService,通过数据库查询账号密码

public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    /**
     * 根据用户名去查询用户以及用户权限
     * 把对应的用户信息封装成UserDetails对象
     *
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 查询用户信息
        LambdaQueryWapper<User> queryWrapper = new LambdaQueryWapper();
        queryWrapper.eq(User::getUserName, username);
        User user = userMapper.selectOne(queryWrapper);
        // 如果没有用户抛异常
        if(Objects.inNull(user)){
            throw new RuntimeException("用户名或密码错误");
        }
        // 把数据封装成UserDetails对象
        List<String> list = userMapper.selectpermsByUserId(user.getId());
        return new LoginUser(user,list);
    }
}

通过PasswordEncoder对比前端传入的和数据库查询的用户信息
我们一般使用的是SpringSecurity为我们提供的BCryptPasswordEncoder
我们只需要将BCryptPasswordEncoder注入到IOC容器中

// SpringSecurity的配置扩展类,继承WebSecurityConfigurerAdapter
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;
    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }
    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception{
        httpSecurity
                //关闭csrf
                .csrf().disable()
                //不通过Session获取SecurityContext
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                //对于登录接口,允许匿名访问
                .antMatchers("/login").anonymous()
                //除上面外的所有请求全部需要鉴权认证
                .anyRequest().authenticated();

        httpSecurity.addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
    }
}

自定义登录接口

@RestController
public class LoginController {

    @RequestMapping("/login")
    @PreAuthorize("hasAuthority('test')")
    public String login(@RequestBody User user){
        // 登录
        return loginService.login(user);
    }


    @RequestMapping("/logout")
    public String logout(@RequestBody User user){
        // 登录
        return loginService.logout(user);
    }
}

登录服务主要逻辑

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private RedisCache redisCache;

    @Override
    public ResponseResult login(User user){
        // AuthenticationManager authenticate 进行用户认证
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUserName(), user.getPassword());
        Authentication authentication = authenticationManager.authenticate(authenticationToken);
        // 认证不通过,给出提示
        if(Objects.isNull(authentication)){
            throw new RuntimeException("登录失败");
        }
        // 认证通过了,生成jwt
        LoginUser loginUser = authentication.getPrincipal();
        String userid = loginUser.getUser().getId().toString();
        String JWT = JwtUtil.createJWT(userid);
        HashMap<String, String> map = new HashMap<>();
        map.put("token",jwt);
        // 把完整的信息存入redis
        redisCache.setCacheObject("login:"+userid, loginUser);

        return new ResponseResult(200, "登陆成功",map);
    }


    @Override
    public ResponseResult logout(User user) {
        // 获取SecurityContextHolder中的用户id
        UsernamePasswordAuthenticationToken authentication = (UsernamePasswordAuthenticationToken)SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser)authentication.getPrincipal();
        Long userid = loginUser.getUser().getId();

        // 删除redis中的值
        redisCache.deleteObject("login:"+userid);
        return new ResponseResult(200,"注销成功");
    }
}

定义jwt认证过滤器

@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    @Autowired
    private RedisCache redisCache;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        // 获取token
        String token = request.getHeader("token");
        if(!StringUtils.hasText(token)){
            filterChain.doFilter(request,response);
            return;
        }
        // 解析token
        String userid;
        try {
            Claims claims = JwtUtil.parseJWT(token);
            userid = claims.getSubject();

        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("token非法");
        }
        // 从redis中获取用户信息
        String redisKey = "login:"+userid;
        LoginUser loginUser = redisCache.getCacheObject(redisKey);
        if(Objects.isNull(loginUser)){
            throw new RuntimeException("用户未登录");
        }
        // 存入SecurityContextHolder
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser,null,null);
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);

        filterChain.doFilter(request,response);
    }
}