使用JWT(JSON WEB TOKEN)工具, <artifactId>jjwt</artifactId>
生成token方式
package com.travelsky.auto.token; import com.travelsky.config.TokenConfig; import io.jsonwebtoken.*; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.stereotype.Component; import java.sql.Date; import java.time.LocalDateTime; import java.time.ZoneId; /** * token工廠 */ @Component @Slf4j public class TokenFactory { @Autowired private TokenConfig tokenConfig; /** * 生成token * @param key * @return
*/
public TokenContent createToken(final String key) { final LocalDateTime now = LocalDateTime.now(); // Claims保存主題信息
final Claims claims = Jwts.claims().setSubject(tokenConfig.getSubject()); final String token = Jwts.builder() // 設置信息
.setClaims(claims) // 設置主體
.setIssuer(tokenConfig.getIssuer()) // 設置創建時間
.setIssuedAt(Date.from(now.atZone(ZoneId.systemDefault()).toInstant())) // 設置過期時間
.setExpiration(Date.from(now.plusMinutes(tokenConfig.getExpiration()).atZone(ZoneId.systemDefault()).toInstant())) // 使用HS512加密
.signWith(SignatureAlgorithm.HS512, key) // 生成字符串token
.compact(); return new TokenContent(token, claims); }
根據前端取回的token進行驗證方式
package com.travelsky.auto.token; import com.travelsky.config.TokenConfig; import io.jsonwebtoken.*; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.stereotype.Component; import java.sql.Date; import java.time.LocalDateTime; import java.time.ZoneId; /** * token工廠 */ @Component @Slf4j public class TokenFactory { @Autowired private TokenConfig tokenConfig; /** * 驗證token * @param key 與subject一致 * @param token 頁面傳回的token字符串 */
void parser(final String key, final String token) { try { // 驗證token
Jwts.parser().setSigningKey(key).parseClaimsJws(token); } catch (UnsupportedJwtException | MalformedJwtException | IllegalArgumentException | SignatureException ex) { log.error("不可用Invalid Token", ex); throw new BadCredentialsException("驗證失敗,Token不可用:Invalid token: ", ex); } catch (ExpiredJwtException expiredEx) { log.info("過期Token is expired", expiredEx); throw new ExpiredTokenException("token過期", expiredEx); } } }
token配置類
package com.travelsky.config; import lombok.Data; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Configuration; @Configuration @Data @ConfigurationProperties(prefix = "token") public class TokenConfig { private String issuer; private Long expiration; private String subject; }
token配置文件
token: issuer: antlord expiration: 20 subject: token