当前位置:   article > 正文

Spring Boot2 + Spring Security + JWT 实现项目级前后端分离认证授权_spring-boot-starter-security jwt

spring-boot-starter-security jwt

一 简介

Spring SecuritySpring 家族中的一个安全管理框架。相比与另外一个安全框架 Shiro,它提供了更丰富的功能,扩展性更好,社区资源也比 Shiro 丰富。在 Spring Boot 出现之前,Spring Security 就已经发展了多年了,但是使用的并不多,安全管理这个领域,一直是 Shiro 的天下。
相对于 Shiro,在 SSM/SSH 中整合 Spring Security 都是比较麻烦的操作,所以 Spring Security 虽然功能比 Shiro 强大,但是使用反而没有 Shiro 多(Shiro 虽然功能没有 Spring Security 多,但是对于大部分项目而言,Shiro 上手简单也够用了)。
自从有了 Spring Boot 之后,Spring Boot 对于 Spring Security 提供了 自动化配置方案,可以零配置使用 Spring Security。

一般 WEB 应用的需要进行认证和授权。

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

常见的安全管理技术栈的组合是这样的:

  • SSM + Shiro
  • Spring Boot/Spring Cloud + Spring Security

注意:这只是一个推荐的组合而已,如果单纯从技术上来说,无论怎么组合,都是可以运行的。

二 实际使用

项目技术:Spring Boo2 、Spring Security、MyBatis、MySQL

项目结构:

2.1 pom.xml

  1. <!-- spring security 安全认证 -->
  2. <dependency>
  3. <groupId>org.springframework.boot</groupId>
  4. <artifactId>spring-boot-starter-security</artifactId>
  5. </dependency>
  6. <!--Token生成与解析-->
  7. <dependency>
  8. <groupId>io.jsonwebtoken</groupId>
  9. <artifactId>jjwt</artifactId>
  10. <version>0.9.0</version>
  11. </dependency>

2.2 application.properties

  1. # jwt token配置
  2. # 令牌自定义标识
  3. jwt.token.header=token
  4. # 令牌秘钥
  5. jwt.token.secret=abcdefghijklmnopqrstuvwxyz
  6. # 令牌有效期(默认30分钟)
  7. jwt.token.expireTime=30

2.3 JwtToken工具类

  1. package com.modules.security;
  2. import io.jsonwebtoken.Claims;
  3. import io.jsonwebtoken.Jwts;
  4. import io.jsonwebtoken.SignatureAlgorithm;
  5. import lombok.extern.slf4j.Slf4j;
  6. import org.springframework.beans.factory.annotation.Value;
  7. import org.springframework.security.core.userdetails.UserDetails;
  8. import org.springframework.stereotype.Component;
  9. import javax.servlet.http.HttpServletRequest;
  10. import java.util.Date;
  11. import java.util.HashMap;
  12. import java.util.Map;
  13. /**
  14. * @ClassName JwtTokenUtil
  15. * @Description JwtToken生成的工具类
  16. * @Author li'chao
  17. * @Date 2022-3-8 17:17
  18. * @Version 1.0
  19. **/
  20. @Slf4j
  21. @Component
  22. public class JwtTokenUtil {
  23. private static final String CLAIM_KEY_USERNAME = "sub";
  24. private static final String CLAIM_KEY_CREATED = "created";
  25. // 令牌自定义标识
  26. @Value("${jwt.token.header}")
  27. private String header;
  28. // 令牌秘钥
  29. @Value("${jwt.token.secret}")
  30. private String secret;
  31. // 令牌有效期(默认30分钟)
  32. @Value("${jwt.token.expireTime}")
  33. private Long expiration;
  34. /**
  35. * 根据负责生成JWT的token
  36. */
  37. private String generateToken(Map<String, Object> claims) {
  38. return Jwts.builder()
  39. .setClaims(claims)
  40. .setExpiration(generateExpirationDate())
  41. .signWith(SignatureAlgorithm.HS512, secret)
  42. .compact();
  43. }
  44. /**
  45. * 从token中获取JWT中的负载
  46. */
  47. private Claims getClaimsFromToken(String token) {
  48. Claims claims = null;
  49. try {
  50. claims = Jwts.parser()
  51. .setSigningKey(secret)
  52. .parseClaimsJws(token)
  53. .getBody();
  54. } catch (Exception e) {
  55. log.info("JWT格式验证失败:{}",token);
  56. }
  57. return claims;
  58. }
  59. /**
  60. * 生成token的过期时间
  61. */
  62. private Date generateExpirationDate() {
  63. return new Date(System.currentTimeMillis() + expiration * 1000);
  64. }
  65. /**
  66. * 从token中获取登录用户名
  67. */
  68. public String getUserNameFromToken(String token) {
  69. String username;
  70. try {
  71. Claims claims = getClaimsFromToken(token);
  72. username = claims.getSubject();
  73. } catch (Exception e) {
  74. username = null;
  75. }
  76. return username;
  77. }
  78. /**
  79. * 验证token是否还有效
  80. *
  81. * @param token 客户端传入的token
  82. * @param userDetails 从数据库中查询出来的用户信息
  83. */
  84. public boolean validateToken(String token, UserDetails userDetails) {
  85. String username = getUserNameFromToken(token);
  86. return username.equals(userDetails.getUsername()) && !isTokenExpired(token);
  87. }
  88. /**
  89. * 判断token是否已经失效
  90. */
  91. public boolean isTokenExpired(String token) {
  92. Date expiredDate = getExpiredDateFromToken(token);
  93. return expiredDate.before(new Date());
  94. }
  95. /**
  96. * 从token中获取过期时间
  97. */
  98. private Date getExpiredDateFromToken(String token) {
  99. Claims claims = getClaimsFromToken(token);
  100. return claims.getExpiration();
  101. }
  102. /**
  103. * 根据用户信息生成token
  104. */
  105. public String generateToken(UserDetails userDetails) {
  106. Map<String, Object> claims = new HashMap<>();
  107. claims.put(CLAIM_KEY_USERNAME, userDetails.getUsername());
  108. claims.put(CLAIM_KEY_CREATED, new Date());
  109. return generateToken(claims);
  110. }
  111. /**
  112. * 根据用户信息生成token
  113. */
  114. public String generateToken(LoginUser loginUser) {
  115. Map<String, Object> claims = new HashMap<>();
  116. claims.put(CLAIM_KEY_USERNAME, loginUser.getUsername());
  117. claims.put(CLAIM_KEY_CREATED, new Date());
  118. return generateToken(claims);
  119. }
  120. /**
  121. * 判断token是否可以被刷新
  122. */
  123. public boolean canRefresh(String token) {
  124. return !isTokenExpired(token);
  125. }
  126. /**
  127. * 刷新token
  128. */
  129. public String refreshToken(String token) {
  130. Claims claims = getClaimsFromToken(token);
  131. claims.put(CLAIM_KEY_CREATED, new Date());
  132. return generateToken(claims);
  133. }
  134. /**
  135. * 获取请求token
  136. *
  137. * @param request
  138. * @return token
  139. */
  140. public String getToken(HttpServletRequest request)
  141. {
  142. return request.getHeader(header);
  143. }
  144. }

