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

SpringSecurity从入门到精通

快速入门

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

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

1、引入依赖

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

新建一个简单的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<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 IOE
### Spring Security 和 JWT前后端分离架构中的身份验证与授权 在现代 Web 应用程序开发中,采用前后端分离架构变得越来越普遍。为了在这种架构下实现安全的身份验证和授权机制,通常会选择结合使用 Spring Security 和 JSON Web Token (JWT)[^1]。 #### 配置 Spring Security 自定义过滤器链 通过继承 `WebSecurityConfigurerAdapter` 类并覆盖其方法来定制化配置 Spring Security 是一种常见做法。然而,在最新版本的 Spring Security 中推荐直接注册组件而不是扩展此适配器类[^2]: ```java @EnableWebSecurity public class SecurityConfig { @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http.csrf().disable() .authorizeRequests() .antMatchers("/api/auth/**").permitAll() .anyRequest().authenticated() .and() .sessionManagement() .sessionCreationPolicy(SessionCreationPolicy.STATELESS); http.addFilterBefore(jwtAuthenticationTokenFilter(), UsernamePasswordAuthenticationFilter.class); return http.build(); } } ``` 这段代码禁用了 CSRF 支持(因为 REST API 不应依赖于浏览器自动发送 Cookies)、启用了路径匹配规则以及设置了无状态会话管理策略,并添加了一个自定义的 JWT 认证过滤器到 HTTP 请求处理流程之前。 #### 创建 JWT 认证过滤器 接下来需要编写一个专门负责解析请求头携带的 Bearer token 并完成用户认证逻辑的过滤器: ```java @Component public class JwtAuthenticationTokenFilter extends OncePerRequestFilter { private final String secretKey; public JwtAuthenticationTokenFilter(@Value("${jwt.secret}") String secretKey) { this.secretKey = secretKey; } @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException { try { String jwt = getJwtFromRequest(request); if (StringUtils.hasText(jwt)) { Claims claims = Jwts.parserBuilder() .setSigningKey(Keys.hmacShaKeyFor(secretKey.getBytes())) .build() .parseClaimsJws(jwt).getBody(); String username = claims.getSubject(); Collection<? extends GrantedAuthority> authorities = Arrays.stream(claims.get("roles").toString().split(",")) .map(SimpleGrantedAuthority::new) .collect(Collectors.toList()); Authentication authentication = new UsernamePasswordAuthenticationToken( username, null, authorities); SecurityContextHolder.getContext().setAuthentication(authentication); } } catch (Exception ex){ logger.error("Could not set user authentication in security context", ex); } chain.doFilter(request,response); } private String getJwtFromRequest(HttpServletRequest request) { String bearerToken = request.getHeader("Authorization"); if (StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer ")) { return bearerToken.substring(7, bearerToken.length()); } return null; } } ``` 上述代码实现了从 HTTP 头部提取 JWT 字符串的功能,并利用 HMAC SHA-256 算法对其进行签名验证;如果成功,则构建相应的 `UsernamePasswordAuthenticationToken` 对象填充至当前线程的安全上下文中以便后续访问控制决策时能够获取已登录用户的权限信息[^3]。 #### 客户端集成 对于前端应用而言,当用户尝试登录时应该向服务器提交用户名密码组合换取有效的 JWT ,之后每次发起受保护资源请求前都需要附带该令牌作为凭证。考虑到 Base64 编码可能存在的 URL 特殊字符问题,建议遵循 RFC 7519 规范采用 Base64URL 方案编码 payload 数据部分[^4]。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值