Java Code Examples for io.jsonwebtoken.Jws#getBody()

The following examples show how to use io.jsonwebtoken.Jws#getBody() . 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: 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 2
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 3
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 4
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 5
Source File: JwtUtils.java    From leyou with Apache License 2.0 5 votes vote down vote up
/**
 * 获取token中的用户信息
 *
 * @param token     用户请求中的令牌
 * @param publicKey 公钥
 * @return 用户信息
 * @throws Exception
 */
public static UserInfo getInfoFromToken(String token, PublicKey publicKey) throws Exception {
    Jws<Claims> claimsJws = parserToken(token, publicKey);
    Claims body = claimsJws.getBody();
    return new UserInfo(
            ObjectUtils.toLong(body.get(JwtConstans.JWT_KEY_ID)),
            ObjectUtils.toString(body.get(JwtConstans.JWT_KEY_USER_NAME))
    );
}
 
Example 6
Source File: EventBusAuthenticationService.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
private HonoUserImpl(final Jws<Claims> expandedToken, final String token) {
    Objects.requireNonNull(expandedToken);
    Objects.requireNonNull(token);
    if (expandedToken.getBody() == null) {
        throw new IllegalArgumentException("token has no claims");
    }
    this.token = token;
    this.expandedToken = expandedToken;
    this.authorities = AuthoritiesImpl.from(expandedToken.getBody());
}
 
Example 7
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 8
Source File: JwtTokenFactory.java    From Groza 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 9
Source File: JwtGeneratorTest.java    From cloud-iot-core-androidthings with Apache License 2.0 5 votes vote down vote up
/**
 * 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());
}
 
Example 10
Source File: JwtGeneratorTest.java    From cloud-iot-core-androidthings with Apache License 2.0 5 votes vote down vote up
/**
 * 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 testCreateJwtRsa() throws JoseException {
    JwtGenerator jwtGenerator =
            new JwtGenerator(RSA_KEY_PAIR, JWT_AUDIENCE, TOKEN_LIFETIME, TEST_CLOCK);
    String rawJwt = jwtGenerator.createJwt();

    // Validate JWT
    Jws<Claims> parsedJwt = Jwts.parser()
            .setSigningKey(RSA_KEY_PAIR.getPublic())
            .parseClaimsJws(rawJwt);

    JwsHeader header = parsedJwt.getHeader();
    Claims claims = parsedJwt.getBody();

    assertThat(header.getAlgorithm()).isEqualTo("RS256");
    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());
}
 
Example 11
Source File: JwtSsoBasedRefreshTokenFilter.java    From wecube-platform with Apache License 2.0 5 votes vote down vote up
protected Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response,
        Jws<Claims> jwt) {

    Claims claims = jwt.getBody();
    validateTokenType(claims);

    String clientType = claims.get(ApplicationConstants.JwtInfo.CLAIM_KEY_CLIENT_TYPE, String.class);
    if (StringUtils.isNotBlank(clientType) && ApplicationConstants.ClientType.SUB_SYSTEM.equals(clientType)) {
        return attemptSubSystemAuthentication(request, response, claims);
    } else {
        return attemptUserAuthentication(request, response, claims);
    }
}
 
Example 12
Source File: JwtTokenFactory.java    From IOT-Technical-Guide 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();
    securityUser.setEmail(subject);
    securityUser.setAuthority(Authority.parse(scopes.get(0)));
    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(1l);
    }
    String customerId = claims.get(CUSTOMER_ID, String.class);
    if (customerId != null) {
        securityUser.setCustomerId(1L);
    }

    return securityUser;
}
 
Example 13
Source File: JwtUtils.java    From leyou with Apache License 2.0 5 votes vote down vote up
/**
 * 获取token中的用户信息
 *
 * @param token     用户请求中的令牌
 * @param publicKey 公钥
 * @return 用户信息
 * @throws Exception
 */
public static UserInfo getInfoFromToken(String token, byte[] publicKey) throws Exception {
    Jws<Claims> claimsJws = parserToken(token, publicKey);
    Claims body = claimsJws.getBody();
    return new UserInfo(
            ObjectUtils.toLong(body.get(JwtConstans.JWT_KEY_ID)),
            ObjectUtils.toString(body.get(JwtConstans.JWT_KEY_USER_NAME))
    );
}
 
