依赖pom

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-security</artifactId>
  4. <version>2.3.2.RELEASE</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>io.jsonwebtoken</groupId>
  8. <artifactId>jjwt</artifactId>
  9. <version>0.9.1</version>
  10. </dependency>
  11. <dependency>
  12. <groupId>commons-io</groupId>
  13. <artifactId>commons-io</artifactId>
  14. <version>2.3</version>
  15. </dependency>

认证入口AuthenticationFilter

  1. import org.springframework.lang.Nullable;
  2. import org.springframework.security.authentication.AuthenticationManager;
  3. import org.springframework.security.authentication.AuthenticationServiceException;
  4. import org.springframework.security.core.Authentication;
  5. import org.springframework.security.core.AuthenticationException;
  6. import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
  7. import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
  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 mori
  16. * @date 2021-08-17 11:14:00
  17. */
  18. public class JwtAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
  19. private final static String USERNAME_PARAMETER = "username";
  20. private final static String PASSWORD_PARAMETER = "password";
  21. private final static String POST_METHOD = "POST";
  22. private final static boolean POST_ONLY = true;
  23. private final AuthenticationManager authenticationManager;
  24. public JwtAuthenticationFilter(AuthenticationManager authenticationManager) {
  25. super(new AntPathRequestMatcher("/auth/login", "POST"));
  26. this.authenticationManager = authenticationManager;
  27. }
  28. @Override
  29. public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
  30. if (POST_ONLY && !POST_METHOD.equals(request.getMethod())) {
  31. throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
  32. } else {
  33. String username = this.obtainUsername(request);
  34. String password = this.obtainPassword(request);
  35. if (username == null) {
  36. username = "";
  37. }
  38. if (password == null) {
  39. password = "";
  40. }
  41. username = username.trim();
  42. JwtToken authRequest = new JwtToken(username, password);
  43. this.setDetails(request, authRequest);
  44. return this.authenticationManager.authenticate(authRequest);
  45. }
  46. }
  47. @Nullable
  48. protected String obtainPassword(HttpServletRequest request) {
  49. return request.getParameter(PASSWORD_PARAMETER);
  50. }
  51. @Nullable
  52. protected String obtainUsername(HttpServletRequest request) {
  53. return request.getParameter(USERNAME_PARAMETER);
  54. }
  55. protected void setDetails(HttpServletRequest request, JwtToken authRequest) {
  56. authRequest.setDetails(this.authenticationDetailsSource.buildDetails(request));
  57. }
  58. }

自定义Token对象JwtToken

  1. public class JwtToken extends AbstractAuthenticationToken {
  2. private final Object principal;
  3. private final Object credential;
  4. public JwtToken(Object principal, Object credential) {
  5. super(null);
  6. this.principal = principal;
  7. this.credential = credential;
  8. setAuthenticated(false);
  9. }
  10. public JwtToken(Collection<? extends GrantedAuthority> authorities, Object principal, Object credential) {
  11. super(authorities);
  12. this.principal = principal;
  13. this.credential = credential;
  14. setAuthenticated(true);
  15. }
  16. @Override
  17. public Object getCredentials() {
  18. return this.credential;
  19. }
  20. @Override
  21. public Object getPrincipal() {
  22. return this.principal;
  23. }
  24. }

