Spring Security并结合JWT实现用户认证(Authentication) 和用户授权(Authorization)

🎈个人公众号:🎈 :✨✨ 可为编程 ✨✨ 🍟🍟
🔑个人信条:🔑知足知不足 有为有不为 为与不为皆为可为🌵
🍉本篇简介:🍉 本片详细说明了Spring Security并结合JWT实现用户认证(Authentication) 和用户授权(Authorization),并给出具体操作实例,如有出入还望指正。

关注公众号【可为编程】回复【面试】领取年度最新面试题大全!!!

引言

在Web应用开发中,安全一直是非常重要的一个方面。Spring Security基于Spring 框架,提供了一套Web应用安全性的完整解决方案。

JwT (JSON Web Token) 是当前比较主源的Token令牌生成方案,非常适合作为登录和授权认证的凭证。

这里我们就使用 Spring Security并结合JWT实现用户认证(Authentication) 和用户授权(Authorization) 两个主要部分的安全内容。

一、JWT与OAuth2的区别

在此之前,只是停留在用的阶段,对二者的使用场景很是模糊,感觉都是一样的呀,有啥不同呢,这里我也是根据网上的指点,在这罗列一下。

1、跨域实现不同

首先是涉及到跨域的问题
如果ABC三个系统是相同域名的,比如都是ww

  • 6
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
Spring Security可以使用JWT(JSON Web Token)来验证用户的身份和权限。 1.添加JWT依赖项:在pom.xml文件中添加以下依赖项: ``` <dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt</artifactId> <version>0.9.1</version> </dependency> ``` 2.创建JWT工具类:创建一个JWT工具类来生成和验证JWT。 ``` import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureAlgorithm; import org.springframework.security.core.Authentication; import org.springframework.security.core.userdetails.User; import org.springframework.stereotype.Component; import java.util.Date; @Component public class JwtUtils { private final String JWT_SECRET = "mysecretkey"; private final int JWT_EXPIRATION_MS = 86400000; public String generateJwtToken(Authentication authentication) { User user = (User) authentication.getPrincipal(); return Jwts.builder() .setSubject((user.getUsername())) .setIssuedAt(new Date()) .setExpiration(new Date((new Date()).getTime() + JWT_EXPIRATION_MS)) .signWith(SignatureAlgorithm.HS512, JWT_SECRET) .compact(); } public boolean validateJwtToken(String authToken) { try { Jwts.parser().setSigningKey(JWT_SECRET).parseClaimsJws(authToken); return true; } catch (Exception e) { e.printStackTrace(); } return false; } public String getUsernameFromJwtToken(String token) { return Jwts.parser() .setSigningKey(JWT_SECRET) .parseClaimsJws(token) .getBody().getSubject(); } } ``` 3.创建JWT过滤器:创建一个JWT过滤器来验证JWT并设置用户的身份和权限。 ``` import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.web.authentication.WebAuthenticationDetailsSource; import org.springframework.stereotype.Component; import org.springframework.web.filter.OncePerRequestFilter; import com.example.demo.security.services.UserDetailsServiceImpl; import io.jsonwebtoken.ExpiredJwtException; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @Component public class JwtAuthTokenFilter extends OncePerRequestFilter { @Autowired private JwtUtils jwtUtils; @Autowired private UserDetailsServiceImpl userDetailsService; @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException { try { String jwt = parseJwt(request); if (jwt != null && jwtUtils.validateJwtToken(jwt)) { String username = jwtUtils.getUsernameFromJwtToken(jwt); UserDetails userDetails = userDetailsService.loadUserByUsername(username); UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities()); authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request)); SecurityContextHolder.getContext().setAuthentication(authentication); } } catch (ExpiredJwtException e) { logger.error("JWT token is expired: {}", e.getMessage()); } catch (Exception e) { logger.error("Cannot set user authentication: {}", e.getMessage()); } chain.doFilter(request, response); } private String parseJwt(HttpServletRequest request) { String headerAuth = request.getHeader("Authorization"); if (headerAuth != null && headerAuth.startsWith("Bearer ")) { return headerAuth.substring(7, headerAuth.length()); } return null; } } ``` 4.配置Spring Security:在Spring Security配置中添加JWT过滤器。 ``` import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.dao.DaoAuthenticationProvider; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; import com.example.demo.security.jwt.JwtAuthTokenFilter; import com.example.demo.security.services.UserDetailsServiceImpl; @Configuration @EnableWebSecurity @EnableGlobalMethodSecurity( // securedEnabled = true, // jsr250Enabled = true, prePostEnabled = true) public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private JwtAuthTokenFilter jwtAuthTokenFilter; @Autowired private UserDetailsServiceImpl userDetailsService; @Autowired private BCryptPasswordEncoder bCryptPasswordEncoder; @Bean public DaoAuthenticationProvider authenticationProvider() { DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider(); authProvider.setUserDetailsService(userDetailsService); authProvider.setPasswordEncoder(bCryptPasswordEncoder); return authProvider; } @Override public void configure(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception { authenticationManagerBuilder.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder); } @Bean @Override public AuthenticationManager authenticationManagerBean() throws Exception { return super.authenticationManagerBean(); } @Bean public BCryptPasswordEncoder bCryptPasswordEncoder() { return new BCryptPasswordEncoder(); } @Override protected void configure(HttpSecurity http) throws Exception { http.csrf().disable() .authorizeRequests() .antMatchers("/api/auth/**").permitAll() .anyRequest().authenticated(); http.addFilterBefore(jwtAuthTokenFilter, UsernamePasswordAuthenticationFilter.class); } } ``` 现在,Spring Security将使用JWT来验证用户的身份和权限。您可以在需要身份验证和授权的端点上使用Spring Security注释,例如@PreAuthorize和@PostAuthorize。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

可为编程

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值