io.jsonwebtoken.Jws Java Examples

The following examples show how to use io.jsonwebtoken.Jws. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: JwtService.java    From nifi-registry with Apache License 2.0 6 votes vote down vote up
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 IdentityProvider?
        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;
    }
}
 
Example #2
Source File: JwtService.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
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;
    }
}
 
Example #3
Source File: TestJwtRsa.java    From kisso with Apache License 2.0 6 votes vote down vote up
@Test
public void testRsa() throws Exception {
    SSOConfig ssoConfig = SSOConfig.getInstance();
    Key key = RsaKeyHelper.getRsaKey(new ClassPathResource(ssoConfig.getRsaJksStore()).getInputStream(),
            ssoConfig.getRsaAlias(), ssoConfig.getRsaKeypass(), ssoConfig.getRsaStorepass());
    Map<String, Object> claims = new HashMap<>();
    claims.put("user", "cope");
    Calendar expires = Calendar.getInstance();
    expires.add(Calendar.HOUR, 2);

    // 加密
    String token = Jwts.builder()
            .setClaims(claims)
            .setSubject("test rsa jwt")
            .setIssuedAt(new Date())
            .setExpiration(expires.getTime())
            .signWith(key, SignatureAlgorithm.RS512)
            .compact();
    System.out.println(token);

    // CRT 证书中读取公钥解密
    PublicKey publicKey = RsaKeyHelper.getRsaPublicKey(new ClassPathResource(ssoConfig.getRsaCertStore()).getInputStream());
    Jws<Claims> crtClaimsJws = Jwts.parserBuilder().require("user", "cope")
            .setSigningKey(publicKey).build().parseClaimsJws(token);
    System.out.println("crt subject: " + crtClaimsJws.getBody().getSubject());
}
 
Example #4
Source File: JwtTokenFactory.java    From Groza with Apache License 2.0 6 votes vote down vote up
public SecurityUser parseRefreshToken(RawAccessJwtToken rawAccessToken) {
    Jws<Claims> jwsClaims = rawAccessToken.parseClaims(settings.getTokenSigningKey());
    Claims claims = jwsClaims.getBody();
    String subject = claims.getSubject();
    List<String> scopes = claims.get(SCOPES, List.class);
    if (scopes == null || scopes.isEmpty()) {
        throw new IllegalArgumentException("Refresh Token doesn't have any scopes");
    }
    if (!scopes.get(0).equals(Authority.REFRESH_TOKEN.name())) {
        throw new IllegalArgumentException("Invalid Refresh Token scope");
    }
    boolean isPublic = claims.get(IS_PUBLIC, Boolean.class);
    UserPrincipal principal = new UserPrincipal(isPublic ? UserPrincipal.Type.PUBLIC_ID : UserPrincipal.Type.USER_NAME, subject);
    SecurityUser securityUser = new SecurityUser(new UserId(UUID.fromString(claims.get(USER_ID, String.class))));
    securityUser.setUserPrincipal(principal);
    return securityUser;
}
 
Example #5
Source File: JwtAuthenticationProvider.java    From OpenLRW with Educational Community License v2.0 6 votes vote down vote up
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    RawAccessJwtToken rawAccessToken = (RawAccessJwtToken) authentication.getCredentials();

    Jws<Claims> jwsClaims = rawAccessToken.parseClaims(jwtSettings.getTokenSigningKey());
    String orgId = jwsClaims.getBody().getSubject();
    String tenantId = jwsClaims.getBody().get("tenant", String.class);
    List<String> scopes = jwsClaims.getBody().get("scopes", List.class);
    List<GrantedAuthority> authorities = scopes.stream()
            .map(authority -> new SimpleGrantedAuthority(authority))
            .collect(Collectors.toList());
    
    UserContext context = UserContext.create(tenantId, orgId, authorities);
    
    return new JwtAuthenticationToken(context, context.getAuthorities());
}
 
Example #6
Source File: JwtService.java    From nifi with Apache License 2.0 6 votes vote down vote up
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);
    }
}
 
Example #7
Source File: JwtService.java    From nifi-registry with Apache License 2.0 6 votes vote down vote up
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);
    }
}
 