2.4 自定义权限不足处理类

  1. package com.modules.security.handle;
  2. import com.alibaba.fastjson.JSON;
  3. import com.modules.common.utils.ServletUtils;
  4. import com.modules.common.web.Result;
  5. import org.springframework.security.access.AccessDeniedException;
  6. import org.springframework.security.web.access.AccessDeniedHandler;
  7. import org.springframework.stereotype.Component;
  8. import javax.servlet.ServletException;
  9. import javax.servlet.http.HttpServletRequest;
  10. import javax.servlet.http.HttpServletResponse;
  11. import java.io.IOException;
  12. /**
  13. * 当访问接口没有权限时,自定义的返回结果
  14. *
  15. * @author li'chao
  16. */
  17. @Component
  18. public class AccessDeniedHandlerImpl implements AccessDeniedHandler {
  19. @Override
  20. public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException e) throws IOException, ServletException {
  21. ServletUtils.renderString(response, JSON.toJSONString(Result.unauth("权限不足")));
  22. }
  23. }

2.5 自定义认证失败处理类

  1. package com.modules.security.handle;
  2. import com.alibaba.fastjson.JSON;
  3. import com.modules.common.utils.ServletUtils;
  4. import com.modules.common.web.Result;
  5. import org.springframework.security.core.AuthenticationException;
  6. import org.springframework.security.web.AuthenticationEntryPoint;
  7. import org.springframework.stereotype.Component;
  8. import javax.servlet.ServletException;
  9. import javax.servlet.http.HttpServletRequest;
  10. import javax.servlet.http.HttpServletResponse;
  11. import java.io.IOException;
  12. /**
  13. * 认证失败处理类 自定义返回未授权
  14. *
  15. * @author li'chao
  16. */
  17. @Component
  18. public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint
  19. {
  20. @Override
  21. public void commence(HttpServletRequest equest, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
  22. ServletUtils.renderString(response, JSON.toJSONString(Result.auth("token认证失败")));
  23. }
  24. }

