依赖pom
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
<version>2.3.2.RELEASE</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.3</version>
</dependency>
认证入口AuthenticationFilter
import org.springframework.lang.Nullable;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* 拦截登录请求
*
* @author mori
* @date 2021-08-17 11:14:00
*/
public class JwtAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
private final static String USERNAME_PARAMETER = "username";
private final static String PASSWORD_PARAMETER = "password";
private final static String POST_METHOD = "POST";
private final static boolean POST_ONLY = true;
private final AuthenticationManager authenticationManager;
public JwtAuthenticationFilter(AuthenticationManager authenticationManager) {
super(new AntPathRequestMatcher("/auth/login", "POST"));
this.authenticationManager = authenticationManager;
}
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
if (POST_ONLY && !POST_METHOD.equals(request.getMethod())) {
throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
} else {
String username = this.obtainUsername(request);
String password = this.obtainPassword(request);
if (username == null) {
username = "";
}
if (password == null) {
password = "";
}
username = username.trim();
JwtToken authRequest = new JwtToken(username, password);
this.setDetails(request, authRequest);
return this.authenticationManager.authenticate(authRequest);
}
}
@Nullable
protected String obtainPassword(HttpServletRequest request) {
return request.getParameter(PASSWORD_PARAMETER);
}
@Nullable
protected String obtainUsername(HttpServletRequest request) {
return request.getParameter(USERNAME_PARAMETER);
}
protected void setDetails(HttpServletRequest request, JwtToken authRequest) {
authRequest.setDetails(this.authenticationDetailsSource.buildDetails(request));
}
}
自定义Token对象JwtToken
public class JwtToken extends AbstractAuthenticationToken {
private final Object principal;
private final Object credential;
public JwtToken(Object principal, Object credential) {
super(null);
this.principal = principal;
this.credential = credential;
setAuthenticated(false);
}
public JwtToken(Collection<? extends GrantedAuthority> authorities, Object principal, Object credential) {
super(authorities);
this.principal = principal;
this.credential = credential;
setAuthenticated(true);
}
@Override
public Object getCredentials() {
return this.credential;
}
@Override
public Object getPrincipal() {
return this.principal;
}
}
JWT 认证服务提供JwtAuthenticationProvider
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
/**
* jwt认证
*
* @author mori
* @date 2021-08-17 13:56:00
*/
public class JwtAuthenticationProvider implements AuthenticationProvider {
private final UserDetailsService userDetailsService;
private final PasswordEncoder passwordEncoder;
public JwtAuthenticationProvider(UserDetailsService userDetailsService, PasswordEncoder passwordEncoder) {
this.userDetailsService = userDetailsService;
this.passwordEncoder = passwordEncoder;
}
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
JwtToken jwtToken = (JwtToken) authentication;
UserDetails details = userDetailsService.loadUserByUsername(jwtToken.getName());
checkCredentials(details, jwtToken);
checkUserDetails(details);
return new JwtToken(details.getAuthorities(), details, jwtToken.getCredentials());
}
public void checkCredentials(UserDetails details, JwtToken jwtToken) {
if (jwtToken.getCredentials() == null) {
throw new BadCredentialsException("The password not null");
}
if (!passwordEncoder.matches(jwtToken.getCredentials().toString(), details.getPassword())) {
throw new BadCredentialsException("The Password verification failed");
}
}
public void checkUserDetails(UserDetails details) {
if (!details.isAccountNonLocked()) {
throw new BadCredentialsException("The Account is locked");
}
}
@Override
public boolean supports(Class<?> clazz) {
return JwtToken.class.isAssignableFrom(clazz);
}
}
获取用户信息JwtUserDetailsService
import com.lenton.inner.entity.SystemUser;
import com.lenton.inner.service.ISystemUserService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import java.util.ArrayList;
import java.util.Collection;
/**
* @author mori
* @date 2021-08-17 11:17:00
*/
public class JwtUserDetailsService implements UserDetailsService {
private final ISystemUserService systemUserService;
public JwtUserDetailsService(ISystemUserService systemUserService) {
this.systemUserService = systemUserService;
}
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
SystemUser systemUser = systemUserService.loadUserByUsername(username);
if(systemUser == null){
throw new UsernameNotFoundException("User not found");
}
String encodedPassword = systemUser.getPassword();
Collection<GrantedAuthority> collection = new ArrayList<>();
SecurityUser securityUser = new SecurityUser(username, encodedPassword, collection);
securityUser.setUserId(systemUser.getSystemUserId());
return securityUser;
}
}
自定义用户信息SecurityUser
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import java.util.Collection;
/**
* 自定义保存用户信息
* @author mori
* @date 2021-08-17 11:12:00
*/
public class SecurityUser extends User {
private String userId;
public SecurityUser(String username, String password, Collection<? extends GrantedAuthority> authorities) {
super(username, password, authorities);
}
public SecurityUser(String username, String password, boolean enabled, boolean accountNonExpired, boolean credentialsNonExpired, boolean accountNonLocked, Collection<? extends GrantedAuthority> authorities) {
super(username, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities);
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
@Override
public Collection<GrantedAuthority> getAuthorities() {
return super.getAuthorities();
}
}
自定义密码编码器JwtPasswordEncoder
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
/**
* 凭证编码器
*
* @author mori
* @date 2021-08-17 13:59:00
*/
public class JwtPasswordEncoder implements PasswordEncoder {
private static final BCryptPasswordEncoder ENCODER = new BCryptPasswordEncoder();
@Override
public String encode(CharSequence rawPassword) {
return ENCODER.encode(rawPassword);
}
@Override
public boolean matches(CharSequence rawPassword, String encodedPassword) {
return ENCODER.matches(rawPassword, encodedPassword);
}
@Override
public boolean upgradeEncoding(String encodedPassword) {
return ENCODER.upgradeEncoding(encodedPassword);
}
}
JWT请求过滤器JwtRequestFilter
import com.lenton.inner.common.Result;
import com.lenton.inner.common.util.SpringWebUtil;
import io.jsonwebtoken.ExpiredJwtException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetails;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* @author mori
* @date 2021-08-17 11:09:00
*/
public class JwtRequestFilter extends OncePerRequestFilter {
private final static String TOKEN_PREFIX = "Bearer ";
private final static String TOKEN_HEADER_NAME = "Authorization";
private final static String UNAUTHORIZED_CODE = "401";
public String getToken(HttpServletRequest request) {
return request.getHeader(TOKEN_HEADER_NAME);
}
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
throws ServletException, IOException {
final String originalToken = getToken(request);
if (originalToken == null || originalToken.isEmpty()) {
chain.doFilter(request, response);
return;
}
SecurityUser securityUser = null;
String token = originalToken;
if (token.startsWith(TOKEN_PREFIX)) {
token = token.substring(7);
try {
securityUser = JwtTokenUtil.getSecurityUser(token);
} catch (IllegalArgumentException e) {
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
SpringWebUtil.response(response, Result.fail(UNAUTHORIZED_CODE, "The token parsing failed:" + e.getMessage()));
return;
} catch (ExpiredJwtException e) {
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
SpringWebUtil.response(response, Result.fail(UNAUTHORIZED_CODE, "The token expired"));
return;
} catch (Exception e) {
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
SpringWebUtil.response(response, Result.fail(UNAUTHORIZED_CODE, e.getMessage()));
return;
}
}
if (securityUser == null) {
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
SpringWebUtil.response(response, Result.fail(UNAUTHORIZED_CODE, "The token parsing failed"));
return;
}
JwtToken jwtToken = new JwtToken(securityUser.getAuthorities(), securityUser, "");
jwtToken.setDetails(new WebAuthenticationDetails(request));
SecurityContextHolder.getContext().setAuthentication(jwtToken);
chain.doFilter(request, response);
}
}
JWT token生成JwtTokenUtil
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;
/**
* jwt工具类
*
* @author mori
* @date 2021-08-17 11:20:00
*/
public class JwtTokenUtil {
public static final long JWT_TOKEN_VALIDITY = 2 * 60 * 60;
private static final String SECRET = "secret";
public static SecurityUser getSecurityUser(String token) {
Claims claims = getAllClaimsFromToken(token);
String userId = claims.getSubject();
String username = (String) claims.get("username");
SecurityUser securityUser = new SecurityUser(username, "", new ArrayList<>());
securityUser.setUserId(userId);
return securityUser;
}
public static Date getExpirationDateFromToken(String token) {
return getClaimFromToken(token, Claims::getExpiration);
}
public static <T> T getClaimFromToken(String token, Function<Claims, T> claimsResolver) {
final Claims claims = getAllClaimsFromToken(token);
return claimsResolver.apply(claims);
}
private static Claims getAllClaimsFromToken(String token) {
return Jwts.parser().setSigningKey(SECRET).parseClaimsJws(token).getBody();
}
private static Boolean isTokenExpired(String token) {
final Date expiration = getExpirationDateFromToken(token);
return expiration.before(new Date());
}
public static String generateToken(SecurityUser userDetails) {
Map<String, Object> claims = new HashMap<>(1 << 2);
claims.put("username", userDetails.getUsername());
return doGenerateToken(claims, userDetails.getUserId());
}
private static String doGenerateToken(Map<String, Object> claims, String subject) {
return Jwts.builder()
.setClaims(claims)
.setSubject(subject)
.setIssuedAt(new Date(System.currentTimeMillis()))
.setExpiration(new Date(System.currentTimeMillis() + JWT_TOKEN_VALIDITY * 1000))
.signWith(SignatureAlgorithm.HS512, SECRET).compact();
}
}
认证成功处理JwtAuthenticationSuccessHandler
import com.lenton.inner.common.Result;
import com.lenton.inner.common.util.SpringWebUtil;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
/**
* jwt认证成功
*
* @author mori
* @date 2021-08-17 14:15:00
*/
public class JwtAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
SecurityUser userDetails = (SecurityUser)authentication.getPrincipal();
Map<String, String> map = new HashMap<>(1 << 2);
map.put("token", JwtTokenUtil.generateToken(userDetails));
SpringWebUtil.response(response, Result.ok(map));
}
}
认证失败处理JwtAuthenticationFailureHandler
import com.lenton.inner.common.Result;
import com.lenton.inner.common.util.SpringWebUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* @author mori
* @date 2021-08-17 14:53:00
*/
@Slf4j
public class JwtAuthenticationFailureHandler implements AuthenticationFailureHandler {
private final static String UNAUTHORIZED_CODE = "401";
@Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
log.debug(e.getMessage(),e);
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
SpringWebUtil.response(response, Result.fail(UNAUTHORIZED_CODE, e.getMessage()));
}
}
无权限访问处理JwtAuthenticationEntryPoint
import com.lenton.inner.common.Result;
import com.lenton.inner.common.util.SpringWebUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* @author mori
* @date 2021-08-17 11:10:00
*/
@Slf4j
public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint {
private final static String UNAUTHORIZED_CODE = "401";
@Override
public void commence(HttpServletRequest request, HttpServletResponse response,
AuthenticationException e) throws IOException {
log.debug(e.getMessage(),e);
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
SpringWebUtil.response(response,Result.fail(UNAUTHORIZED_CODE, e.getMessage()));
}
}
拒绝访问处理JwtAccessDeniedHandler
import com.lenton.inner.common.Result;
import com.lenton.inner.common.util.SpringWebUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* @author mori
* @date 2021-08-17 11:11:00
*/
@Slf4j
public class JwtAccessDeniedHandler implements AccessDeniedHandler {
private final static String ACCESS_DENIED_CODE = "403";
@Override
public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException e) throws IOException {
log.debug(e.getMessage(),e);
response.setStatus(HttpServletResponse.SC_FORBIDDEN);
SpringWebUtil.response(response, Result.fail(ACCESS_DENIED_CODE,"JWT token authentication failed."));
}
}
web安全配置WebSecurityConfig
import com.lenton.inner.service.ISystemUserService;
import com.lenton.inner.web.common.config.security.*;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
/**
* @author mori
* @date 2021-08-17 11:05:00
*/
@EnableWebSecurity
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
private final ISystemUserService systemUserService;
public BaseWebSecurityConfig(ISystemUserService systemUserService) {
this.systemUserService = systemUserService;
}
public PasswordEncoder jwtPasswordEncoder() {
return new JwtPasswordEncoder();
}
public JwtAuthenticationSuccessHandler jwtAuthenticationSuccessHandler() {
return new JwtAuthenticationSuccessHandler();
}
public JwtAuthenticationFailureHandler jwtAuthenticationFailureHandler() {
return new JwtAuthenticationFailureHandler();
}
public JwtAccessDeniedHandler jwtAccessDeniedHandler() {
return new JwtAccessDeniedHandler();
}
public JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint() {
return new JwtAuthenticationEntryPoint();
}
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers(
"/swagger-ui/index.html",
"/swagger-resources/**",
"/swagger-ui/**",
"/webjars/**",
"/v3/**",
"/api/**",
"/actuator/**");
}
@Override
protected void configure(AuthenticationManagerBuilder authenticationManagerBuilder) {
UserDetailsService userDetailsService = new JwtUserDetailsService(systemUserService);
JwtAuthenticationProvider jwtAuthenticationProvider = new JwtAuthenticationProvider(userDetailsService, jwtPasswordEncoder());
authenticationManagerBuilder.authenticationProvider(jwtAuthenticationProvider);
}
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
JwtAuthenticationFilter authenticationFilter = new JwtAuthenticationFilter(authenticationManagerBean());
authenticationFilter.setAuthenticationFailureHandler(jwtAuthenticationFailureHandler());
authenticationFilter.setAuthenticationSuccessHandler(jwtAuthenticationSuccessHandler());
httpSecurity.authorizeRequests()
.antMatchers("/auth/**").permitAll()
.anyRequest().authenticated();
httpSecurity.addFilterAt(authenticationFilter, UsernamePasswordAuthenticationFilter.class)
.addFilterAfter(new JwtRequestFilter(), JwtAuthenticationFilter.class)
.exceptionHandling()
.accessDeniedHandler(jwtAccessDeniedHandler())
.authenticationEntryPoint(jwtAuthenticationEntryPoint())
.and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and().csrf().disable();
}
}
认证上下文AuthenticationContextHolder
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import java.util.Optional;
/**
* 认证上下文,获取当前登录user
* @author mori
* @date 2021-08-18 16:15:00
*/
@Slf4j
public class AuthenticationContextHolder {
/**
* 查询身份验证主题,user_id
*
* @return {@link String}
*/
public static String getAuthenticationPrincipal() {
String userInfo = Optional.ofNullable(SecurityContextHolder.getContext())
.map(SecurityContext::getAuthentication)
.map(Authentication::getPrincipal)
.map(JSONObject::toJSONString)
.orElse(null);
log.debug("Authentication Principal :" + userInfo);
if (userInfo == null) {
return null;
}
JSONObject user = JSONObject.parseObject(userInfo);
return user.getString("userId");
}
/**
* 查询身份验证的名字,username
*
* @return {@link String}
*/
public static String getAuthenticationName() {
String authenticationName = Optional.ofNullable(SecurityContextHolder.getContext())
.map(SecurityContext::getAuthentication)
.map(Authentication::getName)
.orElse(null);
log.debug("Authentication getName :" + authenticationName);
return authenticationName;
}
}
web工具类SpringWebUtil
import com.alibaba.fastjson.JSONObject;
import com.lenton.inner.common.Result;
import eu.bitwalker.useragentutils.Browser;
import eu.bitwalker.useragentutils.OperatingSystem;
import eu.bitwalker.useragentutils.UserAgent;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;
/**
* spring web工具类
*
* @author mori
* @date 2021/07/27
*/
public final class SpringWebUtil {
private static final String UNKNOWN = "unknown";
private static final int IP_MAX_LENGTH = 15;
/**
* 获取请求
*
* @return {@link HttpServletRequest}
*/
public static HttpServletRequest getRequest() {
ServletRequestAttributes requestAttributes =
(ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
return requestAttributes == null ? null : requestAttributes.getRequest();
}
/**
* 获取响应
*
* @return {@link HttpServletResponse}
*/
public static HttpServletResponse getResponse() {
ServletRequestAttributes requestAttributes =
(ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
return requestAttributes == null ? null : requestAttributes.getResponse();
}
/**
* 查询ip地址
*
* @param request 请求
* @return {@link String}
*/
public static String getIpAddress(HttpServletRequest request) {
try {
if (request == null) {
return "";
}
// 获取请求主机IP地址,如果通过代理进来,则透过防火墙获取真实IP地址
String ip = request.getHeader("X-Forwarded-For");
if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_CLIENT_IP");
}
if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_X_FORWARDED_FOR");
}
if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
} else if (ip.length() > IP_MAX_LENGTH) {
String[] ips = ip.split(",");
for (String strIp : ips) {
if (!(UNKNOWN.equalsIgnoreCase(strIp))) {
ip = strIp;
break;
}
}
}
return ip;
} catch (Exception e) {
return "";
}
}
/**
* 获取服务部署根路径 http:// + ip + port
*
* @return {@link String}
*/
public static String getServerIpAndPort() {
//+ ":" + request.getServerPort()
return Objects.requireNonNull(getRequest()).getScheme() + "://" + getRequest().getServerName() + ":" + getRequest().getServerPort();
}
/**
* 获取当前用户浏览器信息
*
* @param request HttpServletRequest
* @return 当前用户浏览器信息
*/
public static String getHeader(HttpServletRequest request) {
return request.getHeader("User-Agent");
}
/**
* 获取当前用户浏览器型号
*
* @return 当前用户浏览器型号
*/
public static String getUserBrowser(HttpServletRequest request) {
try {
UserAgent userAgent = UserAgent.parseUserAgentString(Objects.requireNonNull(request).getHeader("User-Agent"));
Browser browser = userAgent.getBrowser();
return browser.toString();
} catch (Exception e) {
return StringUtils.EMPTY;
}
}
/**
* 获取当前用户系统型号
*
* @return 当前用户系统型号
*/
public static String getUserOperatingSystem(HttpServletRequest request) {
try {
UserAgent userAgent = UserAgent.parseUserAgentString(Objects.requireNonNull(request).getHeader("User-Agent"));
OperatingSystem operatingSystem = userAgent.getOperatingSystem();
return operatingSystem.toString();
} catch (Exception e) {
return StringUtils.EMPTY;
}
}
/**
* 获取请求头
*
* @param request 请求
* @return {@link Map}
*/
public static Map<String, Object> getRequestHeaders(HttpServletRequest request) {
Map<String, Object> headers = new HashMap<>(1 << 4);
Enumeration<String> headerNames = request.getHeaderNames();
while (headerNames.hasMoreElements()) {
String headerName = headerNames.nextElement();
headers.put(headerName, request.getHeader(headerName));
}
return headers;
}
/**
* 获取响应头
*
* @param response 响应
* @return {@link Map}
*/
public static Map<String, Object> getResponseHeaders(HttpServletResponse response) {
Map<String, Object> headers = new HashMap<>(1 << 4);
Collection<String> headerNames = response.getHeaderNames();
for (String headerName : headerNames) {
headers.put(headerName, response.getHeader(headerName));
}
return headers;
}
public static void response(HttpServletResponse response,Result<?> result) {
String resp = JSONObject.toJSONString(result);
response.setContentType("application/json;charset=utf-8");
try (PrintWriter writer = response.getWriter()) {
writer.print(resp);
} catch (IOException e) {
// NOOP
}
}
}
前端统一返回对象Result
import com.alibaba.fastjson.annotation.JSONField;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.lenton.inner.common.exception.CommonErrorCode;
import lombok.Data;
import java.util.Objects;
/**
* 前端统一返回格式
*
* @author mori
* @date 2021-07-28 12:06:00
*/
@Data
public class Result<T> {
private T data;
private String code;
private String msg;
public Result() {
}
public Result(String code, String msg) {
this(null, code, msg);
}
public Result(T data, String code) {
this(data, code, null);
}
public Result(T data, String code, String msg) {
this.data = data;
this.code = code;
this.msg = msg;
}
public static <T> Result<T> ok(T body) {
return new Result<>(body, CommonErrorCode.SUCCESS.getCode());
}
public static Result<Void> fail(String code, String msg) {
return new Result<>(code, msg);
}
/**
* 是否成功
*
* @return boolean
*/
@JSONField(serialize = false)
@JsonIgnore
public boolean isSuccess() {
return Objects.equals(CommonErrorCode.SUCCESS.getCode(), this.code);
}
/**
* 是否出错
*
* @return boolean
*/
@JSONField(serialize = false)
@JsonIgnore
public boolean isError() {
return !isSuccess();
}
}