Example #8
Source File: SmsVerificationJwtVerifier.java    From daming with Apache License 2.0 6 votes vote down vote up
/**
 * @param jwt, JWT issued by daming.
 * @return claims that contains verified mobile and scope.
 * @see #verify(String, String)
 */
@Deprecated
public SmsVerificationClaims verify(String jwt) {
    if (jwt == null) {
        throw new BadSmsVerificationJwtException("The jwt must not be null");
    }
    try {
        JwtParser parser = Jwts.parser()
                .setSigningKey(publicKey);
        if (clock != null) {
            parser = parser.setClock(clock);
        }
        Jws<Claims> claims = parser
                .parseClaimsJws(jwt);
        String mobile = claims.getBody().get("mobile", String.class);
        String scope = claims.getBody().get("scope", String.class);
        return new SmsVerificationClaims(mobile, scope);
    } catch (Exception err) {
        throw new BadSmsVerificationJwtException(err.getMessage(), err);
    }
}
 
Example #9
Source File: JwtTokenFactory.java    From IOT-Technical-Guide with Apache License 2.0 6 votes vote down vote up
public SecurityUser parseRefreshToken(RawAccessJwtToken rawAccessToken) {
    Jws<Claims> jwsClaims = rawAccessToken.parseClaims(settings.getTokenSigningKey());
    Claims claims = jwsClaims.getBody();
    String subject = claims.getSubject();
    List<String> scopes = claims.get(SCOPES, List.class);
    if (scopes == null || scopes.isEmpty()) {
        throw new IllegalArgumentException("Refresh Token doesn't have any scopes");
    }
    if (!scopes.get(0).equals(Authority.REFRESH_TOKEN.name())) {
        throw new IllegalArgumentException("Invalid Refresh Token scope");
    }
    boolean isPublic = claims.get(IS_PUBLIC, Boolean.class);
    UserPrincipal principal = new UserPrincipal(isPublic ? UserPrincipal.Type.PUBLIC_ID : UserPrincipal.Type.USER_NAME, subject);
    SecurityUser securityUser = new SecurityUser();
    securityUser.setUserPrincipal(principal);
    return securityUser;
}
 
Example #10
Source File: JwtTokenFactory.java    From iotplatform with Apache License 2.0 6 votes vote down vote up
public SecurityUser parseRefreshToken(RawAccessJwtToken rawAccessToken) {
  Jws<Claims> jwsClaims = rawAccessToken.parseClaims(settings.getTokenSigningKey());
  Claims claims = jwsClaims.getBody();
  String subject = claims.getSubject();
  List<String> scopes = claims.get(SCOPES, List.class);
  if (scopes == null || scopes.isEmpty()) {
    throw new IllegalArgumentException("Refresh Token doesn't have any scopes");
  }
  if (!scopes.get(0).equals(Authority.REFRESH_TOKEN.name())) {
    throw new IllegalArgumentException("Invalid Refresh Token scope");
  }
  boolean isPublic = claims.get(IS_PUBLIC, Boolean.class);
  UserPrincipal principal = new UserPrincipal(isPublic ? UserPrincipal.Type.PUBLIC_ID : UserPrincipal.Type.USER_NAME,
      subject);
  SecurityUser securityUser = new SecurityUser(new UserId(UUID.fromString(claims.get(USER_ID, String.class))));
  securityUser.setUserPrincipal(principal);
  return securityUser;
}
 
Example #11
Source File: ElexisEnvironmentLoginDialog.java    From elexis-3-core with Eclipse Public License 1.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
private Set<String> parseRoles(Jws<Claims> jwsClaim){
	Set<String> roles = new HashSet<String>();
	Map<String, Object> realmAccess =
		(Map<String, Object>) jwsClaim.getBody().get("realm_access");
	if (realmAccess != null) {
		List<String> realmAccessRoles = (List<String>) realmAccess.get("roles");
		if (realmAccessRoles != null) {
			roles.addAll(realmAccessRoles);
		}
	}
	Map<String, Object> resourceAccess =
		(Map<String, Object>) jwsClaim.getBody().get("resource_access");
	if (resourceAccess != null) {
		Map<String, Object> elexisRcpOpenidAccess =
			(Map<String, Object>) resourceAccess.get("elexis-rcp-openid");
		if (elexisRcpOpenidAccess != null) {
			List<String> elexisRcpOpenidAccessRoles =
				(List<String>) elexisRcpOpenidAccess.get("roles");
			if (elexisRcpOpenidAccessRoles != null) {
				roles.addAll(elexisRcpOpenidAccessRoles);
			}
		}
	}
	return roles;
}
 