JWT 认证服务提供JwtAuthenticationProvider

  1. import org.springframework.security.authentication.AuthenticationProvider;
  2. import org.springframework.security.authentication.BadCredentialsException;
  3. import org.springframework.security.core.Authentication;
  4. import org.springframework.security.core.AuthenticationException;
  5. import org.springframework.security.core.userdetails.UserDetails;
  6. import org.springframework.security.core.userdetails.UserDetailsService;
  7. import org.springframework.security.crypto.password.PasswordEncoder;
  8. /**
  9. * jwt认证
  10. *
  11. * @author mori
  12. * @date 2021-08-17 13:56:00
  13. */
  14. public class JwtAuthenticationProvider implements AuthenticationProvider {
  15. private final UserDetailsService userDetailsService;
  16. private final PasswordEncoder passwordEncoder;
  17. public JwtAuthenticationProvider(UserDetailsService userDetailsService, PasswordEncoder passwordEncoder) {
  18. this.userDetailsService = userDetailsService;
  19. this.passwordEncoder = passwordEncoder;
  20. }
  21. @Override
  22. public Authentication authenticate(Authentication authentication) throws AuthenticationException {
  23. JwtToken jwtToken = (JwtToken) authentication;
  24. UserDetails details = userDetailsService.loadUserByUsername(jwtToken.getName());
  25. checkCredentials(details, jwtToken);
  26. checkUserDetails(details);
  27. return new JwtToken(details.getAuthorities(), details, jwtToken.getCredentials());
  28. }
  29. public void checkCredentials(UserDetails details, JwtToken jwtToken) {
  30. if (jwtToken.getCredentials() == null) {
  31. throw new BadCredentialsException("The password not null");
  32. }
  33. if (!passwordEncoder.matches(jwtToken.getCredentials().toString(), details.getPassword())) {
  34. throw new BadCredentialsException("The Password verification failed");
  35. }
  36. }
  37. public void checkUserDetails(UserDetails details) {
  38. if (!details.isAccountNonLocked()) {
  39. throw new BadCredentialsException("The Account is locked");
  40. }
  41. }
  42. @Override
  43. public boolean supports(Class<?> clazz) {
  44. return JwtToken.class.isAssignableFrom(clazz);
  45. }
  46. }

获取用户信息JwtUserDetailsService

  1. import com.lenton.inner.entity.SystemUser;
  2. import com.lenton.inner.service.ISystemUserService;
  3. import org.springframework.security.core.GrantedAuthority;
  4. import org.springframework.security.core.userdetails.UserDetails;
  5. import org.springframework.security.core.userdetails.UserDetailsService;
  6. import org.springframework.security.core.userdetails.UsernameNotFoundException;
  7. import java.util.ArrayList;
  8. import java.util.Collection;
  9. /**
  10. * @author mori
  11. * @date 2021-08-17 11:17:00
  12. */
  13. public class JwtUserDetailsService implements UserDetailsService {
  14. private final ISystemUserService systemUserService;
  15. public JwtUserDetailsService(ISystemUserService systemUserService) {
  16. this.systemUserService = systemUserService;
  17. }
  18. @Override
  19. public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
  20. SystemUser systemUser = systemUserService.loadUserByUsername(username);
  21. if(systemUser == null){
  22. throw new UsernameNotFoundException("User not found");
  23. }
  24. String encodedPassword = systemUser.getPassword();
  25. Collection<GrantedAuthority> collection = new ArrayList<>();
  26. SecurityUser securityUser = new SecurityUser(username, encodedPassword, collection);
  27. securityUser.setUserId(systemUser.getSystemUserId());
  28. return securityUser;
  29. }
  30. }

自定义用户信息SecurityUser

  1. import org.springframework.security.core.GrantedAuthority;
  2. import org.springframework.security.core.userdetails.User;
  3. import java.util.Collection;
  4. /**
  5. * 自定义保存用户信息
  6. * @author mori
  7. * @date 2021-08-17 11:12:00
  8. */
  9. public class SecurityUser extends User {
  10. private String userId;
  11. public SecurityUser(String username, String password, Collection<? extends GrantedAuthority> authorities) {
  12. super(username, password, authorities);
  13. }
  14. public SecurityUser(String username, String password, boolean enabled, boolean accountNonExpired, boolean credentialsNonExpired, boolean accountNonLocked, Collection<? extends GrantedAuthority> authorities) {
  15. super(username, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities);
  16. }
  17. public String getUserId() {
  18. return userId;
  19. }
  20. public void setUserId(String userId) {
  21. this.userId = userId;
  22. }
  23. @Override
  24. public Collection<GrantedAuthority> getAuthorities() {
  25. return super.getAuthorities();
  26. }
  27. }

