- 宣傳官網(wǎng) http://xb.exrick.cn
- 在線Demo http://xboot.exrick.cn
- 開源版Github地址 https://github.com/Exrick/x-boot
- 開發(fā)文檔 https://www.kancloud.cn/exrick/xboot/1009234
- 獲取完整版 http://xpay.exrick.cn/pay?xboot
JWT
JSON Web Token (JWT)是一個(gè)開放標(biāo)準(zhǔn)(RFC 7519)烹笔,它定義了一種緊湊的朱巨、自包含的方式,用于作為JSON對(duì)象在各方之間安全地傳輸信息降传。該信息可以被驗(yàn)證和信任至非,因?yàn)樗菙?shù)字簽名的
官網(wǎng):https://jwt.io
- JSON Web Token由Header蜗侈、Payload、Signature三部分組成睡蟋,它們之間用圓點(diǎn)(.)連接。
一個(gè)典型的JWT看起來是這個(gè)樣子的:
xxxxx.yyyyy.zzzzz
分別對(duì)應(yīng):Header.Payload.Signature
Header
header典型的由兩部分組成:token的類型(“JWT”)和算法名稱(比如:HMAC SHA256或者RSA等等)枷颊。
例如:
{
"alg": "HS256",
"typ": "JWT"
}
用Base64對(duì)這個(gè)JSON編碼就得到JWT的第一部分
Payload
JWT的第二部分是payload戳杀,通常在這部分存入交互信息,XBoot中存入了用戶名和用戶權(quán)限(避免每次請(qǐng)求再次讀取用戶權(quán)限)以及token失效時(shí)間夭苗。
例如:
{
"sub": "admin",
"authorities": "["添加用戶","ROLE_ADMIN"]",
"exp": 1555554537
}
對(duì)payload進(jìn)行Base64編碼就得到JWT的第二部分
注意:簽名并不是加密信卡,任何人都能看到JWT里的內(nèi)容,除非它們是加密的题造,因此請(qǐng)勿放置明文敏感信息至JWT中
Signature
簽名是用于驗(yàn)證消息在傳遞過程中有沒有被更改傍菇,并且對(duì)于使用私鑰簽名的token,它還可以驗(yàn)證JWT的發(fā)送方是否為它所稱的發(fā)送方界赔。
例如:
HMACSHA256(base64UrlEncode(header) + "." + base64UrlEncode(payload), secret)
JWT缺點(diǎn):JWT是無法撤銷的丢习,除非是達(dá)到了設(shè)定的過期時(shí)間,且刷新Token機(jī)制麻煩淮悼。解決方案:XBoot中可配置使用Redis記錄咐低,60分鐘內(nèi)(可配置)無請(qǐng)求自動(dòng)失效,可隨時(shí)管理token袜腥,詳見代碼
Spring Security整合
- 添加依賴
<!-- Spring Security -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<!-- JWT -->
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency>
- Spring Security核心配置入口
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled=true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
...
@Autowired
private AuthenticationSuccessHandler successHandler;
@Autowired
private AuthenticationFailHandler failHandler;
@Autowired
private RestAccessDeniedHandler accessDeniedHandler;
@Override
protected void configure(HttpSecurity http) throws Exception {
...
registry.and()
...
//成功處理類
.successHandler(successHandler)
//失敗
.failureHandler(failHandler)
//關(guān)閉跨站請(qǐng)求防護(hù)
.csrf().disable()
//前后端分離采用JWT 不需要session
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
//自定義權(quán)限拒絕處理類
.exceptionHandling().accessDeniedHandler(accessDeniedHandler)
.and()
//添加JWT過濾器 除已配置的其它請(qǐng)求都需經(jīng)過此過濾器
.addFilter(new JWTAuthenticationFilter(authenticationManager()));
}
}
- JWT過濾器 認(rèn)證處理類
public class JWTAuthenticationFilter extends BasicAuthenticationFilter {
public JWTAuthenticationFilter(AuthenticationManager authenticationManager) {
super(authenticationManager);
}
public JWTAuthenticationFilter(AuthenticationManager authenticationManager, AuthenticationEntryPoint authenticationEntryPoint) {
super(authenticationManager, authenticationEntryPoint);
}
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
String header = request.getHeader(SecurityConstant.HEADER);
if(StrUtil.isBlank(header)){
header = request.getParameter(SecurityConstant.HEADER);
}
Boolean notValid = StrUtil.isBlank(header) || (!tokenRedis && !header.startsWith(SecurityConstant.TOKEN_SPLIT));
if (notValid) {
chain.doFilter(request, response);
return;
}
try {
UsernamePasswordAuthenticationToken authentication = getAuthentication(header, response);
SecurityContextHolder.getContext().setAuthentication(authentication);
}catch (Exception e){
e.toString();
}
chain.doFilter(request, response);
}
private UsernamePasswordAuthenticationToken getAuthentication(String header, HttpServletResponse response) {
// 用戶名
String username = null;
// 權(quán)限
List<GrantedAuthority> authorities = new ArrayList<>();
// JWT
try {
// 解析token
Claims claims = Jwts.parser()
.setSigningKey(SecurityConstant.JWT_SIGN_KEY)
.parseClaimsJws(header.replace(SecurityConstant.TOKEN_SPLIT, ""))
.getBody();
// 獲取用戶名
username = claims.getSubject();
String authority = claims.get(SecurityConstant.AUTHORITIES).toString();
if(StrUtil.isNotBlank(authority)){
List<String> list = new Gson().fromJson(authority, new TypeToken<List<String>>(){}.getType());
for(String ga : list){
authorities.add(new SimpleGrantedAuthority(ga));
}
}
} catch (ExpiredJwtException e) {
ResponseUtil.out(response, ResponseUtil.resultMap(false,401,"登錄已失效见擦,請(qǐng)重新登錄"));
} catch (Exception e){
log.error(e.toString());
ResponseUtil.out(response, ResponseUtil.resultMap(false,500,"解析token錯(cuò)誤"));
}
if(StrUtil.isNotBlank(username)) {
// 踩坑提醒 此處password不能為null
User principal = new User(username, "", authorities);
return new UsernamePasswordAuthenticationToken(principal, null, authorities);
}
return null;
}
}
- 成功處理類
@Slf4j
@Component
public class AuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {
@Value("${xboot.tokenExpireTime}")
private Integer tokenExpireTime;
@Value("${xboot.saveLoginTime}")
private Integer saveLoginTime;
@Override
@SystemLog(description = "登錄系統(tǒng)", type = LogType.LOGIN)
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
//用戶選擇保存登錄狀態(tài)幾天
String saveLogin = request.getParameter(SecurityConstant.SAVE_LOGIN);
...
String username = ((UserDetails)authentication.getPrincipal()).getUsername();
List<GrantedAuthority> authorities = (List<GrantedAuthority>) ((UserDetails)authentication.getPrincipal()).getAuthorities();
List<String> list = new ArrayList<>();
for(GrantedAuthority g : authorities){
list.add(g.getAuthority());
}
// 登陸成功生成token
String token = SecurityConstant.TOKEN_SPLIT + Jwts.builder()
//主題 放入用戶名
.setSubject(username)
//自定義屬性 放入用戶擁有請(qǐng)求權(quán)限
.claim(SecurityConstant.AUTHORITIES, new Gson().toJson(list))
//失效時(shí)間
.setExpiration(new Date(System.currentTimeMillis() + tokenExpireTime * 60 * 1000))
//簽名算法和密鑰
.signWith(SignatureAlgorithm.HS512, SecurityConstant.JWT_SIGN_KEY)
.compact();
ResponseUtil.out(response, ResponseUtil.resultMap(true,200,"登錄成功", token));
}
}
- 失敗處理類
@Slf4j
@Component
public class AuthenticationFailHandler extends SimpleUrlAuthenticationFailureHandler {
...
@Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
...
if (e instanceof UsernameNotFoundException || e instanceof BadCredentialsException) {
ResponseUtil.out(response, ResponseUtil.resultMap(false,500,"用戶名或密碼錯(cuò)誤"));
} else if (e instanceof DisabledException) {
ResponseUtil.out(response, ResponseUtil.resultMap(false,500,"賬戶被禁用,請(qǐng)聯(lián)系管理員"));
} else if (e instanceof LoginFailLimitException){
ResponseUtil.out(response, ResponseUtil.resultMap(false,500,((LoginFailLimitException) e).getMsg()));
} else {
ResponseUtil.out(response, ResponseUtil.resultMap(false,500,"登錄失敗羹令,其他內(nèi)部錯(cuò)誤"));
}
}
}
- 自定義權(quán)限拒絕處理類
@Component
public class RestAccessDeniedHandler implements AccessDeniedHandler {
@Override
public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException)
throws IOException, ServletException {
ResponseUtil.out(response, ResponseUtil.resultMap(false,403,"抱歉鲤屡,您沒有訪問權(quán)限"));
}
}