Example #12
Source File: JwtService.java    From nifi with Apache License 2.0 5 votes vote down vote up
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";

        // A common attack is someone trying to use a token after the user is logged out
        // No need to show a stacktrace for an expected and handled scenario
        String causeMessage = e.getLocalizedMessage();
        if (e.getCause() != null) {
            causeMessage += "\n\tCaused by: " + e.getCause().getLocalizedMessage();
        }
        if (logger.isDebugEnabled()) {
            logger.error(errorMessage, e);
        } else {
            logger.error(errorMessage);
            logger.error(causeMessage);
        }
        throw e;
    }
}
 
Example #13
Source File: StaticJWTController.java    From tutorials with MIT License 5 votes vote down vote up
@RequestMapping(value = "/parser", method = GET)
public JwtResponse parser(@RequestParam String jwt) throws UnsupportedEncodingException {

    Jws<Claims> jws = Jwts.parser()
        .setSigningKeyResolver(secretService.getSigningKeyResolver())
        .parseClaimsJws(jwt);

    return new JwtResponse(jws);
}
 
Example #14
Source File: JwtSsoBasedRefreshTokenFilter.java    From wecube-platform with Apache License 2.0 5 votes vote down vote up
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
        throws AuthenticationException, IOException, ServletException {
    log.info("=== refresh token ===");

    validateRequestHeader(request);

    String sRefreshToken = request.getHeader(ApplicationConstants.JwtInfo.HEADER_AUTHORIZATION);
    sRefreshToken = sRefreshToken.substring(ApplicationConstants.JwtInfo.PREFIX_BEARER_TOKEN.length()).trim();

    if (log.isDebugEnabled()) {
        log.debug("refresh token:{}", sRefreshToken);
    }

    if (StringUtils.isBlank(sRefreshToken)) {
        throw new BadCredentialsException("refresh token is blank.");
    }

    Jws<Claims> jwt = jwtBuilder.parseJwt(sRefreshToken);

    if (jwt == null) {
        log.error("failed to parse refresh token:{}", sRefreshToken);
        throw new BadCredentialsException("bad refresh token.");
    }

    return attemptAuthentication(request, response, jwt);
}
 
Example #15
Source File: JsonWebTokenAuthenticationService.java    From spring-boot-mongodb-jwt with Apache License 2.0 5 votes vote down vote up
@Override
public Authentication authenticate(final HttpServletRequest request) {
    final String token = request.getHeader(SecurityConstants.AUTH_HEADER_NAME);
    final Jws<Claims> tokenData = parseToken(token);
    if (tokenData != null) {
        User user = getUserFromToken(tokenData);
        if (user != null) {
            return new UserAuthentication(user);
        }
    }
    return null;
}
 
Example #16
Source File: Auth0JwtParserTest.java    From athenz with Apache License 2.0 5 votes vote down vote up
@Test
@SuppressWarnings("rawtypes")
public void testParse() throws Exception {
    // mock internal parser
    Auth0JwtParser parser = new Auth0JwtParser(baseKeyStore, "https://athenz-oauth-example.auth0.com/.well-known/jwks.json");
    JwtParser jwtParserMock = Mockito.mock(JwtParser.class);
    Field f = parser.getClass().getSuperclass().getDeclaredField("parser");
    f.setAccessible(true);
    f.set(parser, jwtParserMock);

    // parse error
    Mockito.when(jwtParserMock.parseClaimsJws(null)).thenThrow(new NullPointerException());
    assertThrows(OAuthJwtAccessTokenException.class, () -> parser.parse(null));

    // parse success
    String jwtString = "dummy-jwt-string";
    Jws<Claims> jws = new Jws<Claims>() {
        public JwsHeader getHeader() { return null; }
        public Claims getBody() { return null; }

        @Override
        public String getSignature() {
            return "dummy-jwt-signature";
        }
    };
    Mockito.when(jwtParserMock.parseClaimsJws(jwtString)).thenReturn(jws);
    OAuthJwtAccessToken token = parser.parse(jwtString);
    assertNotNull(token);
    assertTrue(token instanceof Auth0Jwt);
    assertEquals(token.getSignature(), "dummy-jwt-signature");
}
 