自定义密码编码器JwtPasswordEncoder

  1. import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
  2. import org.springframework.security.crypto.password.PasswordEncoder;
  3. /**
  4. * 凭证编码器
  5. *
  6. * @author mori
  7. * @date 2021-08-17 13:59:00
  8. */
  9. public class JwtPasswordEncoder implements PasswordEncoder {
  10. private static final BCryptPasswordEncoder ENCODER = new BCryptPasswordEncoder();
  11. @Override
  12. public String encode(CharSequence rawPassword) {
  13. return ENCODER.encode(rawPassword);
  14. }
  15. @Override
  16. public boolean matches(CharSequence rawPassword, String encodedPassword) {
  17. return ENCODER.matches(rawPassword, encodedPassword);
  18. }
  19. @Override
  20. public boolean upgradeEncoding(String encodedPassword) {
  21. return ENCODER.upgradeEncoding(encodedPassword);
  22. }
  23. }

JWT请求过滤器JwtRequestFilter

  1. import com.lenton.inner.common.Result;
  2. import com.lenton.inner.common.util.SpringWebUtil;
  3. import io.jsonwebtoken.ExpiredJwtException;
  4. import org.springframework.security.core.context.SecurityContextHolder;
  5. import org.springframework.security.web.authentication.WebAuthenticationDetails;
  6. import org.springframework.web.filter.OncePerRequestFilter;
  7. import javax.servlet.FilterChain;
  8. import javax.servlet.ServletException;
  9. import javax.servlet.http.HttpServletRequest;
  10. import javax.servlet.http.HttpServletResponse;
  11. import java.io.IOException;
  12. /**
  13. * @author mori
  14. * @date 2021-08-17 11:09:00
  15. */
  16. public class JwtRequestFilter extends OncePerRequestFilter {
  17. private final static String TOKEN_PREFIX = "Bearer ";
  18. private final static String TOKEN_HEADER_NAME = "Authorization";
  19. private final static String UNAUTHORIZED_CODE = "401";
  20. public String getToken(HttpServletRequest request) {
  21. return request.getHeader(TOKEN_HEADER_NAME);
  22. }
  23. @Override
  24. protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
  25. throws ServletException, IOException {
  26. final String originalToken = getToken(request);
  27. if (originalToken == null || originalToken.isEmpty()) {
  28. chain.doFilter(request, response);
  29. return;
  30. }
  31. SecurityUser securityUser = null;
  32. String token = originalToken;
  33. if (token.startsWith(TOKEN_PREFIX)) {
  34. token = token.substring(7);
  35. try {
  36. securityUser = JwtTokenUtil.getSecurityUser(token);
  37. } catch (IllegalArgumentException e) {
  38. response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
  39. SpringWebUtil.response(response, Result.fail(UNAUTHORIZED_CODE, "The token parsing failed:" + e.getMessage()));
  40. return;
  41. } catch (ExpiredJwtException e) {
  42. response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
  43. SpringWebUtil.response(response, Result.fail(UNAUTHORIZED_CODE, "The token expired"));
  44. return;
  45. } catch (Exception e) {
  46. response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
  47. SpringWebUtil.response(response, Result.fail(UNAUTHORIZED_CODE, e.getMessage()));
  48. return;
  49. }
  50. }
  51. if (securityUser == null) {
  52. response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
  53. SpringWebUtil.response(response, Result.fail(UNAUTHORIZED_CODE, "The token parsing failed"));
  54. return;
  55. }
  56. JwtToken jwtToken = new JwtToken(securityUser.getAuthorities(), securityUser, "");
  57. jwtToken.setDetails(new WebAuthenticationDetails(request));
  58. SecurityContextHolder.getContext().setAuthentication(jwtToken);
  59. chain.doFilter(request, response);
  60. }
  61. }

