下面列出了怎么用io.jsonwebtoken.UnsupportedJwtException的API类实例代码及写法,或者点击链接到github查看源代码。
/**
*
* @param jwt json web token
* @return 解签实体
* @throws ExpiredJwtException token过期
* @throws UnsupportedJwtException 不支持的TOKEN
* @throws MalformedJwtException 参数格式形变等异常
* @throws SignatureException 签名异常
* @throws IllegalArgumentException 非法参数
*/
public static Claims parseJwt(String jwt) throws ExpiredJwtException, UnsupportedJwtException, MalformedJwtException, SignatureException, IllegalArgumentException {
return Jwts.parser()
.setSigningKey(DatatypeConverter.parseBase64Binary(secretKey))
.parseClaimsJws(jwt)
.getBody();
// 令牌ID -- claims.getId()
// 客户标识 -- claims.getSubject()
// 客户标识
// 签发者 -- claims.getIssuer()
// 签发时间 -- claims.getIssuedAt()
// 接收方 -- claims.getAudience()
// 访问主张-角色 -- claims.get("roles", String.class)
// 访问主张-权限 -- claims.get("perms", String.class)
}
private Jws<Claims> parseTokenFromBase64EncodedString(final String base64EncodedToken) throws JwtException {
try {
return Jwts.parser().setSigningKeyResolver(new SigningKeyResolverAdapter() {
@Override
public byte[] resolveSigningKeyBytes(JwsHeader header, Claims claims) {
final String identity = claims.getSubject();
// Get the key based on the key id in the claims
final Integer keyId = claims.get(KEY_ID_CLAIM, Integer.class);
final Key key = keyService.getKey(keyId);
// Ensure we were able to find a key that was previously issued by this key service for this user
if (key == null || key.getKey() == null) {
throw new UnsupportedJwtException("Unable to determine signing key for " + identity + " [kid: " + keyId + "]");
}
return key.getKey().getBytes(StandardCharsets.UTF_8);
}
}).parseClaimsJws(base64EncodedToken);
} catch (final MalformedJwtException | UnsupportedJwtException | SignatureException | ExpiredJwtException | IllegalArgumentException | AdministrationException e) {
// TODO: Exercise all exceptions to ensure none leak key material to logs
final String errorMessage = "Unable to validate the access token.";
throw new JwtException(errorMessage, e);
}
}
/**
* 跳转到主页面数据处理
*
* @author: quhailong
* @date: 2019/9/27
*/
public String homeHandle(Model model) {
String token = CookieUtils.getCookie("token");
if (!StringUtils.isEmpty(token)) {
try {
if (jedisClusterUtil.isExistKey("LOGOUT:" + token)) {
return "login";
} else {
UserInfoDTO userInfoDTO = tokenAnalysisUtils.tokenAnalysis(token);
model.addAttribute("name", userInfoDTO.getUserName());
return "index";
}
} catch (ExpiredJwtException | UnsupportedJwtException | MalformedJwtException | SignatureException | IllegalArgumentException exception) {
exception.printStackTrace();
return "user";
}
}
return "login";
}
/**
* 跳转到分享管理页面数据处理
*
* @author: quhailong
* @date: 2019/9/27
*/
public String shareHandle(Model model) {
String token = CookieUtils.getCookie("token");
if (!StringUtils.isEmpty(token)) {
try {
if (jedisClusterUtil.isExistKey("LOGOUT:" + token)) {
return "login";
} else {
UserInfoDTO userInfoDTO = tokenAnalysisUtils.tokenAnalysis(token);
model.addAttribute("name", userInfoDTO.getUserName());
return "share";
}
} catch (ExpiredJwtException | UnsupportedJwtException | MalformedJwtException | SignatureException | IllegalArgumentException exception) {
exception.printStackTrace();
return "user";
}
}
return "login";
}
private Jws<Claims> parseTokenFromBase64EncodedString(final String base64EncodedToken) throws JwtException {
try {
return Jwts.parser().setSigningKeyResolver(new SigningKeyResolverAdapter() {
@Override
public byte[] resolveSigningKeyBytes(JwsHeader header, Claims claims) {
final String identity = claims.getSubject();
// Get the key based on the key id in the claims
final String keyId = claims.get(KEY_ID_CLAIM, String.class);
final Key key = keyService.getKey(keyId);
// Ensure we were able to find a key that was previously issued by this key service for this user
if (key == null || key.getKey() == null) {
throw new UnsupportedJwtException("Unable to determine signing key for " + identity + " [kid: " + keyId + "]");
}
return key.getKey().getBytes(StandardCharsets.UTF_8);
}
}).parseClaimsJws(base64EncodedToken);
} catch (final MalformedJwtException | UnsupportedJwtException | SignatureException | ExpiredJwtException | IllegalArgumentException e) {
// TODO: Exercise all exceptions to ensure none leak key material to logs
final String errorMessage = "Unable to validate the access token.";
throw new JwtException(errorMessage, e);
}
}
@Override
protected Object getPreAuthenticatedPrincipal(HttpServletRequest request) {
String jwtHeader = request.getHeader(JWT_HEADER_NAME);
if (jwtHeader == null) {
return null;
}
String encodedJwt = jwtHeader;
try {
Claims claims = Jwts.parser()
.setSigningKey(DatatypeConverter.parseBase64Binary(backendSecret))
.parseClaimsJws(encodedJwt)
.getBody();
AuthnContext authnContext = getAuthnContext(claims);
log.info("Attempting login with userid={} and level={}", claims.getSubject(), authnContext);
return new UsernameContextPrincipal(claims.getSubject(), authnContext);
} catch (UnsupportedJwtException jwtException) {
throw new PreAuthenticatedCredentialsNotFoundException("Invalid JWT Token", jwtException);
}
}
private Jws<Claims> parseTokenFromBase64EncodedString(final String base64EncodedToken) throws JwtException {
try {
return Jwts.parser().setSigningKeyResolver(new SigningKeyResolverAdapter() {
@Override
public byte[] resolveSigningKeyBytes(JwsHeader header, Claims claims) {
final String identity = claims.getSubject();
// Get the key based on the key id in the claims
final Integer keyId = claims.get(KEY_ID_CLAIM, Integer.class);
final Key key = keyService.getKey(keyId);
// Ensure we were able to find a key that was previously issued by this key service for this user
if (key == null || key.getKey() == null) {
throw new UnsupportedJwtException("Unable to determine signing key for " + identity + " [kid: " + keyId + "]");
}
return key.getKey().getBytes(StandardCharsets.UTF_8);
}
}).parseClaimsJws(base64EncodedToken);
} catch (final MalformedJwtException | UnsupportedJwtException | SignatureException | ExpiredJwtException | IllegalArgumentException | AdministrationException e) {
// TODO: Exercise all exceptions to ensure none leak key material to logs
final String errorMessage = "Unable to validate the access token.";
throw new JwtException(errorMessage, e);
}
}
public Key getKey(SignatureAlgorithm algorithm)
{
if (algorithm.isHmac()) {
if (hmacKey == null) {
throw new UnsupportedJwtException(format("JWT is signed with %s, but no HMAC key is configured", algorithm));
}
return new SecretKeySpec(hmacKey, algorithm.getJcaName());
}
if (publicKey == null) {
throw new UnsupportedJwtException(format("JWT is signed with %s, but no key is configured", algorithm));
}
return publicKey;
}
@Override
protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
try {
Authentication authentication = TokenAuthenticationHelper.getAuthentication(httpServletRequest);
// 对用 token 获取到的用户进行校验
SecurityContextHolder.getContext().setAuthentication(authentication);
filterChain.doFilter(httpServletRequest, httpServletResponse);
} catch (ExpiredJwtException | UnsupportedJwtException | MalformedJwtException |
SignatureException | IllegalArgumentException e) {
httpServletResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Token expired,登陆已过期");
}
}
/**
* Make sure Jwt created is formatted according to the Google Cloud IoT Core<a
* href="https://cloud.google.com/iot/docs/how-tos/credentials/jwts#jwt_composition">spec</a>.
*/
@Test
public void testCreateJwtEc() throws JoseException {
JwtGenerator jwtGenerator =
new JwtGenerator(EC_KEY_PAIR, JWT_AUDIENCE, TOKEN_LIFETIME, TEST_CLOCK);
String rawJwt = jwtGenerator.createJwt();
// Validate JWT
Jws<Claims> parsedJwt;
try {
parsedJwt = Jwts.parser()
.setSigningKey(EC_KEY_PAIR.getPublic())
.parseClaimsJws(rawJwt);
} catch (UnsupportedJwtException | MalformedJwtException | SignatureException e) {
fail("Error parsing JWT: " + e);
return; // Satisfy compiler
}
JwsHeader header = parsedJwt.getHeader();
Claims claims = parsedJwt.getBody();
assertThat(header.getAlgorithm()).isEqualTo("ES256");
assertThat(header.getType()).isEqualTo("JWT");
assertThat(claims.getAudience()).isEqualTo(JWT_AUDIENCE);
// JWT requires time in seconds from epoch, not millis, so allow issue time within one
// second.
assertThat(claims.getIssuedAt().getTime()).isAtLeast(TEST_CLOCK.millis() - 1000);
assertThat(claims.getIssuedAt().getTime()).isAtMost(TEST_CLOCK.millis() + 1000);
// Check expiration time within one second of issue time + TOKEN_LIFETIME
assertThat(claims.getExpiration().getTime())
.isLessThan(Clock.offset(TEST_CLOCK, TOKEN_LIFETIME.plusSeconds(1)).millis());
assertThat(claims.getExpiration().getTime())
.isAtLeast(Clock.offset(TEST_CLOCK, TOKEN_LIFETIME.minusSeconds(1)).millis());
}
@Override
protected void doFilterInternal(final HttpServletRequest request, final HttpServletResponse response, final FilterChain filterChain) throws ServletException,
IOException {
try {
Authentication authentication = TokenAuthenticationHelper.getAuthentication(request);
SecurityContextHolder.getContext().setAuthentication(authentication);
filterChain.doFilter(request, response);
} catch (ExpiredJwtException | UnsupportedJwtException | MalformedJwtException |
SignatureException | IllegalArgumentException e) {
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Token expired");
}
}
private String getUserIfValid(String token) {
Key key = new SecretKeySpec("secret".getBytes(), "DES");
try {
Jws<Claims> claims = Jwts.parser().setSigningKey(key)
.parseClaimsJws(token);
String scope = claims.getBody().get("scope", String.class);
System.out.println("scope " + scope);
return claims.getBody().getSubject();
} catch (ExpiredJwtException | MalformedJwtException | SignatureException | UnsupportedJwtException | IllegalArgumentException e) {
//don't trust the JWT!
e.printStackTrace();
throw new NotAuthorizedException("Invalid JWT");
}
}
private String getUserIfValid(String token) {
Key key = new SecretKeySpec("secret".getBytes(), "DES");
try {
Jws<Claims> claims = Jwts.parser().setSigningKey(key)
.parseClaimsJws(token);
String scope = claims.getBody().get("scope", String.class);
System.out.println("scope " + scope);
return claims.getBody().getSubject();
} catch (ExpiredJwtException | MalformedJwtException | SignatureException | UnsupportedJwtException | IllegalArgumentException e) {
//don't trust the JWT!
throw new NotAuthorizedException("Invalid JWT");
}
}
@Test(expectedExceptions = {JOSEException.class, AlgorithmMismatchException.class, InvalidJwtException.class, UnsupportedJwtException.class},
description = "Illustrate validation of signature algorithm")
public void testFailSignatureAlgorithm() throws Exception {
HashSet<TokenUtils.InvalidClaims> invalidFields = new HashSet<>();
invalidFields.add(TokenUtils.InvalidClaims.ALG);
String token = TokenUtils.generateTokenString("/Token1.json", invalidFields);
RSAPublicKey publicKey = (RSAPublicKey) TokenUtils.readPublicKey("/publicKey.pem");
int expGracePeriodSecs = 60;
validateToken(token, publicKey, TEST_ISSUER, expGracePeriodSecs);
}
private Jws<Claims> parseToken(final String token) {
if (token != null) {
try {
return Jwts.parser().setSigningKey(secretKey).parseClaimsJws(token);
} catch (ExpiredJwtException | UnsupportedJwtException | MalformedJwtException
| SignatureException | IllegalArgumentException e) {
return null;
}
}
return null;
}
@Override
public Jwt<Header, Claims> parseClaimsJwt(String claimsJwt) {
try {
return parse(claimsJwt, new JwtHandlerAdapter<Jwt<Header, Claims>>() {
@Override
public Jwt<Header, Claims> onClaimsJwt(Jwt<Header, Claims> jwt) {
return jwt;
}
});
} catch (IllegalArgumentException iae) {
throw new UnsupportedJwtException("Signed JWSs are not supported.", iae);
}
}
@Override
public Jws<String> parsePlaintextJws(String plaintextJws) {
try {
return parse(plaintextJws, new JwtHandlerAdapter<Jws<String>>() {
@Override
public Jws<String> onPlaintextJws(Jws<String> jws) {
return jws;
}
});
} catch (IllegalArgumentException iae) {
throw new UnsupportedJwtException("Signed JWSs are not supported.", iae);
}
}
/**
* Parses and validates JWT Token signature.
*
* @throws BadCredentialsException
* @throws JwtExpiredTokenException
*
*/
public Jws<Claims> parseClaims(String signingKey) {
try {
return Jwts.parser().setSigningKey(signingKey).parseClaimsJws(this.token);
} catch (UnsupportedJwtException | MalformedJwtException | IllegalArgumentException | SignatureException ex) {
logger.error("Invalid JWT Token", ex);
throw new BadCredentialsException("Invalid JWT token: ", ex);
} catch (ExpiredJwtException expiredEx) {
logger.info("JWT Token is expired", expiredEx);
throw new JwtExpiredTokenException(this, "JWT Token expired", expiredEx);
}
}
/**
* Parses and validates JWT Token signature.
*
* @throws BadCredentialsException
* @throws JwtExpiredTokenException
*
*/
public Jws<Claims> parseClaims(String signingKey) {
try {
return Jwts.parser().setSigningKey(signingKey).parseClaimsJws(this.token);
} catch (UnsupportedJwtException | MalformedJwtException | IllegalArgumentException | SignatureException ex) {
logger.error("Invalid JWT Token", ex);
throw new BadCredentialsException("Invalid JWT token: ", ex);
} catch (ExpiredJwtException expiredEx) {
logger.info("JWT Token is expired", expiredEx);
throw new JwtExpiredTokenException(this, "JWT Token expired", expiredEx);
}
}
@Override
public Jwt<Header, Claims> parseClaimsJwt(String claimsJwt) {
try {
return parse(claimsJwt, new JwtHandlerAdapter<Jwt<Header, Claims>>() {
@Override
public Jwt<Header, Claims> onClaimsJwt(Jwt<Header, Claims> jwt) {
return jwt;
}
});
} catch (IllegalArgumentException iae) {
throw new UnsupportedJwtException("Signed JWSs are not supported.", iae);
}
}
@Override
public Jws<String> parsePlaintextJws(String plaintextJws) {
try {
return parse(plaintextJws, new JwtHandlerAdapter<Jws<String>>() {
@Override
public Jws<String> onPlaintextJws(Jws<String> jws) {
return jws;
}
});
} catch (IllegalArgumentException iae) {
throw new UnsupportedJwtException("Signed JWSs are not supported.", iae);
}
}
/**
* 查看分享页面数据处理
*
* @author: quhailong
* @date: 2019/9/27
*/
public String sHandle(Model model, String shareId) {
String token = CookieUtils.getCookie("token");
if (!StringUtils.isEmpty(token)) {
try {
if (jedisClusterUtil.isExistKey("LOGOUT:" + token)) {
return "login";
} else {
UserInfoDTO userInfoDTO = tokenAnalysisUtils.tokenAnalysis(token);
String getShareUserUrl = "http://localhost:8095/api/share/getshareuser?shareId=" + shareId;
String resultString = HttpClientUtils.HttpGet(getShareUserUrl);
RestAPIResult restAPIResult = JSONUtils.parseObject(resultString, RestAPIResult.class);
Map<String, Object> map = restAPIResult.getRespMap();
UserInfoDTO shareUserInfoDTO = JSONUtils.parseObject((String) map.get("userinfo"), UserInfoDTO.class);
if (shareUserInfoDTO == null) {
model.addAttribute("name", userInfoDTO.getUserName());
return "sError";
} else if (shareUserInfoDTO.getUserId().equals(userInfoDTO.getUserId())) {
model.addAttribute("name", userInfoDTO.getUserName());
return "share";
}
ShareDTO shareDTO = JSONUtils.parseObject((String) map.get("share"), ShareDTO.class);
if (shareDTO.getExpiration() != null && shareDTO.getExpiration().getTime() - (new Date().getTime()) < 0) {
return "sError";
}
model.addAttribute("name", userInfoDTO.getUserName());
model.addAttribute("shareUser", shareUserInfoDTO.getUserName());
if (shareDTO.getMultiWhether() == 1) {
model.addAttribute("shareName", shareDTO.getTheme() + "等文件");
} else {
model.addAttribute("shareName", shareDTO.getTheme() + "文件");
}
String addShareViewCountUrl = "http://localhost:8095/api/share/addshareview";
AddShareViewCountRequest addShareViewCountRequest = new AddShareViewCountRequest();
addShareViewCountRequest.setShareId(shareId);
HttpClientUtils.httpPostWithJSON(addShareViewCountUrl, JSONUtils.toJSONString(addShareViewCountRequest));
model.addAttribute("shareId", shareDTO.getShareId());
return "s";
}
} catch (ExpiredJwtException | UnsupportedJwtException | MalformedJwtException | SignatureException | IllegalArgumentException exception) {
exception.printStackTrace();
return "user";
}
}
return "login";
}
private String extractUserId(HttpServletRequest httpRequest, String workspaceId) {
// First search in the session fro activity notification coming from the client
final HttpSession session = httpRequest.getSession();
Subject subject = (Subject) session.getAttribute("che_subject");
if (subject != null) {
String userId = subject.getUserId();
if (userId != null) {
return userId;
}
}
// Then search in the machine token for activity notification coming from the agents
final String token = tokenExtractor.getToken(httpRequest);
if (isNullOrEmpty(token)) {
return null;
}
// check token signature and verify is this token machine or not
try {
final Jws<Claims> jwt =
Jwts.parser()
.setSigningKey(keyManager.getOrCreateKeyPair(workspaceId).getPublic())
.parseClaimsJws(token);
final Claims claims = jwt.getBody();
if (MACHINE_TOKEN_KIND.equals(jwt.getHeader().get("kind"))) {
return claims.get(USER_ID_CLAIM, String.class);
}
} catch (UnsupportedJwtException
| MalformedJwtException
| SignatureException
| SignatureKeyManagerException
| ExpiredJwtException
| IllegalArgumentException ex) {
LOG.warn("Could not get a user Id from a machine token", ex);
}
return null;
}
public PolicyFailure unsupportedJwt(IPolicyContext context, UnsupportedJwtException e) {
return createAuthenticationPolicyFailure(context, AUTH_JWT_UNSUPPORTED_JWT,
Messages.getString("JWTPolicy.NoTransportSecurity")); //$NON-NLS-1$
}
protected SakaiAccessToken getSakaiAccessToken(Key publicKey, HttpServletRequest request, HttpServletResponse response) {
String authorization = request.getHeader("authorization");
if (authorization == null || !authorization.startsWith("Bearer")) {
log.error("Invalid authorization {}", authorization);
LTI13Util.return400(response, "invalid_authorization");
return null;
}
// https://stackoverflow.com/questions/7899525/how-to-split-a-string-by-space/7899558
String[] parts = authorization.split("\\s+");
if (parts.length != 2 || parts[1].length() < 1) {
log.error("Bad authorization {}", authorization);
LTI13Util.return400(response, "invalid_authorization");
return null;
}
String jws = parts[1];
Claims claims;
try {
claims = Jwts.parser().setSigningKey(publicKey).parseClaimsJws(jws).getBody();
} catch (ExpiredJwtException | MalformedJwtException | UnsupportedJwtException
| io.jsonwebtoken.security.SignatureException | IllegalArgumentException e) {
log.error("Signature error {}\n{}", e.getMessage(), jws);
LTI13Util.return400(response, "signature_error");
return null;
}
// Reconstruct the SakaiAccessToken
// https://www.baeldung.com/jackson-deserialization
SakaiAccessToken sat;
try {
ObjectMapper mapper = new ObjectMapper();
String jsonResult = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(claims);
// System.out.println("jsonResult=" + jsonResult);
sat = new ObjectMapper().readValue(jsonResult, SakaiAccessToken.class);
} catch (IOException ex) {
log.error("PARSE ERROR {}\n{}", ex.getMessage(), claims.toString());
LTI13Util.return400(response, "token_parse_failure", ex.getMessage());
return null;
}
// Validity check the access token
if (sat.tool_id != null && sat.scope != null && sat.expires != null) {
// All good
} else {
log.error("SakaiAccessToken missing required data {}", sat);
LTI13Util.return400(response, "Missing required data in access_token");
return null;
}
return sat;
}
@Override
public <T> T parse(String jwt, JwtHandler<T> handler) throws ExpiredJwtException, UnsupportedJwtException, MalformedJwtException, SignatureException, IllegalArgumentException {
return this.jwtParser.parse(jwt, handler);
}
@Override
public Jwt<Header, String> parsePlaintextJwt(String plaintextJwt) throws UnsupportedJwtException, MalformedJwtException, SignatureException, IllegalArgumentException {
return this.jwtParser.parsePlaintextJwt(plaintextJwt);
}
@Override
public Jwt<Header, Claims> parseClaimsJwt(String claimsJwt) throws ExpiredJwtException, UnsupportedJwtException, MalformedJwtException, SignatureException, IllegalArgumentException {
return this.jwtParser.parseClaimsJwt(claimsJwt);
}
@Override
public Jws<String> parsePlaintextJws(String plaintextJws) throws UnsupportedJwtException, MalformedJwtException, SignatureException, IllegalArgumentException {
return this.jwtParser.parsePlaintextJws(plaintextJws);
}
@Override
public Jws<Claims> parseClaimsJws(String claimsJws) throws ExpiredJwtException, UnsupportedJwtException, MalformedJwtException, SignatureException, IllegalArgumentException {
return this.jwtParser.parseClaimsJws(claimsJws);
}