Example #17
Source File: JsonWebTokenAuthenticationService.java    From spring-boot-mongodb-jwt with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example #18
Source File: KeycloakEnvironmentInitializationFilter.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public Subject extractSubject(String token) throws ServletException {

  Jws<Claims> jwt = jwtParser.parseClaimsJws(token);
  Claims claims = jwt.getBody();
  LOG.debug("JWT = {}", jwt);
  // OK, we can trust this JWT

  try {
    String username =
        claims.get(
            keycloakSettings.get().get(KeycloakConstants.USERNAME_CLAIM_SETTING), String.class);
    if (username == null) { // fallback to unique id promised by spec
      // https://openid.net/specs/openid-connect-basic-1_0.html#ClaimStability
      username = claims.getIssuer() + ":" + claims.getSubject();
    }
    String id = claims.getSubject();

    String email =
        retrieveEmail(token, claims, id)
            .orElseThrow(
                () ->
                    new JwtException(
                        "Unable to authenticate user because email address is not set in keycloak profile"));
    User user = userManager.getOrCreateUser(id, email, username);
    return new AuthorizedSubject(
        new SubjectImpl(user.getName(), user.getId(), token, false), permissionChecker);
  } catch (ServerException | ConflictException e) {
    throw new ServletException(
        "Unable to identify user " + claims.getSubject() + " in Che database", e);
  }
}
 
Example #19
Source File: JwtTokenProvider.java    From spring-webmvc-jwt-sample with GNU General Public License v3.0 5 votes vote down vote up
public boolean validateToken(String token) {
    try {
        Jws<Claims> claims = Jwts.parser().setSigningKey(secretKey).parseClaimsJws(token);

        if (claims.getBody().getExpiration().before(new Date())) {
            return false;
        }

        return true;
    } catch (JwtException | IllegalArgumentException e) {
        throw new InvalidJwtAuthenticationException("Expired or invalid JWT token");
    }
}
 
Example #20
Source File: DefaultJwtParser.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@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);
    }
}
 
Example #21
Source File: DefaultJwtParser.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public Jws<Claims> parseClaimsJws(String claimsJws) {
    return parse(claimsJws, new JwtHandlerAdapter<Jws<Claims>>() {
        @Override
        public Jws<Claims> onClaimsJws(Jws<Claims> jws) {
            return jws;
        }
    });
}
 
Example #22
Source File: DefaultJwtParser.java    From jjwt with Apache License 2.0 5 votes vote down vote up
@Override
public Jws<Claims> parseClaimsJws(String claimsJws) {
    return parse(claimsJws, new JwtHandlerAdapter<Jws<Claims>>() {
        @Override
        public Jws<Claims> onClaimsJws(Jws<Claims> jws) {
            return jws;
        }
    });
}
 
Example #23
Source File: Device.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Creates a new device for a token.
 * <p>
 * The token is expected to contain the device identifier in the <em>sub</em> claim and
 * the tenant identifier in the <em>ten</em> claim.
 *
 * @param token The token asserting the device's identity.
 * @throws NullPointerException if the token does not contain a tenant and device identifier.
 */
public Device(final Jws<Claims> token) {
    this(Objects.requireNonNull(token).getBody().get("ten", String.class), token.getBody().getSubject());
    try {
        final Set<?> aut = token.getBody().get("aut", Set.class);
        if (aut != null) {
            authorities.addAll(aut);
        }
    } catch (final RequiredTypeException e) {
        // token contains no authorities claim
    }
}
 
Example #24
Source File: AuthTokenHelperImplTest.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Verifies that the helper can create a token for a given set of
 * authorities and can then parse the token again.
 */