JWT token生成JwtTokenUtil

  1. import io.jsonwebtoken.Claims;
  2. import io.jsonwebtoken.Jwts;
  3. import io.jsonwebtoken.SignatureAlgorithm;
  4. import java.util.ArrayList;
  5. import java.util.Date;
  6. import java.util.HashMap;
  7. import java.util.Map;
  8. import java.util.function.Function;
  9. /**
  10. * jwt工具类
  11. *
  12. * @author mori
  13. * @date 2021-08-17 11:20:00
  14. */
  15. public class JwtTokenUtil {
  16. public static final long JWT_TOKEN_VALIDITY = 2 * 60 * 60;
  17. private static final String SECRET = "secret";
  18. public static SecurityUser getSecurityUser(String token) {
  19. Claims claims = getAllClaimsFromToken(token);
  20. String userId = claims.getSubject();
  21. String username = (String) claims.get("username");
  22. SecurityUser securityUser = new SecurityUser(username, "", new ArrayList<>());
  23. securityUser.setUserId(userId);
  24. return securityUser;
  25. }
  26. public static Date getExpirationDateFromToken(String token) {
  27. return getClaimFromToken(token, Claims::getExpiration);
  28. }
  29. public static <T> T getClaimFromToken(String token, Function<Claims, T> claimsResolver) {
  30. final Claims claims = getAllClaimsFromToken(token);
  31. return claimsResolver.apply(claims);
  32. }
  33. private static Claims getAllClaimsFromToken(String token) {
  34. return Jwts.parser().setSigningKey(SECRET).parseClaimsJws(token).getBody();
  35. }
  36. private static Boolean isTokenExpired(String token) {
  37. final Date expiration = getExpirationDateFromToken(token);
  38. return expiration.before(new Date());
  39. }
  40. public static String generateToken(SecurityUser userDetails) {
  41. Map<String, Object> claims = new HashMap<>(1 << 2);
  42. claims.put("username", userDetails.getUsername());
  43. return doGenerateToken(claims, userDetails.getUserId());
  44. }
  45. private static String doGenerateToken(Map<String, Object> claims, String subject) {
  46. return Jwts.builder()
  47. .setClaims(claims)
  48. .setSubject(subject)
  49. .setIssuedAt(new Date(System.currentTimeMillis()))
  50. .setExpiration(new Date(System.currentTimeMillis() + JWT_TOKEN_VALIDITY * 1000))
  51. .signWith(SignatureAlgorithm.HS512, SECRET).compact();
  52. }
  53. }

认证成功处理JwtAuthenticationSuccessHandler

  1. import com.lenton.inner.common.Result;
  2. import com.lenton.inner.common.util.SpringWebUtil;
  3. import org.springframework.security.core.Authentication;
  4. import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
  5. import javax.servlet.ServletException;
  6. import javax.servlet.http.HttpServletRequest;
  7. import javax.servlet.http.HttpServletResponse;
  8. import java.io.IOException;
  9. import java.util.HashMap;
  10. import java.util.Map;
  11. /**
  12. * jwt认证成功
  13. *
  14. * @author mori
  15. * @date 2021-08-17 14:15:00
  16. */
  17. public class JwtAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
  18. @Override
  19. public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
  20. SecurityUser userDetails = (SecurityUser)authentication.getPrincipal();
  21. Map<String, String> map = new HashMap<>(1 << 2);
  22. map.put("token", JwtTokenUtil.generateToken(userDetails));
  23. SpringWebUtil.response(response, Result.ok(map));
  24. }
  25. }

认证失败处理JwtAuthenticationFailureHandler

  1. import com.lenton.inner.common.Result;
  2. import com.lenton.inner.common.util.SpringWebUtil;
  3. import lombok.extern.slf4j.Slf4j;
  4. import org.springframework.security.core.AuthenticationException;
  5. import org.springframework.security.web.authentication.AuthenticationFailureHandler;
  6. import javax.servlet.ServletException;
  7. import javax.servlet.http.HttpServletRequest;
  8. import javax.servlet.http.HttpServletResponse;
  9. import java.io.IOException;
  10. /**
  11. * @author mori
  12. * @date 2021-08-17 14:53:00
  13. */
  14. @Slf4j
  15. public class JwtAuthenticationFailureHandler implements AuthenticationFailureHandler {
  16. private final static String UNAUTHORIZED_CODE = "401";
  17. @Override
  18. public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
  19. log.debug(e.getMessage(),e);
  20. response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
  21. SpringWebUtil.response(response, Result.fail(UNAUTHORIZED_CODE, e.getMessage()));
  22. }
  23. }

