查看原文
其他

mall整合SpringSecurity和JWT实现认证和授权(一)

梦想de星空 macrozheng 2020-08-20
来自专辑
mall学习教程(架构篇)

本文主要讲解mall通过整合SpringSecurity和JWT实现后台用户的登录和授权功能,同时改造Swagger-UI的配置使其可以自动记住登录令牌进行发送。

项目使用框架介绍

SpringSecurity

SpringSecurity是一个强大的可高度定制的认证和授权框架,对于Spring应用来说它是一套Web安全标准。SpringSecurity注重于为Java应用提供认证和授权功能,像所有的Spring项目一样,它对自定义需求具有强大的扩展性。

JWT

JWT是JSON WEB TOKEN的缩写,它是基于 RFC 7519 标准定义的一种可以安全传输的的JSON对象,由于使用了数字签名,所以是可信任和安全的。

JWT的组成

  • JWT token的格式:header.payload.signature

  • header中用于存放签名的生成算法

  1. {"alg": "HS512"}

  • payload中用于存放用户名、token的生成时间和过期时间

  1. {"sub":"admin","created":1489079981393,"exp":1489684781}

  • signature为以header和payload生成的签名,一旦header和payload被篡改,验证将失败

  1. //secret为加密算法的密钥

  2. String signature = HMACSHA512(base64UrlEncode(header) + "." +base64UrlEncode(payload),secret)

JWT实例

这是一个JWT的字符串

  1. eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJhZG1pbiIsImNyZWF0ZWQiOjE1NTY3NzkxMjUzMDksImV4cCI6MTU1NzM4MzkyNX0.d-iki0193X0bBOETf2UN3r3PotNIEAV7mzIxxeI5IxFyzzkOZxS0PGfF_SK6wxCv2K8S0cZjMkv6b5bCqc0VBw

可以在该网站上获得解析结果:https://jwt.io/

JWT实现认证和授权的原理

  • 用户调用登录接口,登录成功后获取到JWT的token;

  • 之后用户每次调用接口都在http的header中添加一个叫Authorization的头,值为JWT的token;

  • 后台程序通过对Authorization头中信息的解码及数字签名校验来获取其中的用户信息,从而实现认证和授权。

Hutool

Hutool是一个丰富的Java开源工具包,它帮助我们简化每一行代码,减少每一个方法,mall项目采用了此工具包。

项目使用表说明

  • ums_admin:后台用户表

  • ums_role:后台用户角色表

  • ums_permission:后台用户权限表

  • ums_admin_role_relation:后台用户和角色关系表,用户与角色是多对多关系

  • ums_role_permission_relation:后台用户角色和权限关系表,角色与权限是多对多关系

  • ums_admin_permission_relation:后台用户和权限关系表(除角色中定义的权限以外的加减权限),加权限是指用户比角色多出的权限,减权限是指用户比角色少的权限

整合SpringSecurity及JWT

在pom.xml中添加项目依赖

  1. <!--SpringSecurity依赖配置-->

  2. <dependency>

  3. <groupId>org.springframework.boot</groupId>

  4. <artifactId>spring-boot-starter-security</artifactId>

  5. </dependency>

  6. <!--Hutool Java工具包-->

  7. <dependency>

  8. <groupId>cn.hutool</groupId>

  9. <artifactId>hutool-all</artifactId>

  10. <version>4.5.7</version>

  11. </dependency>

  12. <!--JWT(Json Web Token)登录支持-->

  13. <dependency>

  14. <groupId>io.jsonwebtoken</groupId>

  15. <artifactId>jjwt</artifactId>

  16. <version>0.9.0</version>

  17. </dependency>

添加JWT token的工具类

用于生成和解析JWT token的工具类