2.6 自定义 token 验证类

  1. package com.modules.security.handle;
  2. import com.alibaba.fastjson.JSON;
  3. import com.modules.common.utils.ServletUtils;
  4. import com.modules.common.web.Result;
  5. import org.springframework.security.core.AuthenticationException;
  6. import org.springframework.security.web.AuthenticationEntryPoint;
  7. import org.springframework.stereotype.Component;
  8. import javax.servlet.ServletException;
  9. import javax.servlet.http.HttpServletRequest;
  10. import javax.servlet.http.HttpServletResponse;
  11. import java.io.IOException;
  12. /**
  13. * 认证失败处理类 自定义返回未授权
  14. *
  15. * @author li'chao
  16. */
  17. @Component
  18. public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint
  19. {
  20. @Override
  21. public void commence(HttpServletRequest equest, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
  22. ServletUtils.renderString(response, JSON.toJSONString(Result.auth("token认证失败")));
  23. }
  24. }

2.7 自定义登录处理

  1. package com.modules.security;
  2. import com.fasterxml.jackson.annotation.JsonIgnore;
  3. import com.modules.system.entity.SysUser;
  4. import org.springframework.security.core.GrantedAuthority;
  5. import org.springframework.security.core.userdetails.UserDetails;
  6. import java.util.Collection;
  7. import java.util.Set;
  8. /**
  9. * 登录用户身份权限
  10. *
  11. * @author li'chao
  12. */
  13. public class LoginUser implements UserDetails
  14. {
  15. private static final long serialVersionUID = 1L;
  16. /**
  17. * 用户唯一标识
  18. */
  19. private String token;
  20. /**
  21. * 登陆时间
  22. */
  23. private Long loginTime;
  24. /**
  25. * 过期时间
  26. */
  27. private Long expireTime;
  28. /**
  29. * 登录IP地址
  30. */
  31. private String ipaddr;
  32. /**
  33. * 登录地点
  34. */
  35. private String loginLocation;
  36. /**
  37. * 浏览器类型
  38. */
  39. private String browser;
  40. /**
  41. * 操作系统
  42. */
  43. private String os;
  44. /**
  45. * 权限列表
  46. */
  47. private Set<String> permissions;
  48. /**
  49. * 用户信息
  50. */
  51. private SysUser user;
  52. public String getToken()
  53. {
  54. return token;
  55. }
  56. public void setToken(String token)
  57. {
  58. this.token = token;
  59. }
  60. public LoginUser()
  61. {
  62. }
  63. public LoginUser(SysUser user, Set<String> permissions)
  64. {
  65. this.user = user;
  66. this.permissions = permissions;
  67. }
  68. @JsonIgnore
  69. @Override
  70. public String getPassword()
  71. {
  72. return user.getPassword();
  73. }
  74. @Override
  75. public String getUsername()
  76. {
  77. return user.getUserName();
  78. }
  79. /**
  80. * 账户是否未过期,过期无法验证
  81. */
  82. @JsonIgnore
  83. @Override
  84. public boolean isAccountNonExpired()
  85. {
  86. return true;
  87. }
  88. /**
  89. * 指定用户是否解锁,锁定的用户无法进行身份验证
  90. *
  91. * @return
  92. */
  93. @JsonIgnore
  94. @Override
  95. public boolean isAccountNonLocked()
  96. {
  97. return true;
  98. }
  99. /**
  100. * 指示是否已过期的用户的凭据(密码),过期的凭据防止认证
  101. *
  102. * @return
  103. */
  104. @JsonIgnore
  105. @Override
  106. public boolean isCredentialsNonExpired()
  107. {
  108. return true;
  109. }
  110. /**
  111. * 是否可用 ,禁用的用户不能身份验证
  112. *
  113. * @return
  114. */
  115. @JsonIgnore
  116. @Override
  117. public boolean isEnabled()
  118. {
  119. return true;
  120. }
  121. public Long getLoginTime()
  122. {
  123. return loginTime;
  124. }
  125. public void setLoginTime(Long loginTime)
  126. {
  127. this.loginTime = loginTime;
  128. }
  129. public String getIpaddr()
  130. {
  131. return ipaddr;
  132. }
  133. public void setIpaddr(String ipaddr)
  134. {
  135. this.ipaddr = ipaddr;
  136. }
  137. public String getLoginLocation()
  138. {
  139. return loginLocation;
  140. }
  141. public void setLoginLocation(String loginLocation)
  142. {
  143. this.loginLocation = loginLocation;
  144. }
  145. public String getBrowser()
  146. {
  147. return browser;
  148. }
  149. public void setBrowser(String browser)
  150. {
  151. this.browser = browser;
  152. }
  153. public String getOs()
  154. {
  155. return os;
  156. }
  157. public void setOs(String os)
  158. {
  159. this.os = os;
  160. }
  161. public Long getExpireTime()
  162. {
  163. return expireTime;
  164. }
  165. public void setExpireTime(Long expireTime)
  166. {
  167. this.expireTime = expireTime;
  168. }
  169. public Set<String> getPermissions()
  170. {
  171. return permissions;
  172. }
  173. public void setPermissions(Set<String> permissions)
  174. {
  175. this.permissions = permissions;
  176. }
  177. public SysUser getUser()
  178. {
  179. return user;
  180. }
  181. public void setUser(SysUser user)
  182. {
  183. this.user = user;
  184. }
  185. @Override
  186. public Collection<? extends GrantedAuthority> getAuthorities()
  187. {
  188. return null;
  189. }
  190. }
  1. package com.modules.security.service;
  2. import com.modules.common.enmus.PublicEnum;
  3. import com.modules.common.exception.CustomException;
  4. import com.modules.common.utils.StringUtils;
  5. import com.modules.security.LoginUser;
  6. import com.modules.system.entity.SysUser;
  7. import com.modules.system.service.SysUserService;
  8. import lombok.extern.slf4j.Slf4j;
  9. import org.springframework.beans.factory.annotation.Autowired;
  10. import org.springframework.security.core.userdetails.UserDetails;
  11. import org.springframework.security.core.userdetails.UserDetailsService;
  12. import org.springframework.security.core.userdetails.UsernameNotFoundException;
  13. import org.springframework.stereotype.Service;
  14. /**
  15. * @ClassName UserDetailsServiceImpl
  16. * @Description 用户验证处理
  17. * @Author li'chao
  18. * @Date 2022-3-9 22:20
  19. * @Version 1.0
  20. **/
  21. @Slf4j
  22. @Service
  23. public class UserDetailsServiceImpl implements UserDetailsService {
  24. @Autowired
  25. private SysUserService sysUserService;
  26. /**
  27. * 登录信息验证
  28. * @param username
  29. * @return
  30. * @throws UsernameNotFoundException
  31. */
  32. @Override
  33. public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
  34. SysUser sysUser = sysUserService.selectUserByLoginName(username);
  35. if (StringUtils.isNull(sysUser))
  36. {
  37. log.info("登录用户:{} 不存在.", username);
  38. throw new UsernameNotFoundException("登录账号不存在");
  39. }
  40. else if (PublicEnum.DELETE.getCode().equals(sysUser.getStatus()))
  41. {
  42. log.info("登录用户:{} 已被删除.", username);
  43. throw new CustomException("账号已被删除");
  44. }
  45. else if (PublicEnum.DISABLE.getCode().equals(sysUser.getStatus()))
  46. {
  47. log.info("登录用户:{} 已被停用.", username);
  48. throw new CustomException("账号已停用");
  49. }
  50. return createLoginUser(sysUser);
  51. }
  52. public UserDetails createLoginUser(SysUser user)
  53. {
  54. return new LoginUser(user, null);
  55. }
  56. }
  1. package com.modules.security.service;
  2. import com.modules.security.JwtTokenUtil;
  3. import com.modules.security.LoginUser;
  4. import lombok.extern.slf4j.Slf4j;
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.security.authentication.AuthenticationManager;
  7. import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
  8. import org.springframework.security.core.Authentication;
  9. import org.springframework.stereotype.Service;
  10. /**
  11. * @ClassName LoginService
  12. * @Description 登录校验
  13. * @Author li'chao
  14. * @Date 2022-3-11 14:21
  15. * @Version 1.0
  16. **/
  17. @Slf4j
  18. @Service
  19. public class LoginService {
  20. @Autowired
  21. private AuthenticationManager authenticationManager;
  22. @Autowired
  23. private JwtTokenUtil jwtTokenUtil;
  24. /**
  25. * 登录验证
  26. *
  27. * @param username 用户名
  28. * @param password 密码
  29. * @return 结果
  30. */
  31. public LoginUser login(String username, String password) {
  32. String token = null;
  33. LoginUser loginUser = null;
  34. // 用户验证
  35. Authentication authentication = null;
  36. // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
  37. authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, password));
  38. loginUser = (LoginUser) authentication.getPrincipal();
  39. token = jwtTokenUtil.generateToken(loginUser);
  40. loginUser.setToken(token);
  41. return loginUser;
  42. }
  43. }
  1. package com.modules.common.web;
  2. import com.modules.common.utils.StringUtils;
  3. import java.util.HashMap;
  4. /**
  5. * 操作消息提醒
  6. *
  7. * @author lc
  8. */
  9. public class Result extends HashMap<String, Object> {
  10. private static final long serialVersionUID = 1L;
  11. public static final String CODE_TAG = "code";
  12. public static final String MSG_TAG = "msg";
  13. public static final String DATA_TAG = "data";
  14. public static final String success_Count = "successCount";
  15. public static final String fail_Count = "failCount";
  16. public static final String messCell_Count = "messCellCount";
  17. /**
  18. * 状态类型
  19. */
  20. public enum Type {
  21. /**
  22. * 成功
  23. */
  24. SUCCESS(200),
  25. /**
  26. * 警告
  27. */
  28. WARN(300),
  29. /**
  30. * 失败
  31. */
  32. FAIL(400),
  33. /**
  34. * 错误
  35. */
  36. ERROR(500),
  37. /**
  38. * 权限不足
  39. */
  40. UNAUTH(600),
  41. /**
  42. * token认证失败
  43. */
  44. AUTH(700);
  45. private final int value;
  46. Type(int value) {
  47. this.value = value;
  48. }
  49. public int value() {
  50. return this.value;
  51. }
  52. }
  53. /**
  54. * 初始化一个新创建的 Result 对象,使其表示一个空消息。
  55. *
  56. * @param type
  57. * @param msg
  58. * @param successCount
  59. * @param failCount
  60. * @param messCellCount
  61. * @param data
  62. */
  63. public Result(Type type, String msg, int successCount, int failCount, int messCellCount, Object data) {
  64. super.put(CODE_TAG, type.value);
  65. super.put(MSG_TAG, msg);
  66. if (StringUtils.isNotNull(data)) {
  67. super.put(DATA_TAG, data);
  68. }
  69. super.put(success_Count, successCount);
  70. super.put(fail_Count, failCount);
  71. super.put(messCell_Count, messCellCount);
  72. }
  73. /**
  74. * 初始化一个新创建的 Result 对象
  75. *
  76. * @param type 状态类型
  77. * @param msg 返回内容
  78. */
  79. public Result(Type type, String msg) {
  80. super.put(CODE_TAG, type.value);
  81. super.put(MSG_TAG, msg);
  82. }
  83. /**
  84. * 初始化一个新创建的 Result 对象
  85. *
  86. * @param type 状态类型
  87. * @param msg 返回内容
  88. * @param data 数据对象
  89. */
  90. public Result(Type type, Object msg, Object data) {
  91. super.put(CODE_TAG, type.value);
  92. super.put(MSG_TAG, msg);
  93. if (StringUtils.isNotNull(data)) {
  94. super.put(DATA_TAG, data);
  95. }
  96. }
  97. /**
  98. * 返回成功消息
  99. *
  100. * @return 成功消息
  101. */
  102. public static Result success() {
  103. return success("操作成功");
  104. }
  105. /**
  106. * 返回成功数据
  107. *
  108. * @return 成功消息
  109. */
  110. public static Result success(Object data) {
  111. return success("操作成功", data);
  112. }
  113. /**
  114. * 返回成功消息
  115. *
  116. * @param msg 返回内容
  117. * @return 成功消息
  118. */
  119. public static Result success(String msg) {
  120. return success(msg, null);
  121. }
  122. /**
  123. * 返回成功消息
  124. *
  125. * @param msg 返回内容
  126. * @param data 数据对象
  127. * @return 成功消息
  128. */
  129. public static Result success(String msg, Object data) {
  130. return new Result(Type.SUCCESS, msg, data);
  131. }
  132. /**
  133. * 返回成功消息
  134. *
  135. * @param msg 返回内容
  136. * @param data 数据对象
  137. * @param successCount 成功数据集条数
  138. * @param failCount 失败条数条数
  139. * @param messCellCount 异常单元格条数
  140. * @return 成功消息
  141. */
  142. public static Result success(String msg, int successCount, int failCount, int messCellCount, Object data) {
  143. return new Result(Type.SUCCESS, msg, successCount, failCount, messCellCount, data);
  144. }
  145. /**
  146. * 返回成功消息
  147. *
  148. * @param msg 返回内容
  149. * @param data 数据对象
  150. * @param successCount 成功数据集条数
  151. * @param failCount 失败条数条数
  152. * @param messCellCount 异常单元格条数
  153. * @return 失败消息
  154. */
  155. public static Result error(String msg, int successCount, int failCount, int messCellCount, Object data) {
  156. return new Result(Type.ERROR, msg, successCount, failCount, messCellCount, data);
  157. }
  158. /**
  159. * 返回警告消息
  160. *
  161. * @param msg 返回内容
  162. * @return 警告消息
  163. */
  164. public static Result warn(String msg) {
  165. return warn(msg, null);
  166. }
  167. /**
  168. * 返回警告消息
  169. *
  170. * @param msg 返回内容
  171. * @param data 数据对象
  172. * @return 警告消息
  173. */
  174. public static Result warn(String msg, Object data) {
  175. return new Result(Type.WARN, msg, data);
  176. }
  177. /**
  178. * 返回错误消息
  179. *
  180. * @return
  181. */
  182. public static Result error() {
  183. return error("操作失败");
  184. }
  185. /**
  186. * 返回错误消息
  187. *
  188. * @param msg 返回内容
  189. * @return 警告消息
  190. */
  191. public static Result error(Object msg) {
  192. return error(msg, null);
  193. }
  194. /**
  195. * 返回错误消息
  196. *
  197. * @param msg 返回内容
  198. * @param data 数据对象
  199. * @return 警告消息
  200. */
  201. public static Result error(Object msg, Object data) {
  202. return new Result(Type.ERROR, msg, data);
  203. }
  204. /**
  205. * 返回权限不足消息
  206. *
  207. * @return
  208. */
  209. public static Result unauth() {
  210. return error("权限不足");
  211. }
  212. /**
  213. * 返回权限不足消息
  214. *
  215. * @param msg 返回内容
  216. * @return 警告消息
  217. */
  218. public static Result unauth(String msg) {
  219. return error(msg, null);
  220. }
  221. /**
  222. * 返回无权限信息
  223. *
  224. * @param msg 返回内容
  225. * @param data 数据对象
  226. * @return 警告消息
  227. */
  228. public static Result unauth(String msg, Object data) {
  229. return new Result(Type.UNAUTH, msg, data);
  230. }
  231. /**
  232. * 返回token认证失败消息
  233. *
  234. * @return
  235. */
  236. public static Result auth() {
  237. return error("token认证失败");
  238. }
  239. /**
  240. * 返回token认证失败消息
  241. *
  242. * @param msg 返回内容
  243. * @return 警告消息
  244. */
  245. public static Result auth(String msg) {
  246. return error(msg, null);
  247. }
  248. /**
  249. * 返回token认证失败消息
  250. *
  251. * @param msg 返回内容
  252. * @param data 数据对象
  253. * @return 警告消息
  254. */
  255. public static Result auth(String msg, Object data) {
  256. return new Result(Type.AUTH, msg, data);
  257. }
  258. /**
  259. * 返回失败消息
  260. *
  261. * @return
  262. */
  263. public static Result fail()
  264. {
  265. return fail("操作失败");
  266. }
  267. /**
  268. * 返返回失败消息
  269. *
  270. * @param msg 返回内容
  271. * @return 警告消息
  272. */
  273. public static Result fail(String msg)
  274. {
  275. return fail(msg, null);
  276. }
  277. /**
  278. * 返回失败消息
  279. *
  280. * @param msg 返回内容
  281. * @param data 数据对象
  282. * @return 警告消息
  283. */
  284. public static Result fail(String msg, Object data)
  285. {
  286. return new Result(Type.FAIL, msg, data);
  287. }
  288. }