@Test
public void testCreateAndExpandToken() {

    final Authorities authorities = new AuthoritiesImpl()
            .addResource("telemetry", "*", Activity.READ, Activity.WRITE)
            .addOperation("registration", "*", "assert");
    final String token = helper.createToken("userA", authorities);

    final Jws<Claims> parsedToken = helper.expand(token);
    assertNotNull(parsedToken.getBody());
}
 
Example #25
Source File: RefreshToken.java    From OpenLRW with Educational Community License v2.0 5 votes vote down vote up
/**
 * Creates and validates Refresh token 
 * 
 * @param token
 * @param signingKey
 * 
 * @throws BadCredentialsException
 * @throws JwtExpiredTokenException
 * 
 * @return
 */
public static Optional<RefreshToken> create(RawAccessJwtToken token, String signingKey) {
    Jws<Claims> claims = token.parseClaims(signingKey);

    List<String> scopes = claims.getBody().get("scopes", List.class);
    if (scopes == null || scopes.isEmpty() 
            || !scopes.stream().filter(scope -> Scopes.REFRESH_TOKEN.authority().equals(scope)).findFirst().isPresent()) {
        return Optional.empty();
    }

    return Optional.of(new RefreshToken(claims));
}
 
Example #26
Source File: RawAccessJwtToken.java    From iotplatform with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
  }
}
 
Example #27
Source File: JwtTokenFactory.java    From iotplatform with Apache License 2.0 5 votes vote down vote up
public SecurityUser parseAccessJwtToken(RawAccessJwtToken rawAccessToken) {
  Jws<Claims> jwsClaims = rawAccessToken.parseClaims(settings.getTokenSigningKey());
  Claims claims = jwsClaims.getBody();
  String subject = claims.getSubject();
  List<String> scopes = claims.get(SCOPES, List.class);
  if (scopes == null || scopes.isEmpty()) {
    throw new IllegalArgumentException("JWT Token doesn't have any scopes");
  }

  SecurityUser securityUser = new SecurityUser(new UserId(UUID.fromString(claims.get(USER_ID, String.class))));
  securityUser.setEmail(subject);
  securityUser.setAuthority(Authority.parse(scopes.get(0)));
  securityUser.setFirstName(claims.get(FIRST_NAME, String.class));
  securityUser.setLastName(claims.get(LAST_NAME, String.class));
  securityUser.setEnabled(claims.get(ENABLED, Boolean.class));
  boolean isPublic = claims.get(IS_PUBLIC, Boolean.class);
  UserPrincipal principal = new UserPrincipal(isPublic ? UserPrincipal.Type.PUBLIC_ID : UserPrincipal.Type.USER_NAME,
      subject);
  securityUser.setUserPrincipal(principal);
  String tenantId = claims.get(TENANT_ID, String.class);
  if (tenantId != null) {
    securityUser.setTenantId(new TenantId(UUID.fromString(tenantId)));
  }
  String customerId = claims.get(CUSTOMER_ID, String.class);
  if (customerId != null) {
    securityUser.setCustomerId(new CustomerId(UUID.fromString(customerId)));
  }

  return securityUser;
}
 
Example #28
Source File: RawAccessJwtToken.java    From springboot-security-jwt with MIT License 5 votes vote down vote up
/**
 * 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);
    }
}
 
Example #29
Source File: AuthTokenHelperImpl.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public Jws<Claims> expand(final String token) {

    Objects.requireNonNull(token);
    return Jwts.parser()
            .setSigningKey(key)
            .parseClaimsJws(token);
}
 
Example #30
Source File: StaticJWTController.java    From tutorials with MIT License 5 votes vote down vote up
@RequestMapping(value = "/parser-enforce", method = GET)
public JwtResponse parserEnforce(@RequestParam String jwt) throws UnsupportedEncodingException {
    Jws<Claims> jws = Jwts.parser()
        .requireIssuer("Stormpath")
        .require("hasMotorcycle", true)
        .setSigningKeyResolver(secretService.getSigningKeyResolver())
        .parseClaimsJws(jwt);

    return new JwtResponse(jws);
}