相关方法说明:

  • generateToken(UserDetails userDetails) :用于根据登录用户信息生成token

  • getUserNameFromToken(String token):从token中获取登录用户的信息

  • validateToken(String token, UserDetails userDetails):判断token是否还有效

  1. package com.macro.mall.tiny.common.utils;


  2. import io.jsonwebtoken.Claims;

  3. import io.jsonwebtoken.Jwts;

  4. import io.jsonwebtoken.SignatureAlgorithm;

  5. import org.slf4j.Logger;

  6. import org.slf4j.LoggerFactory;

  7. import org.springframework.beans.factory.annotation.Value;

  8. import org.springframework.security.core.userdetails.UserDetails;

  9. import org.springframework.stereotype.Component;


  10. import java.util.Date;

  11. import java.util.HashMap;

  12. import java.util.Map;


  13. /**

  14. * JwtToken生成的工具类

  15. * Created by macro on 2018/4/26.

  16. */

  17. @Component

  18. public class JwtTokenUtil {

  19. private static final Logger LOGGER = LoggerFactory.getLogger(JwtTokenUtil.class);

  20. private static final String CLAIM_KEY_USERNAME = "sub";

  21. private static final String CLAIM_KEY_CREATED = "created";

  22. @Value("${jwt.secret}")

  23. private String secret;

  24. @Value("${jwt.expiration}")

  25. private Long expiration;


  26. /**

  27. * 根据负责生成JWT的token

  28. */

  29. private String generateToken(Map<String, Object> claims) {

  30. return Jwts.builder()

  31. .setClaims(claims)

  32. .setExpiration(generateExpirationDate())

  33. .signWith(SignatureAlgorithm.HS512, secret)

  34. .compact();

  35. }


  36. /**

  37. * 从token中获取JWT中的负载

  38. */

  39. private Claims getClaimsFromToken(String token) {

  40. Claims claims = null;

  41. try {

  42. claims = Jwts.parser()

  43. .setSigningKey(secret)

  44. .parseClaimsJws(token)

  45. .getBody();

  46. } catch (Exception e) {

  47. LOGGER.info("JWT格式验证失败:{}",token);

  48. }

  49. return claims;

  50. }


  51. /**

  52. * 生成token的过期时间

  53. */

  54. private Date generateExpirationDate() {

  55. return new Date(System.currentTimeMillis() + expiration * 1000);

  56. }


  57. /**

  58. * 从token中获取登录用户名

  59. */

  60. public String getUserNameFromToken(String token) {

  61. String username;

  62. try {

  63. Claims claims = getClaimsFromToken(token);

  64. username = claims.getSubject();

  65. } catch (Exception e) {

  66. username = null;

  67. }

  68. return username;

  69. }


  70. /**

  71. * 验证token是否还有效

  72. *

  73. * @param token 客户端传入的token

  74. * @param userDetails 从数据库中查询出来的用户信息

  75. */

  76. public boolean validateToken(String token, UserDetails userDetails) {

  77. String username = getUserNameFromToken(token);

  78. return username.equals(userDetails.getUsername()) && !isTokenExpired(token);

  79. }


  80. /**

  81. * 判断token是否已经失效

  82. */

  83. private boolean isTokenExpired(String token) {

  84. Date expiredDate = getExpiredDateFromToken(token);

  85. return expiredDate.before(new Date());

  86. }


  87. /**

  88. * 从token中获取过期时间

  89. */

  90. private Date getExpiredDateFromToken(String token) {

  91. Claims claims = getClaimsFromToken(token);

  92. return claims.getExpiration();

  93. }


  94. /**

  95. * 根据用户信息生成token

  96. */

  97. public String generateToken(UserDetails userDetails) {

  98. Map<String, Object> claims = new HashMap<>();

  99. claims.put(CLAIM_KEY_USERNAME, userDetails.getUsername());

  100. claims.put(CLAIM_KEY_CREATED, new Date());

  101. return generateToken(claims);

  102. }


  103. /**

  104. * 判断token是否可以被刷新

  105. */

  106. public boolean canRefresh(String token) {

  107. return !isTokenExpired(token);

  108. }


  109. /**

  110. * 刷新token

  111. */

  112. public String refreshToken(String token) {

  113. Claims claims = getClaimsFromToken(token);

  114. claims.put(CLAIM_KEY_CREATED, new Date());

  115. return generateToken(claims);

  116. }

  117. }

