/** * 从token中获取JWT中的负载 */ private Claims getClaimsFromToken(String token) { Claims claims = null; try { claims = Jwts.parser() .setSigningKey(secret) .parseClaimsJws(token) .getBody(); } catch (Exception e) { LOGGER.info("JWT格式验证失败:{}",token); } return claims; }
private String getUserId(String token) { // if we have a signing key resolver use it to validate the token locally // otherwise hit the introspect endpoint if (signingKeyResolver != null) { Jws<Claims> claims = Jwts.parser() .setSigningKeyResolver(signingKeyResolver) .parseClaimsJws(token); return claims.getBody().get("uid", String.class); } return resolveAccessToken(token).getUid(); }
Optional<Claims> decode(String token) { checkIsStarted(); Claims claims = null; try { claims = Jwts.parser() .setSigningKey(secretKey) .parseClaimsJws(token) .getBody(); requireNonNull(claims.getId(), "Token id hasn't been found"); requireNonNull(claims.getSubject(), "Token subject hasn't been found"); requireNonNull(claims.getExpiration(), "Token expiration date hasn't been found"); requireNonNull(claims.getIssuedAt(), "Token creation date hasn't been found"); return Optional.of(claims); } catch (ExpiredJwtException | SignatureException e) { return Optional.empty(); } catch (Exception e) { throw AuthenticationException.newBuilder() .setSource(Source.jwt()) .setLogin(claims == null ? null : claims.getSubject()) .setMessage(e.getMessage()) .build(); } }
/** * 验签JWT * * @param jwt json web token */ public static JwtAccount parseJwt(String jwt, String appKey) throws ExpiredJwtException, UnsupportedJwtException, MalformedJwtException, SignatureException, IllegalArgumentException { Claims claims = Jwts.parser() .setSigningKey(DatatypeConverter.parseBase64Binary(appKey)) .parseClaimsJws(jwt) .getBody(); JwtAccount jwtAccount = new JwtAccount(); jwtAccount.setTokenId(claims.getId());// 令牌ID jwtAccount.setAppId(claims.getSubject());// 客户标识 jwtAccount.setIssuer(claims.getIssuer());// 签发者 jwtAccount.setIssuedAt(claims.getIssuedAt());// 签发时间 jwtAccount.setAudience(claims.getAudience());// 接收方 jwtAccount.setRoles(claims.get("roles", String.class));// 访问主张-角色 jwtAccount.setPerms(claims.get("perms", String.class));// 访问主张-权限 return jwtAccount; }
@Override public Account getAccountByJwt(final HttpServletRequest request, final HttpServletResponse response, String jwt) { final JwtSigningKeyResolver resolver = getJwtSigningKeyResolver(); SigningKeyResolver signingKeyResolver = new SigningKeyResolverAdapter() { @Override public Key resolveSigningKey(JwsHeader header, Claims claims) { return resolver.getSigningKey(request, response, header, claims); } }; Jws<Claims> jws = Jwts.parser().setSigningKeyResolver(signingKeyResolver).parseClaimsJws(jwt); Claims claims = jws.getBody(); if ("refresh".equals(jws.getHeader().get("stt"))) { //Fix for https://github.com/stormpath/stormpath-sdk-java/issues/674 //This is a refresh token, let's not allow the account to be obtained from it return null; } String accountHref = claims.getSubject(); //will hit the cache: Client client = getClient(request); return client.getResource(accountHref, Account.class); }
public static Claims parseJWT(String jwt) { //This line will throw an exception if it is not a signed JWS (as expected) JwsHeader claims1 = Jwts.parser() .setSigningKey(DatatypeConverter.parseBase64Binary(SIGN)) .parseClaimsJws(jwt).getHeader(); Claims claims = Jwts.parser() .setSigningKey(DatatypeConverter.parseBase64Binary(SIGN)) .parseClaimsJws(jwt).getBody(); // createJWT() System.out.println("ID: " + claims.getId()); System.out.println("Subject: " + claims.getSubject()); System.out.println("Issuer: " + claims.getIssuer()); System.out.println("Expiration: " + claims.getExpiration()); return claims; } }
private int getMaxAge(String token, byte[] clientSecret, CookieConfig cookieConfig, HttpServletRequest request, HttpServletResponse response) { // non-zero indicates override from cookie config if (cookieConfig.getMaxAge() != 0 ) { return cookieConfig.getMaxAge(); } if(Strings.hasText(token) && token.split("\\.").length == 3) { // otherwise, use the claims in the JWT to determine maxAge Jws<Claims> claimsJws = Jwts.parser().setSigningKeyResolver(createKeyResolver(request, response)).parseClaimsJws(token); DateTime issueAt = new DateTime(claimsJws.getBody().getIssuedAt()); DateTime expiration = new DateTime(claimsJws.getBody().getExpiration()); return Seconds.secondsBetween(issueAt, expiration).getSeconds() - Seconds.secondsBetween(issueAt, DateTime.now()).getSeconds(); } return DEFAULT_COOKIE_MAX_AGE; }
@Override public Principal authenticate(HttpServletRequest request) throws AuthenticationException { String header = nullToEmpty(request.getHeader(AUTHORIZATION)); int space = header.indexOf(' '); if ((space < 0) || !header.substring(0, space).equalsIgnoreCase("bearer")) { throw needAuthentication(null); } String token = header.substring(space + 1).trim(); if (token.isEmpty()) { throw needAuthentication(null); } try { Jws<Claims> claimsJws = jwtParser.parseClaimsJws(token); String subject = claimsJws.getBody().getSubject(); return new BasicPrincipal(subject); } catch (JwtException e) { throw needAuthentication(e.getMessage()); } catch (RuntimeException e) { throw new RuntimeException("Authentication error", e); } }
public String getSubject() { return claims.getBody().getSubject(); } }
@Override public Map<String, String> getDecodedTokenDetails(String token) throws Exception { Jws<Claims> jws = getClaims(token); Claims claims = jws.getBody(); Map<String, String> tokenDetails = new HashMap<>(); tokenDetails.put("username", (String)claims.get("user_name")); tokenDetails.put("email", (String)claims.get("email")); tokenDetails.put("expiry", claims.get("exp").toString()); tokenDetails.put("user_id", claims.get("user_id").toString()); return tokenDetails; }
/** * */ public static String getHeaderAsString(String jws, Key key) { return Jwts.parser().setSigningKey(key).parseClaimsJws(jws).getHeader().toString(); }
private Subject extractSubject(String token) throws NotFoundException, ServerException { final Claims claims = jwtParser.parseClaimsJws(token).getBody(); final String userId = claims.get(USER_ID_CLAIM, String.class); // check if user with such id exists final String userName = userManager.getById(userId).getName(); final String workspaceId = claims.get(WORKSPACE_ID_CLAIM, String.class); return new MachineTokenAuthorizedSubject( new SubjectImpl(userName, userId, token, false), permissionChecker, workspaceId); }
public String getAuthenticationFromToken(final String base64EncodedToken) throws JwtException { // The library representations of the JWT should be kept internal to this service. try { final Jws<Claims> jws = parseTokenFromBase64EncodedString(base64EncodedToken); if (jws == null) { throw new JwtException("Unable to parse token"); } // Additional validation that subject is present if (StringUtils.isEmpty(jws.getBody().getSubject())) { throw new JwtException("No subject available in token"); } // TODO: Validate issuer against active registry? if (StringUtils.isEmpty(jws.getBody().getIssuer())) { throw new JwtException("No issuer available in token"); } return jws.getBody().getSubject(); } catch (JwtException e) { logger.debug("The Base64 encoded JWT: " + base64EncodedToken); final String errorMessage = "There was an error validating the JWT"; logger.error(errorMessage, e); throw e; } }
@Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { RawAccessJwtToken rawAccessToken = (RawAccessJwtToken) authentication.getCredentials(); Jws<Claims> jwsClaims = rawAccessToken.parseClaims(jwtSettings.getTokenSigningKey()); String subject = jwsClaims.getBody().getSubject(); List<String> scopes = jwsClaims.getBody().get("scopes", List.class); List<GrantedAuthority> authorities = scopes.stream() .map(SimpleGrantedAuthority::new) .collect(Collectors.toList()); UserContext context = UserContext.create(subject, authorities); return new JwtAuthenticationToken(context, context.getAuthorities()); }
@Override public Instant getExpirationTime() { return expandedToken.getBody().getExpiration().toInstant(); } }
protected void verifyClaim(Jws<Claims> token, String expectedClaimName, Object expectedClaimValue) { JwsHeader<?> header = token.getHeader(); Claims claims = token.getBody(); Object actualClaimValue = claims.get(expectedClaimName); if (actualClaimValue == null) { String msg = String.format( ClaimJwtException.MISSING_EXPECTED_CLAIM_MESSAGE_TEMPLATE, expectedClaimName, expectedClaimValue ); throw new MissingClaimException(header, claims, msg); } else if (!expectedClaimValue.equals(actualClaimValue)) { String msg = String.format( ClaimJwtException.INCORRECT_EXPECTED_CLAIM_MESSAGE_TEMPLATE, expectedClaimName, expectedClaimValue, actualClaimValue ); throw new IncorrectClaimException(header, claims, msg); } }
@Override public Map<String, Object> getAllTokenDetails(String token, String keyUrl) throws Exception { Jws<Claims> claims = getClaimsForKeyUrl( token ); return JsonUtils.toJsonMap(claims.getBody()); }
@Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { if (!(authentication instanceof BearerAuthenticationToken)) { return null; } String bearerToken = (String) authentication.getCredentials(); User user; Jws<Claims> jws; try { jws = tokenAuthenticationService.parse(bearerToken); user = tokenAuthenticationService.verify(jws); } catch (ExpiredJwtException e) { throw new CredentialsExpiredException("JWT token expired", e); } catch (UnsupportedJwtException | MalformedJwtException | IllegalArgumentException e) { // assume that this is not a JWT, allow the next AuthenticationProvider to process it return null; } catch (SignatureException | MissingClaimException | IncorrectClaimException e) { throw new BadCredentialsException("JWT signature verification error or claim incorrect", e); } catch (NotFoundException e) { throw new BadCredentialsException("Invalid username", e); } catch (Exception e) { throw new InternalAuthenticationServiceException("Error authenticating with JWT token", e); } userDetailsChecker.check(user); if (log.isDebugEnabled()) { log.debug("Successfully authenticated user using JWT token, header: " + jws.getHeader() + ", body: " + jws.getBody()); } return new JwtAuthentication(user, bearerToken, jws, user.getAuthorities()); }
/** * This method will validate that the received jwt corresponds to an `access_token` (as opposed to a * `refresh_token`). If that is not the case then this operation will throw a JwtException. It is called * from the constructor, so an AccessToken cannot be instantiated without verifying the jwt is a proper * `access_token` * * @since 1.0.RC8.3 */ private void ensureAccessToken() { if(isMaterialized()) { try { JwsHeader header = AbstractBaseOAuthToken.parseJws(getString(JWT), getDataStore()).getHeader(); String tokenType = (String) header.get("stt"); Assert.isTrue(tokenType.equals("access")); } catch (Exception e) { throw new JwtException("JWT failed validation; it cannot be trusted."); } } else { String href = getStringProperty(HREF_PROP_NAME); if (href != null) { Assert.isTrue(href.contains("/accessTokens/"), "href does not belong to an access token."); } } }