##SpringBoot集成JWT(極簡版) ###在WebConfig配置類中設置介面統一首碼 import org.springframework.context.annotation.Configuration; import org.springframework.web.bind.anno ...
SpringBoot集成JWT(極簡版)
在WebConfig配置類中設置介面統一首碼
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.config.annotation.PathMatchConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void configurePathMatch(PathMatchConfigurer configurer) {
// 指定controller統一的介面首碼
configurer.addPathPrefix("/api", clazz -> clazz.isAnnotationPresent(RestController.class));
}
}
導入JWT依賴
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>3.10.3</version>
</dependency>
JWT工具類TokenUtils.java(生成token的工具類)
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.bai.entity.Admin;
import com.bai.service.AdminService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
@Component
@Slf4j
public class TokenUtils {
private static AdminService staticAdminService;
@Resource
private AdminService adminService;
@PostConstruct
public void setUserService() {
staticAdminService = adminService;
}
/**
* 生成token
*
* @return
*/
public static String genToken(String adminId, String sign) {
return JWT.create().withAudience(adminId) // 將 user id 保存到 token 裡面,作為載荷
.withExpiresAt(DateUtil.offsetHour(new Date(), 2)) // 2小時後token過期
.sign(Algorithm.HMAC256(sign)); // 以 password 作為 token 的密鑰
}
/**
* 獲取當前登錄的用戶信息
*
* @return user對象
* /admin?token=xxxx
*/
public static Admin getCurrentAdmin() {
String token = null;
try {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
token = request.getHeader("token");
if (StrUtil.isNotBlank(token)) {
token = request.getParameter("token");
}
if (StrUtil.isBlank(token)) {
log.error("獲取當前登錄的token失敗, token: {}", token);
return null;
}
String adminId = JWT.decode(token).getAudience().get(0);
return staticAdminService.getById(Integer.valueOf(adminId));
} catch (Exception e) {
log.error("獲取當前登錄的管理員信息失敗, token={}", token, e);
return null;
}
}
}
攔截器JwtInterceptor.java
import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.bai.entity.Admin;
import com.bai.exception.ServiceException;
import com.bai.service.AdminService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
@Component
@Slf4j
public class LoginJWTInterceptor implements HandlerInterceptor {
private static final String ERROR_CODE_401 = "401";
@Autowired
private AdminService adminService;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
//這裡是判斷瀏覽器請求頭裡的token
String token = request.getHeader("token");
if (StrUtil.isBlank(token)) {
token = request.getParameter("token");
}
// 執行認證
if (StrUtil.isBlank(token)) {
throw new ServiceException(ERROR_CODE_401, "無token,請重新登錄");
}
// 獲取 token 中的adminId
String adminId;
Admin admin;
try {
adminId = JWT.decode(token).getAudience().get(0);
// 根據token中的userid查詢資料庫
admin = adminService.getById(Integer.parseInt(adminId));
} catch (Exception e) {
String errMsg = "token驗證失敗,請重新登錄";
log.error(errMsg + ", token=" + token, e);
throw new ServiceException(ERROR_CODE_401, errMsg);
}
if (admin == null) {
throw new ServiceException(ERROR_CODE_401, "用戶不存在,請重新登錄");
}
try {
// 用戶密碼加簽驗證 token
JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(admin.getPassword())).build();
jwtVerifier.verify(token); // 驗證token
} catch (JWTVerificationException e) {
throw new ServiceException(ERROR_CODE_401, "token驗證失敗,請重新登錄");
}
return true;
}
}
在WebConfig配置類中添加自定義攔截器
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.PathMatchConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Autowired
private LoginJWTInterceptor loginJWTInterceptor;
@Override
public void configurePathMatch(PathMatchConfigurer configurer) {
// 指定controller統一的介面首碼
configurer.addPathPrefix("/api", clazz -> clazz.isAnnotationPresent(RestController.class));
}
// 加自定義攔截器JwtInterceptor,設置攔截規則
//.excludePathPatterns("/api/admin/login");放開登錄介面,因為登錄的時候還沒有token
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(loginJWTInterceptor) // 添加所有路徑需要校驗
.addPathPatterns("/api/**").excludePathPatterns("/api/admin/login", "/api/admin/register");//不需要攔截的介面
}
}
設置自定義頭配置(前端在request攔截器設置自定義頭)
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
@Configuration
public class CrosConfiguration {
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.addAllowedOrigin("*"); // 1 設置訪問源地址
corsConfiguration.addAllowedHeader("*"); // 2 設置訪問源請求頭
corsConfiguration.addAllowedMethod("*"); // 3 設置訪問源請求方法
source.registerCorsConfiguration("/**", corsConfiguration); // 4 對介面配置跨域設置
return new CorsFilter(source);
}
}