2.8 SpringSecurity 核心配置

  1. package com.modules.common.config;
  2. import com.modules.security.filter.JwtAuthenticationTokenFilter;
  3. import com.modules.security.handle.AccessDeniedHandlerImpl;
  4. import com.modules.security.handle.AuthenticationEntryPointImpl;
  5. import com.modules.security.handle.LogoutSuccessHandlerImpl;
  6. import org.springframework.beans.factory.annotation.Autowired;
  7. import org.springframework.context.annotation.Bean;
  8. import org.springframework.context.annotation.Configuration;
  9. import org.springframework.http.HttpMethod;
  10. import org.springframework.security.authentication.AuthenticationManager;
  11. import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
  12. import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
  13. import org.springframework.security.config.annotation.web.builders.HttpSecurity;
  14. import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
  15. import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
  16. import org.springframework.security.config.http.SessionCreationPolicy;
  17. import org.springframework.security.core.userdetails.UserDetailsService;
  18. import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
  19. import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
  20. import javax.annotation.Resource;
  21. /**
  22. * @ClassName SecurityConfig
  23. * @Description SpringSecurity的配置
  24. * @Author li'chao
  25. * @Date 2022-3-8 17:46
  26. * @Version 1.0
  27. **/
  28. @Configuration
  29. @EnableWebSecurity
  30. @EnableGlobalMethodSecurity(prePostEnabled=true)
  31. public class SecurityConfig extends WebSecurityConfigurerAdapter {
  32. /**
  33. * 自定义用户认证逻辑
  34. */
  35. @Resource
  36. private UserDetailsService userDetailsService;
  37. /**
  38. * 自定义权限不足处理类
  39. */
  40. @Autowired
  41. private AccessDeniedHandlerImpl accessDeniedHandler;
  42. /**
  43. * 自定义认证失败处理类
  44. */
  45. @Autowired
  46. private AuthenticationEntryPointImpl authenticationEntryPoint;
  47. /**
  48. * 自定义退出处理类
  49. */
  50. @Autowired
  51. private LogoutSuccessHandlerImpl logoutSuccessHandler;
  52. /**
  53. * token认证过滤器
  54. */
  55. @Autowired
  56. private JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;
  57. /**
  58. * 注入 AuthenticationManager
  59. *
  60. * @return
  61. * @throws Exception
  62. */
  63. @Bean
  64. @Override
  65. public AuthenticationManager authenticationManagerBean() throws Exception
  66. {
  67. return super.authenticationManagerBean();
  68. }
  69. /**
  70. * anyRequest | 匹配所有请求路径
  71. * access | SpringEl表达式结果为true时可以访问
  72. * anonymous | 匿名可以访问
  73. * denyAll | 用户不能访问
  74. * fullyAuthenticated | 用户完全认证可以访问(非remember-me下自动登录)
  75. * hasAnyAuthority | 如果有参数,参数表示权限,则其中任何一个权限可以访问
  76. * hasAnyRole | 如果有参数,参数表示角色,则其中任何一个角色可以访问
  77. * hasAuthority | 如果有参数,参数表示权限,则其权限可以访问
  78. * hasIpAddress | 如果有参数,参数表示IP地址,如果用户IP和参数匹配,则可以访问
  79. * hasRole | 如果有参数,参数表示角色,则其角色可以访问
  80. * permitAll | 用户可以任意访问
  81. * rememberMe | 允许通过remember-me登录的用户访问
  82. * authenticated | 用户登录后可访问
  83. */
  84. @Override
  85. protected void configure(HttpSecurity httpSecurity) throws Exception
  86. {
  87. httpSecurity
  88. // CRSF禁用,因为不使用session
  89. .csrf().disable()
  90. .exceptionHandling()
  91. // 认证失败处理类
  92. .authenticationEntryPoint(authenticationEntryPoint)
  93. // 权限不足处理类
  94. .accessDeniedHandler(accessDeniedHandler)
  95. .and()
  96. // 基于token,所以不需要session
  97. .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
  98. // 过滤请求
  99. .authorizeRequests()
  100. // 对于登录login 验证码captchaImage 允许匿名访问
  101. .antMatchers("/user/**", "/captchaImage").anonymous()
  102. .antMatchers(
  103. HttpMethod.GET,
  104. "/*.html",
  105. "/**/*.html",
  106. "/**/*.css",
  107. "/**/*.js"
  108. ).permitAll()
  109. .antMatchers("/profile/**").anonymous()
  110. .antMatchers("/common/download**").anonymous()
  111. .antMatchers("/common/download/resource**").anonymous()
  112. .antMatchers("/swagger-ui.html").anonymous()
  113. .antMatchers("/swagger-resources/**").anonymous()
  114. .antMatchers("/webjars/**").anonymous()
  115. .antMatchers("/*/api-docs").anonymous()
  116. .antMatchers("/druid/**").anonymous()
  117. // 除上面外的所有请求全部需要鉴权认证
  118. .anyRequest().authenticated()
  119. .and()
  120. .headers().frameOptions().disable();
  121. httpSecurity.logout().logoutUrl("/logout").logoutSuccessHandler(logoutSuccessHandler);
  122. // 添加JWT filter
  123. httpSecurity.addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
  124. }
  125. /**
  126. * 自定义身份认证
  127. */
  128. @Override
  129. protected void configure(AuthenticationManagerBuilder builder) throws Exception
  130. {
  131. builder.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder());
  132. }
  133. /**
  134. * 强散列哈希加密实现密码加密
  135. */
  136. @Bean
  137. public BCryptPasswordEncoder bCryptPasswordEncoder()
  138. {
  139. return new BCryptPasswordEncoder();
  140. }
  141. }