无权限访问处理JwtAuthenticationEntryPoint

  1. import com.lenton.inner.common.Result;
  2. import com.lenton.inner.common.util.SpringWebUtil;
  3. import lombok.extern.slf4j.Slf4j;
  4. import org.springframework.security.core.AuthenticationException;
  5. import org.springframework.security.web.AuthenticationEntryPoint;
  6. import javax.servlet.http.HttpServletRequest;
  7. import javax.servlet.http.HttpServletResponse;
  8. import java.io.IOException;
  9. /**
  10. * @author mori
  11. * @date 2021-08-17 11:10:00
  12. */
  13. @Slf4j
  14. public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint {
  15. private final static String UNAUTHORIZED_CODE = "401";
  16. @Override
  17. public void commence(HttpServletRequest request, HttpServletResponse response,
  18. AuthenticationException e) throws IOException {
  19. log.debug(e.getMessage(),e);
  20. response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
  21. SpringWebUtil.response(response,Result.fail(UNAUTHORIZED_CODE, e.getMessage()));
  22. }
  23. }

拒绝访问处理JwtAccessDeniedHandler

  1. import com.lenton.inner.common.Result;
  2. import com.lenton.inner.common.util.SpringWebUtil;
  3. import lombok.extern.slf4j.Slf4j;
  4. import org.springframework.security.access.AccessDeniedException;
  5. import org.springframework.security.web.access.AccessDeniedHandler;
  6. import javax.servlet.http.HttpServletRequest;
  7. import javax.servlet.http.HttpServletResponse;
  8. import java.io.IOException;
  9. /**
  10. * @author mori
  11. * @date 2021-08-17 11:11:00
  12. */
  13. @Slf4j
  14. public class JwtAccessDeniedHandler implements AccessDeniedHandler {
  15. private final static String ACCESS_DENIED_CODE = "403";
  16. @Override
  17. public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException e) throws IOException {
  18. log.debug(e.getMessage(),e);
  19. response.setStatus(HttpServletResponse.SC_FORBIDDEN);
  20. SpringWebUtil.response(response, Result.fail(ACCESS_DENIED_CODE,"JWT token authentication failed."));
  21. }
  22. }