添加SpringSecurity的配置类

  1. package com.macro.mall.tiny.config;


  2. import com.macro.mall.tiny.component.JwtAuthenticationTokenFilter;

  3. import com.macro.mall.tiny.component.RestAuthenticationEntryPoint;

  4. import com.macro.mall.tiny.component.RestfulAccessDeniedHandler;

  5. import com.macro.mall.tiny.dto.AdminUserDetails;

  6. import com.macro.mall.tiny.mbg.model.UmsAdmin;

  7. import com.macro.mall.tiny.mbg.model.UmsPermission;

  8. import com.macro.mall.tiny.service.UmsAdminService;

  9. import org.springframework.beans.factory.annotation.Autowired;

  10. import org.springframework.context.annotation.Bean;

  11. import org.springframework.context.annotation.Configuration;

  12. import org.springframework.http.HttpMethod;

  13. import org.springframework.security.authentication.AuthenticationManager;

  14. import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;

  15. import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;

  16. import org.springframework.security.config.annotation.web.builders.HttpSecurity;

  17. import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;

  18. import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

  19. import org.springframework.security.config.http.SessionCreationPolicy;

  20. import org.springframework.security.core.userdetails.UserDetailsService;

  21. import org.springframework.security.core.userdetails.UsernameNotFoundException;

  22. import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

  23. import org.springframework.security.crypto.password.PasswordEncoder;

  24. import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;


  25. import java.util.List;



  26. /**

  27. * SpringSecurity的配置

  28. * Created by macro on 2018/4/26.

  29. */

  30. @Configuration

  31. @EnableWebSecurity

  32. @EnableGlobalMethodSecurity(prePostEnabled=true)

  33. public class SecurityConfig extends WebSecurityConfigurerAdapter {

  34. @Autowired

  35. private UmsAdminService adminService;

  36. @Autowired

  37. private RestfulAccessDeniedHandler restfulAccessDeniedHandler;

  38. @Autowired

  39. private RestAuthenticationEntryPoint restAuthenticationEntryPoint;


  40. @Override

  41. protected void configure(HttpSecurity httpSecurity) throws Exception {

  42. httpSecurity.csrf()// 由于使用的是JWT,我们这里不需要csrf

  43. .disable()

  44. .sessionManagement()// 基于token,所以不需要session

  45. .sessionCreationPolicy(SessionCreationPolicy.STATELESS)

  46. .and()

  47. .authorizeRequests()

  48. .antMatchers(HttpMethod.GET, // 允许对于网站静态资源的无授权访问

  49. "/",

  50. "/*.html",

  51. "/favicon.ico",

  52. "/**/*.html",

  53. "/**/*.css",

  54. "/**/*.js",

  55. "/swagger-resources/**",

  56. "/v2/api-docs/**"

  57. )

  58. .permitAll()

  59. .antMatchers("/admin/login", "/admin/register")// 对登录注册要允许匿名访问

  60. .permitAll()

  61. .antMatchers(HttpMethod.OPTIONS)//跨域请求会先进行一次options请求

  62. .permitAll()

  63. // .antMatchers("/**")//测试时全部运行访问

  64. // .permitAll()

  65. .anyRequest()// 除上面外的所有请求全部需要鉴权认证

  66. .authenticated();

  67. // 禁用缓存

  68. httpSecurity.headers().cacheControl();

  69. // 添加JWT filter

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

  71. //添加自定义未授权和未登录结果返回

  72. httpSecurity.exceptionHandling()

  73. .accessDeniedHandler(restfulAccessDeniedHandler)

  74. .authenticationEntryPoint(restAuthenticationEntryPoint);

  75. }


  76. @Override

  77. protected void configure(AuthenticationManagerBuilder auth) throws Exception {

  78. auth.userDetailsService(userDetailsService())

  79. .passwordEncoder(passwordEncoder());

  80. }


  81. @Bean

  82. public PasswordEncoder passwordEncoder() {

  83. return new BCryptPasswordEncoder();

  84. }


  85. @Bean

  86. public UserDetailsService userDetailsService() {

  87. //获取登录用户信息

  88. return username -> {

  89. UmsAdmin admin = adminService.getAdminByUsername(username);

  90. if (admin != null) {

  91. List<UmsPermission> permissionList = adminService.getPermissionList(admin.getId());

  92. return new AdminUserDetails(admin,permissionList);

  93. }

  94. throw new UsernameNotFoundException("用户名或密码错误");

  95. };

  96. }


  97. @Bean

  98. public JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter(){

  99. return new JwtAuthenticationTokenFilter();

  100. }


  101. @Bean

  102. @Override

  103. public AuthenticationManager authenticationManagerBean() throws Exception {

  104. return super.authenticationManagerBean();

  105. }


  106. }