2.9 登录控制类

  1. package com.modules.system.controller;
  2. import com.modules.common.aspectj.Log;
  3. import com.modules.common.enmus.BusinessType;
  4. import com.modules.common.web.BaseController;
  5. import com.modules.common.web.Result;
  6. import com.modules.security.service.LoginService;
  7. import io.swagger.annotations.Api;
  8. import io.swagger.annotations.ApiOperation;
  9. import io.swagger.annotations.ApiParam;
  10. import lombok.extern.slf4j.Slf4j;
  11. import org.springframework.beans.factory.annotation.Autowired;
  12. import org.springframework.security.authentication.BadCredentialsException;
  13. import org.springframework.web.bind.annotation.*;
  14. import javax.servlet.http.HttpServletRequest;
  15. /**
  16. * 登录管理
  17. *
  18. * @author lc
  19. */
  20. @Api(tags = "登录管理")
  21. @Slf4j
  22. @CrossOrigin
  23. @RestController
  24. @RequestMapping("/user")
  25. public class LoginController extends BaseController {
  26. @Autowired
  27. private LoginService loginService;
  28. @Log(title = "用户登录", businessType = BusinessType.LOGIN)
  29. @ApiOperation(value = "用户登录", notes = "用户登录")
  30. @PostMapping(value = "/login")
  31. public Result login(HttpServletRequest request,
  32. @ApiParam(name = "loginName", value = "登录账号") @RequestParam(value = "loginName", required = true) String loginName,
  33. @ApiParam(name = "password", value = "密码") @RequestParam(value = "password", required = true) String password) {
  34. try {
  35. return success(loginService.login(loginName, password));
  36. }catch (Exception e) {
  37. if(e instanceof BadCredentialsException){
  38. log.error("BadCredentialsException=====>账号或者密码错误", e.getMessage());
  39. return error("账号或者密码错误");
  40. }else {
  41. log.error("CustomException=====>", e.getMessage());
  42. return error(e.getMessage());
  43. }
  44. }
  45. }
  46. }