web安全配置WebSecurityConfig

  1. import com.lenton.inner.service.ISystemUserService;
  2. import com.lenton.inner.web.common.config.security.*;
  3. import org.springframework.security.authentication.AuthenticationManager;
  4. import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
  5. import org.springframework.security.config.annotation.web.builders.HttpSecurity;
  6. import org.springframework.security.config.annotation.web.builders.WebSecurity;
  7. import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
  8. import org.springframework.security.config.http.SessionCreationPolicy;
  9. import org.springframework.security.core.userdetails.UserDetailsService;
  10. import org.springframework.security.crypto.password.PasswordEncoder;
  11. import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
  12. import org.springframework.context.annotation.Configuration;
  13. import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
  14. /**
  15. * @author mori
  16. * @date 2021-08-17 11:05:00
  17. */
  18. @EnableWebSecurity
  19. @Configuration
  20. public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
  21. private final ISystemUserService systemUserService;
  22. public BaseWebSecurityConfig(ISystemUserService systemUserService) {
  23. this.systemUserService = systemUserService;
  24. }
  25. public PasswordEncoder jwtPasswordEncoder() {
  26. return new JwtPasswordEncoder();
  27. }
  28. public JwtAuthenticationSuccessHandler jwtAuthenticationSuccessHandler() {
  29. return new JwtAuthenticationSuccessHandler();
  30. }
  31. public JwtAuthenticationFailureHandler jwtAuthenticationFailureHandler() {
  32. return new JwtAuthenticationFailureHandler();
  33. }
  34. public JwtAccessDeniedHandler jwtAccessDeniedHandler() {
  35. return new JwtAccessDeniedHandler();
  36. }
  37. public JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint() {
  38. return new JwtAuthenticationEntryPoint();
  39. }
  40. @Override
  41. public AuthenticationManager authenticationManagerBean() throws Exception {
  42. return super.authenticationManagerBean();
  43. }
  44. @Override
  45. public void configure(WebSecurity web) throws Exception {
  46. web.ignoring().antMatchers(
  47. "/swagger-ui/index.html",
  48. "/swagger-resources/**",
  49. "/swagger-ui/**",
  50. "/webjars/**",
  51. "/v3/**",
  52. "/api/**",
  53. "/actuator/**");
  54. }
  55. @Override
  56. protected void configure(AuthenticationManagerBuilder authenticationManagerBuilder) {
  57. UserDetailsService userDetailsService = new JwtUserDetailsService(systemUserService);
  58. JwtAuthenticationProvider jwtAuthenticationProvider = new JwtAuthenticationProvider(userDetailsService, jwtPasswordEncoder());
  59. authenticationManagerBuilder.authenticationProvider(jwtAuthenticationProvider);
  60. }
  61. @Override
  62. protected void configure(HttpSecurity httpSecurity) throws Exception {
  63. JwtAuthenticationFilter authenticationFilter = new JwtAuthenticationFilter(authenticationManagerBean());
  64. authenticationFilter.setAuthenticationFailureHandler(jwtAuthenticationFailureHandler());
  65. authenticationFilter.setAuthenticationSuccessHandler(jwtAuthenticationSuccessHandler());
  66. httpSecurity.authorizeRequests()
  67. .antMatchers("/auth/**").permitAll()
  68. .anyRequest().authenticated();
  69. httpSecurity.addFilterAt(authenticationFilter, UsernamePasswordAuthenticationFilter.class)
  70. .addFilterAfter(new JwtRequestFilter(), JwtAuthenticationFilter.class)
  71. .exceptionHandling()
  72. .accessDeniedHandler(jwtAccessDeniedHandler())
  73. .authenticationEntryPoint(jwtAuthenticationEntryPoint())
  74. .and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
  75. .and().csrf().disable();
  76. }
  77. }

认证上下文AuthenticationContextHolder

  1. import com.alibaba.fastjson.JSONObject;
  2. import lombok.extern.slf4j.Slf4j;
  3. import org.springframework.security.core.Authentication;
  4. import org.springframework.security.core.context.SecurityContext;
  5. import org.springframework.security.core.context.SecurityContextHolder;
  6. import java.util.Optional;
  7. /**
  8. * 认证上下文,获取当前登录user
  9. * @author mori
  10. * @date 2021-08-18 16:15:00
  11. */
  12. @Slf4j
  13. public class AuthenticationContextHolder {
  14. /**
  15. * 查询身份验证主题,user_id
  16. *
  17. * @return {@link String}
  18. */
  19. public static String getAuthenticationPrincipal() {
  20. String userInfo = Optional.ofNullable(SecurityContextHolder.getContext())
  21. .map(SecurityContext::getAuthentication)
  22. .map(Authentication::getPrincipal)
  23. .map(JSONObject::toJSONString)
  24. .orElse(null);
  25. log.debug("Authentication Principal :" + userInfo);
  26. if (userInfo == null) {
  27. return null;
  28. }
  29. JSONObject user = JSONObject.parseObject(userInfo);
  30. return user.getString("userId");
  31. }
  32. /**
  33. * 查询身份验证的名字,username
  34. *
  35. * @return {@link String}
  36. */
  37. public static String getAuthenticationName() {
  38. String authenticationName = Optional.ofNullable(SecurityContextHolder.getContext())
  39. .map(SecurityContext::getAuthentication)
  40. .map(Authentication::getName)
  41. .orElse(null);
  42. log.debug("Authentication getName :" + authenticationName);
  43. return authenticationName;
  44. }
  45. }