相关依赖及方法说明

  • configure(HttpSecurity httpSecurity):用于配置需要拦截的url路径、jwt过滤器及出异常后的处理器;

  • configure(AuthenticationManagerBuilder auth):用于配置UserDetailsService及PasswordEncoder;

  • RestfulAccessDeniedHandler:当用户没有访问权限时的处理器,用于返回JSON格式的处理结果;

  • RestAuthenticationEntryPoint:当未登录或token失效时,返回JSON格式的结果;

  • UserDetailsService:SpringSecurity定义的核心接口,用于根据用户名获取用户信息,需要自行实现;

  • UserDetails:SpringSecurity定义用于封装用户信息的类(主要是用户信息和权限),需要自行实现;

  • PasswordEncoder:SpringSecurity定义的用于对密码进行编码及比对的接口,目前使用的是BCryptPasswordEncoder;

  • JwtAuthenticationTokenFilter:在用户名和密码校验前添加的过滤器,如果有jwt的token,会自行根据token信息进行登录。

添加RestfulAccessDeniedHandler

  1. package com.macro.mall.tiny.component;


  2. import cn.hutool.json.JSONUtil;

  3. import com.macro.mall.tiny.common.api.CommonResult;

  4. import org.springframework.security.access.AccessDeniedException;

  5. import org.springframework.security.web.access.AccessDeniedHandler;

  6. import org.springframework.stereotype.Component;


  7. import javax.servlet.ServletException;

  8. import javax.servlet.http.HttpServletRequest;

  9. import javax.servlet.http.HttpServletResponse;

  10. import java.io.IOException;


  11. /**

  12. * 当访问接口没有权限时,自定义的返回结果

  13. * Created by macro on 2018/4/26.

  14. */

  15. @Component

  16. public class RestfulAccessDeniedHandler implements AccessDeniedHandler{

  17. @Override

  18. public void handle(HttpServletRequest request,

  19. HttpServletResponse response,

  20. AccessDeniedException e) throws IOException, ServletException {

  21. response.setCharacterEncoding("UTF-8");

  22. response.setContentType("application/json");

  23. response.getWriter().println(JSONUtil.parse(CommonResult.forbidden(e.getMessage())));

  24. response.getWriter().flush();

  25. }

  26. }

添加RestAuthenticationEntryPoint

  1. package com.macro.mall.tiny.component;


  2. import cn.hutool.json.JSONUtil;

  3. import com.macro.mall.tiny.common.api.CommonResult;

  4. import org.springframework.security.core.AuthenticationException;

  5. import org.springframework.security.web.AuthenticationEntryPoint;

  6. import org.springframework.stereotype.Component;


  7. import javax.servlet.ServletException;

  8. import javax.servlet.http.HttpServletRequest;

  9. import javax.servlet.http.HttpServletResponse;

  10. import java.io.IOException;


  11. /**

  12. * 当未登录或者token失效访问接口时,自定义的返回结果

  13. * Created by macro on 2018/5/14.

  14. */

  15. @Component

  16. public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint {

  17. @Override

  18. public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {

  19. response.setCharacterEncoding("UTF-8");

  20. response.setContentType("application/json");

  21. response.getWriter().println(JSONUtil.parse(CommonResult.unauthorized(authException.getMessage())));

  22. response.getWriter().flush();

  23. }

  24. }