Example 14
Source File: ForwardActivityFilter.java    From rh-che with Eclipse Public License 2.0 4 votes vote down vote up
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;
}
 
Example 15
Source File: DefaultOAuthJwtAccessToken.java    From athenz with Apache License 2.0 4 votes vote down vote up
/**
 * Create DefaultOAuthJwtAccessToken access token object
 * @param  jws JWS claims
 */
public DefaultOAuthJwtAccessToken(Jws<Claims> jws) {
    // this.header = jws.getHeader();
    this.body = jws.getBody();
    this.signature = jws.getSignature();
}
 
Example 16
Source File: ConfigCheckingJwtHandler.java    From apiman-plugins with Apache License 2.0 4 votes vote down vote up
@Override
public Map<String, Object> onClaimsJws(Jws<Claims> jws) {
    return jws.getBody();
}
 
Example 17
Source File: TokenUtil.java    From JwtPermission with Apache License 2.0 2 votes vote down vote up
/**
 * 解析token
 *
 * @param token  token
 * @param hexKey 16进制密钥
 * @return Claims
 */
public static Claims parseToken(String token, String hexKey) {
    Jws<Claims> claimsJws = Jwts.parser().setSigningKey(parseHexKey(hexKey)).parseClaimsJws(token);
    return claimsJws.getBody();
}
 
Example 18
Source File: JWTHelper.java    From sanshanblog with Apache License 2.0 2 votes vote down vote up
/**
 * 获取token中的用户信息
 *
 * @param token
 * @param pubKeyPath
 * @return
 * @throws Exception
 */
public static IJWTInfo getInfoFromToken(String token, String pubKeyPath) throws Exception {
    Jws<Claims> claimsJws = parserToken(token, pubKeyPath);
    Claims body = claimsJws.getBody();
    return new JWTInfo(body.getSubject(), StringHelper.getObjectValue(body.get(UserInfoConstance.JWT_KEY_USER_ID)),body.get(UserInfoConstance.JWT_KEY_CREATED,Date.class));
}
 
Example 19
Source File: JWTHelper.java    From sanshanblog with Apache License 2.0 2 votes vote down vote up
/**
 * 获取token中的用户信息
 *
 * @param token
 * @param pubKey
 * @return
 * @throws Exception
 */
public static IJWTInfo getInfoFromToken(String token, byte[] pubKey) throws Exception {
    Jws<Claims> claimsJws = parserToken(token, pubKey);
    Claims body = claimsJws.getBody();
    return new JWTInfo(body.getSubject(), StringHelper.getObjectValue(body.get(UserInfoConstance.JWT_KEY_USER_ID)),body.get(UserInfoConstance.JWT_KEY_CREATED,Date.class));
}
 
Example 20
Source File: JwtSsoBasedAuthenticationFilter.java    From wecube-platform with Apache License 2.0 2 votes vote down vote up
protected UsernamePasswordAuthenticationToken getAuthentication(HttpServletRequest request) {
    validateRequestHeader(request);

    String sAccessTokenHeader = request.getHeader(HEADER_AUTHORIZATION);

    String sAccessToken = sAccessTokenHeader.substring(PREFIX_BEARER_TOKEN.length()).trim();

    if (StringUtils.isBlank(sAccessToken)) {
        throw new AuthenticationCredentialsNotFoundException("Access token is blank");
    }

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

    Claims claims = jwt.getBody();

    String sAuthorities = claims.get(CLAIM_KEY_AUTHORITIES, String.class);

    String username = claims.getSubject();

    String tokenType = claims.get(CLAIM_KEY_TYPE, String.class);

    if (!TOKEN_TYPE_ACCESS.equals(tokenType)) {
        throw new AccessDeniedException("Access token is required.");
    }
    
    log.debug("Subject:{};Authorities:{}", username, sAuthorities);

    if (sAuthorities.length() >= 2) {
        sAuthorities = sAuthorities.substring(1);
        sAuthorities = sAuthorities.substring(0, sAuthorities.length() - 1);
    }

    ArrayList<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();

    if (StringUtils.isNotBlank(sAuthorities)) {
        String[] aAuthParts = sAuthorities.split(",");
        for (String s : aAuthParts) {
            GrantedAuthority ga = new SimpleGrantedAuthority(s.trim());
            authorities.add(ga);
        }
    }

    return new UsernamePasswordAuthenticationToken(username, sAccessTokenHeader, authorities);

}