web工具类SpringWebUtil

  1. import com.alibaba.fastjson.JSONObject;
  2. import com.lenton.inner.common.Result;
  3. import eu.bitwalker.useragentutils.Browser;
  4. import eu.bitwalker.useragentutils.OperatingSystem;
  5. import eu.bitwalker.useragentutils.UserAgent;
  6. import org.apache.commons.lang3.StringUtils;
  7. import org.springframework.web.context.request.RequestContextHolder;
  8. import org.springframework.web.context.request.ServletRequestAttributes;
  9. import javax.servlet.http.HttpServletRequest;
  10. import javax.servlet.http.HttpServletResponse;
  11. import java.io.IOException;
  12. import java.io.PrintWriter;
  13. import java.util.*;
  14. /**
  15. * spring web工具类
  16. *
  17. * @author mori
  18. * @date 2021/07/27
  19. */
  20. public final class SpringWebUtil {
  21. private static final String UNKNOWN = "unknown";
  22. private static final int IP_MAX_LENGTH = 15;
  23. /**
  24. * 获取请求
  25. *
  26. * @return {@link HttpServletRequest}
  27. */
  28. public static HttpServletRequest getRequest() {
  29. ServletRequestAttributes requestAttributes =
  30. (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
  31. return requestAttributes == null ? null : requestAttributes.getRequest();
  32. }
  33. /**
  34. * 获取响应
  35. *
  36. * @return {@link HttpServletResponse}
  37. */
  38. public static HttpServletResponse getResponse() {
  39. ServletRequestAttributes requestAttributes =
  40. (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
  41. return requestAttributes == null ? null : requestAttributes.getResponse();
  42. }
  43. /**
  44. * 查询ip地址
  45. *
  46. * @param request 请求
  47. * @return {@link String}
  48. */
  49. public static String getIpAddress(HttpServletRequest request) {
  50. try {
  51. if (request == null) {
  52. return "";
  53. }
  54. // 获取请求主机IP地址,如果通过代理进来,则透过防火墙获取真实IP地址
  55. String ip = request.getHeader("X-Forwarded-For");
  56. if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
  57. if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
  58. ip = request.getHeader("Proxy-Client-IP");
  59. }
  60. if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
  61. ip = request.getHeader("WL-Proxy-Client-IP");
  62. }
  63. if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
  64. ip = request.getHeader("HTTP_CLIENT_IP");
  65. }
  66. if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
  67. ip = request.getHeader("HTTP_X_FORWARDED_FOR");
  68. }
  69. if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
  70. ip = request.getRemoteAddr();
  71. }
  72. } else if (ip.length() > IP_MAX_LENGTH) {
  73. String[] ips = ip.split(",");
  74. for (String strIp : ips) {
  75. if (!(UNKNOWN.equalsIgnoreCase(strIp))) {
  76. ip = strIp;
  77. break;
  78. }
  79. }
  80. }
  81. return ip;
  82. } catch (Exception e) {
  83. return "";
  84. }
  85. }
  86. /**
  87. * 获取服务部署根路径 http:// + ip + port
  88. *
  89. * @return {@link String}
  90. */
  91. public static String getServerIpAndPort() {
  92. //+ ":" + request.getServerPort()
  93. return Objects.requireNonNull(getRequest()).getScheme() + "://" + getRequest().getServerName() + ":" + getRequest().getServerPort();
  94. }
  95. /**
  96. * 获取当前用户浏览器信息
  97. *
  98. * @param request HttpServletRequest
  99. * @return 当前用户浏览器信息
  100. */
  101. public static String getHeader(HttpServletRequest request) {
  102. return request.getHeader("User-Agent");
  103. }
  104. /**
  105. * 获取当前用户浏览器型号
  106. *
  107. * @return 当前用户浏览器型号
  108. */
  109. public static String getUserBrowser(HttpServletRequest request) {
  110. try {
  111. UserAgent userAgent = UserAgent.parseUserAgentString(Objects.requireNonNull(request).getHeader("User-Agent"));
  112. Browser browser = userAgent.getBrowser();
  113. return browser.toString();
  114. } catch (Exception e) {
  115. return StringUtils.EMPTY;
  116. }
  117. }
  118. /**
  119. * 获取当前用户系统型号
  120. *
  121. * @return 当前用户系统型号
  122. */
  123. public static String getUserOperatingSystem(HttpServletRequest request) {
  124. try {
  125. UserAgent userAgent = UserAgent.parseUserAgentString(Objects.requireNonNull(request).getHeader("User-Agent"));
  126. OperatingSystem operatingSystem = userAgent.getOperatingSystem();
  127. return operatingSystem.toString();
  128. } catch (Exception e) {
  129. return StringUtils.EMPTY;
  130. }
  131. }
  132. /**
  133. * 获取请求头
  134. *
  135. * @param request 请求
  136. * @return {@link Map}
  137. */
  138. public static Map<String, Object> getRequestHeaders(HttpServletRequest request) {
  139. Map<String, Object> headers = new HashMap<>(1 << 4);
  140. Enumeration<String> headerNames = request.getHeaderNames();
  141. while (headerNames.hasMoreElements()) {
  142. String headerName = headerNames.nextElement();
  143. headers.put(headerName, request.getHeader(headerName));
  144. }
  145. return headers;
  146. }
  147. /**
  148. * 获取响应头
  149. *
  150. * @param response 响应
  151. * @return {@link Map}
  152. */
  153. public static Map<String, Object> getResponseHeaders(HttpServletResponse response) {
  154. Map<String, Object> headers = new HashMap<>(1 << 4);
  155. Collection<String> headerNames = response.getHeaderNames();
  156. for (String headerName : headerNames) {
  157. headers.put(headerName, response.getHeader(headerName));
  158. }
  159. return headers;
  160. }
  161. public static void response(HttpServletResponse response,Result<?> result) {
  162. String resp = JSONObject.toJSONString(result);
  163. response.setContentType("application/json;charset=utf-8");
  164. try (PrintWriter writer = response.getWriter()) {
  165. writer.print(resp);
  166. } catch (IOException e) {
  167. // NOOP
  168. }
  169. }
  170. }

