栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

【SpringSecurity+JWT】实现前后端分离认证授权

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

【SpringSecurity+JWT】实现前后端分离认证授权

SpringSecurity从入门到精通 快速入门

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

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

1、引入依赖


    org.springframework.boot
    spring-boot-starter-security

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

认证

基本原理

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

SpringSecurity过滤器链如图

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

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


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权限模型)

自定义权限校验方法
@Component("ex")
public class SGExpressionRoot {
    public boolean hasAuthority(String authority){
        // 获取当前用户权限
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser)authentication.getPrincipal();
        List 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("
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 查询用户信息
        LambdaQueryWapper queryWrapper = new LambdaQueryWapper();
        queryWrapper.eq(User::getUserName, username);
        User user = userMapper.selectOne(queryWrapper);
        // 如果没有用户抛异常
        if(Objects.inNull(user)){
            throw new RuntimeException("用户名或密码错误");
        }
        // 把数据封装成UserDetails对象
        List 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 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);
    }
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1002715.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号