记录一下使用Springboot集成JWT实现登录注册,以后有用到直接copy即可。
整体流程
依赖
<!--引入jwt-->
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>3.4.0</version>
</dependency>
<!-- MD5加密依赖 -->
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
</dependency>
工具类
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.huishi.entity.MapUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
@Slf4j
public class SecurityUtils {
public static String md5(String src) {
return DigestUtils.md5Hex(src);
}
//密钥盐
private static final String salt = "1a2b3c4d";
/**
* 密码加密
* @param inputPass
* @return
*/
public static String inputPassToFormPass(String inputPass) {
String str = "" + salt.charAt(0) + salt.charAt(2) + inputPass + salt.charAt(5) + salt.charAt(4);
System.out.println(str);
return md5(str);
}
public static String formPassToDBPass(String formPass, String salt) {
String str = "" + salt.charAt(0) + salt.charAt(2) + formPass + salt.charAt(5) + salt.charAt(4);
return md5(str);
}
public static String inputPassToDbPass(String inputPass, String saltDB) {
String formPass = inputPassToFormPass(inputPass);
String dbPass = formPassToDBPass(formPass, saltDB);
return dbPass;
}
/**
* 生成token
*
* @param mapUser
* @param tokenExpireTime
* @param tokenSecret
* @return
*/
public static String genToken(MapUser mapUser, Integer tokenExpireTime, String tokenSecret) {
Date expireAt = new Date(System.currentTimeMillis() + tokenExpireTime * 60 * 1000);
return JWT.create()
//发行人
.withIssuer("auth0")
//存放数据
.withClaim("userId", mapUser.getId())
.withClaim("username", mapUser.getUserName())
.withClaim("password", mapUser.getPassword())
//过期时间
.withExpiresAt(expireAt)
.sign(Algorithm.HMAC256(tokenSecret));
}
/**
* 对token进行验证
*
* @param token
* @param tokenSecret
* @return
*/
public static Boolean verifyToken(String token, String tokenSecret) {
DecodedJWT decodedJWT = null;
try {
//创建token验证器
JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(tokenSecret)).withIssuer("auth0").build();
decodedJWT = jwtVerifier.verify(token);
log.info("token认证通过,用户:{},过期时间:{}", getUserName(token), decodedJWT.getExpiresAt());
} catch (IllegalArgumentException | JWTVerificationException e) {
//抛出错误即为验证不通过
log.error("token认证失败,用户:{}", getUserName(token));
return false;
}
return true;
}
public static String getUserName(String token) {
return JWT.decode(token).getClaims().get("username").asString();
}
public static Long getUserId(String token) {
if (token == null) return null;
return JWT.decode(token).getClaims().get("userId").asLong();
}
public static String getToken(HttpServletRequest request) {
String authHeader = request.getHeader("Authorization");
if (authHeader != null && authHeader.startsWith("Bearer ")) {
return authHeader.replace("Bearer ", "");
}
return null;
}
}
注册和登录
@Override
public ResponseResult register(MapUser mapUser) {
mapUser.setPassword(SecurityUtils.inputPassToFormPass(mapUser.getPassword()));
return ResponseResult.success(mapUserMapper.insert(mapUser));
}
@Override
public ResponseResult login(MapUser mapUser) {
String password = SecurityUtils.inputPassToFormPass(mapUser.getPassword());
MapUser user = mapUserMapper.findByName(mapUser.getUserName());
if (user == null) throw new ServiceException("用户不存在");
if (!password.equals(user.getPassword())) throw new ServiceException("密码错误");
String token = SecurityUtils.genToken(user, tokenExpireTime, tokenSecret);
MapConfig mapConfig = mapConfigMapper.getByUserId(user.getId());
Map<String, Object> result = new HashMap<>();
result.put("token", token);
result.put("mapConfig", mapConfig.conventEntity());
return ResponseResult.success(result);
}
拦截器
import com.alibaba.fastjson.JSONObject;
import com.huishi.util.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* token拦截器
*/
@Component
@Slf4j
public class TokenInterceptor implements HandlerInterceptor {
@Value("${token.header}")
private String tokenHeader;
@Value("${token.prefix}")
private String tokenPrefix;
@Value("${token.secret}")
private String tokenSecret;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String authHeader = request.getHeader(tokenHeader);
if (authHeader != null && authHeader.startsWith(tokenPrefix)) {
String token = authHeader.replace(tokenPrefix + " ", "");
if (SecurityUtils.verifyToken(token, tokenSecret)) return true;
}
String requestURI = request.getRequestURI();
JSONObject json = new JSONObject();
json.put("msg", "请求:" + requestURI + ",认证失败,无法访问资源");
json.put("code", "401");
response.setContentType("application/json;charset=UTF-8");
response.getWriter().append(json.toString());
return false;
}
}
配置拦截器
import com.huishi.server.interceptor.TokenInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Autowired
private TokenInterceptor tokenInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(tokenInterceptor)
.addPathPatterns("/**")
.excludePathPatterns("/map/user/register", "/map/user/login", "/map/plane/getNewest", "/map/plane/tracePlaneInfo",
"/map/config/get/**",
"/swagger-ui.html",
"/webjars/**",
"/swagger-resources/**");
}
}