前端统一返回对象Result

  1. import com.alibaba.fastjson.annotation.JSONField;
  2. import com.fasterxml.jackson.annotation.JsonIgnore;
  3. import com.lenton.inner.common.exception.CommonErrorCode;
  4. import lombok.Data;
  5. import java.util.Objects;
  6. /**
  7. * 前端统一返回格式
  8. *
  9. * @author mori
  10. * @date 2021-07-28 12:06:00
  11. */
  12. @Data
  13. public class Result<T> {
  14. private T data;
  15. private String code;
  16. private String msg;
  17. public Result() {
  18. }
  19. public Result(String code, String msg) {
  20. this(null, code, msg);
  21. }
  22. public Result(T data, String code) {
  23. this(data, code, null);
  24. }
  25. public Result(T data, String code, String msg) {
  26. this.data = data;
  27. this.code = code;
  28. this.msg = msg;
  29. }
  30. public static <T> Result<T> ok(T body) {
  31. return new Result<>(body, CommonErrorCode.SUCCESS.getCode());
  32. }
  33. public static Result<Void> fail(String code, String msg) {
  34. return new Result<>(code, msg);
  35. }
  36. /**
  37. * 是否成功
  38. *
  39. * @return boolean
  40. */
  41. @JSONField(serialize = false)
  42. @JsonIgnore
  43. public boolean isSuccess() {
  44. return Objects.equals(CommonErrorCode.SUCCESS.getCode(), this.code);
  45. }
  46. /**
  47. * 是否出错
  48. *
  49. * @return boolean
  50. */
  51. @JSONField(serialize = false)
  52. @JsonIgnore
  53. public boolean isError() {
  54. return !isSuccess();
  55. }
  56. }