添加AdminUserDetails

  1. package com.macro.mall.tiny.dto;


  2. import com.macro.mall.tiny.mbg.model.UmsAdmin;

  3. import com.macro.mall.tiny.mbg.model.UmsPermission;

  4. import org.springframework.security.core.GrantedAuthority;

  5. import org.springframework.security.core.authority.SimpleGrantedAuthority;

  6. import org.springframework.security.core.userdetails.UserDetails;


  7. import java.util.Collection;

  8. import java.util.List;

  9. import java.util.stream.Collectors;


  10. /**

  11. * SpringSecurity需要的用户详情

  12. * Created by macro on 2018/4/26.

  13. */

  14. public class AdminUserDetails implements UserDetails {

  15. private UmsAdmin umsAdmin;

  16. private List<UmsPermission> permissionList;

  17. public AdminUserDetails(UmsAdmin umsAdmin, List<UmsPermission> permissionList) {

  18. this.umsAdmin = umsAdmin;

  19. this.permissionList = permissionList;

  20. }


  21. @Override

  22. public Collection<? extends GrantedAuthority> getAuthorities() {

  23. //返回当前用户的权限

  24. return permissionList.stream()

  25. .filter(permission -> permission.getValue()!=null)

  26. .map(permission ->new SimpleGrantedAuthority(permission.getValue()))

  27. .collect(Collectors.toList());

  28. }


  29. @Override

  30. public String getPassword() {

  31. return umsAdmin.getPassword();

  32. }


  33. @Override

  34. public String getUsername() {

  35. return umsAdmin.getUsername();

  36. }


  37. @Override

  38. public boolean isAccountNonExpired() {

  39. return true;

  40. }


  41. @Override

  42. public boolean isAccountNonLocked() {

  43. return true;

  44. }


  45. @Override

  46. public boolean isCredentialsNonExpired() {

  47. return true;

  48. }


  49. @Override

  50. public boolean isEnabled() {

  51. return umsAdmin.getStatus().equals(1);

  52. }

  53. }

添加JwtAuthenticationTokenFilter

在用户名和密码校验前添加的过滤器,如果请求中有jwt的token且有效,会取出token中的用户名,然后调用SpringSecurity的API进行登录操作。

  1. package com.macro.mall.tiny.component;


  2. import com.macro.mall.tiny.common.utils.JwtTokenUtil;

  3. import org.slf4j.Logger;

  4. import org.slf4j.LoggerFactory;

  5. import org.springframework.beans.factory.annotation.Autowired;

  6. import org.springframework.beans.factory.annotation.Value;

  7. import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;

  8. import org.springframework.security.core.context.SecurityContextHolder;

  9. import org.springframework.security.core.userdetails.UserDetails;

  10. import org.springframework.security.core.userdetails.UserDetailsService;

  11. import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;

  12. import org.springframework.web.filter.OncePerRequestFilter;


  13. import javax.servlet.FilterChain;

  14. import javax.servlet.ServletException;

  15. import javax.servlet.http.HttpServletRequest;

  16. import javax.servlet.http.HttpServletResponse;

  17. import java.io.IOException;


  18. /**

  19. * JWT登录授权过滤器

  20. * Created by macro on 2018/4/26.

  21. */

  22. public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

  23. private static final Logger LOGGER = LoggerFactory.getLogger(JwtAuthenticationTokenFilter.class);

  24. @Autowired

  25. private UserDetailsService userDetailsService;

  26. @Autowired

  27. private JwtTokenUtil jwtTokenUtil;

  28. @Value("${jwt.tokenHeader}")

  29. private String tokenHeader;

  30. @Value("${jwt.tokenHead}")

  31. private String tokenHead;


  32. @Override

  33. protected void doFilterInternal(HttpServletRequest request,

  34. HttpServletResponse response,

  35. FilterChain chain) throws ServletException, IOException {

  36. String authHeader = request.getHeader(this.tokenHeader);

  37. if (authHeader != null && authHeader.startsWith(this.tokenHead)) {

  38. String authToken = authHeader.substring(this.tokenHead.length());// The part after "Bearer "

  39. String username = jwtTokenUtil.getUserNameFromToken(authToken);

  40. LOGGER.info("checking username:{}", username);

  41. if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {

  42. UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);

  43. if (jwtTokenUtil.validateToken(authToken, userDetails)) {

  44. UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());

  45. authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));

  46. LOGGER.info("authenticated user:{}", username);

  47. SecurityContextHolder.getContext().setAuthentication(authentication);

  48. }

  49. }

  50. }

  51. chain.doFilter(request, response);

  52. }

  53. }

项目源码地址

https://github.com/macrozheng/mall-learning/tree/master/mall-tiny-04

推荐阅读



欢迎关注,点个在看


    您可能也对以下帖子感兴趣

    文章有问题?点此查看未经处理的缓存