2.10 Swagger2的接口配置

  1. package com.modules.common.config;
  2. import io.swagger.annotations.ApiOperation;
  3. import org.springframework.beans.factory.annotation.Value;
  4. import org.springframework.context.annotation.Bean;
  5. import org.springframework.context.annotation.Configuration;
  6. import springfox.documentation.builders.ApiInfoBuilder;
  7. import springfox.documentation.builders.PathSelectors;
  8. import springfox.documentation.builders.RequestHandlerSelectors;
  9. import springfox.documentation.service.*;
  10. import springfox.documentation.spi.DocumentationType;
  11. import springfox.documentation.spi.service.contexts.SecurityContext;
  12. import springfox.documentation.spring.web.plugins.Docket;
  13. import springfox.documentation.swagger2.annotations.EnableSwagger2;
  14. import java.util.ArrayList;
  15. import java.util.List;
  16. /**
  17. * Swagger2的接口配置
  18. *
  19. * @author lc
  20. */
  21. @Configuration
  22. @EnableSwagger2
  23. public class SwaggerConfig {
  24. @Value("${swagger.show}")
  25. private boolean swaggerShow;
  26. /**
  27. * 创建API
  28. */
  29. @Bean
  30. public Docket createRestApi() {
  31. return new Docket(DocumentationType.SWAGGER_2)
  32. // 是否开启
  33. .enable(swaggerShow)
  34. // 用来创建该API的基本信息,展示在文档的页面中(自定义展示的信息)
  35. .apiInfo(apiInfo())
  36. // 全局header配置
  37. // .globalOperationParameters(parameters)
  38. // 设置哪些接口暴露给Swagger展示
  39. .select()
  40. // 扫描所有有注解的api,用这种方式更灵活
  41. .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
  42. // 扫描指定包中的swagger注解
  43. //.apis(RequestHandlerSelectors.basePackage("com.modules.swagger"))
  44. // 扫描所有 .apis(RequestHandlerSelectors.any())
  45. .paths(PathSelectors.any())
  46. .build()
  47. /* 设置安全模式,swagger可以设置访问token */
  48. .securitySchemes(securitySchemes())
  49. .securityContexts(securityContexts());
  50. }
  51. /**
  52. * 安全模式,这里指定token通过Authorization头请求头传递
  53. */
  54. private List<ApiKey> securitySchemes()
  55. {
  56. List<ApiKey> apiKeyList = new ArrayList<ApiKey>();
  57. apiKeyList.add(new ApiKey("token", "token", "header"));
  58. return apiKeyList;
  59. }
  60. /**
  61. * 安全上下文
  62. */
  63. private List<SecurityContext> securityContexts()
  64. {
  65. List<SecurityContext> securityContexts = new ArrayList<>();
  66. securityContexts.add(
  67. SecurityContext.builder()
  68. .securityReferences(defaultAuth())
  69. .forPaths(PathSelectors.regex("^(?!auth).*$"))
  70. .build());
  71. return securityContexts;
  72. }
  73. /**
  74. * 默认的安全上引用
  75. */
  76. private List<SecurityReference> defaultAuth()
  77. {
  78. AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
  79. AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
  80. authorizationScopes[0] = authorizationScope;
  81. List<SecurityReference> securityReferences = new ArrayList<>();
  82. securityReferences.add(new SecurityReference("token", authorizationScopes));
  83. return securityReferences;
  84. }
  85. /**
  86. * 添加摘要信息
  87. */
  88. private ApiInfo apiInfo() {
  89. // 用ApiInfoBuilder进行定制
  90. return new ApiInfoBuilder()
  91. // 设置标题
  92. .title("标题:系统接口文档")
  93. // 描述
  94. .description("描述:用于描述系统接口...")
  95. // 作者信息
  96. .contact(new Contact("lc", null, null))
  97. // 版本
  98. .version("版本号:" + "v1.0.0")
  99. .build();
  100. }
  101. }
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/不正经/article/detail/639982
推荐阅读
相关标签
  

闽ICP备14008679号