io.jsonwebtoken.Jws#getBody ( )源码实例Demo

下面列出了io.jsonwebtoken.Jws#getBody ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: IOT-Technical-Guide   文件: JwtTokenFactory.java
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;
}
 
源代码2 项目: Groza   文件: JwtTokenFactory.java
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;
}
 
源代码3 项目: iotplatform   文件: JwtTokenFactory.java
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;
}
 
源代码4 项目: leyou   文件: JwtUtils.java
/**
 * 获取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))
    );
}
 
源代码5 项目: leyou   文件: JwtUtils.java
/**
 * 获取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))
    );
}
 
源代码6 项目: IOT-Technical-Guide   文件: JwtTokenFactory.java
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;
}
 
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);
    }
}
 
/**
 * 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());
}
 
/**
 * 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());
}
 
源代码10 项目: Groza   文件: JwtTokenFactory.java
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;
}
 
源代码11 项目: iotplatform   文件: JwtTokenFactory.java
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;
}
 
源代码12 项目: hono   文件: EventBusAuthenticationService.java
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());
}
 
@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);
  }
}
 
源代码14 项目: rh-che   文件: ForwardActivityFilter.java
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;
}
 
源代码15 项目: athenz   文件: DefaultOAuthJwtAccessToken.java
/**
 * 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();
}
 
源代码16 项目: apiman-plugins   文件: ConfigCheckingJwtHandler.java
@Override
public Map<String, Object> onClaimsJws(Jws<Claims> jws) {
    return jws.getBody();
}
 
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);

}
 
源代码18 项目: JwtPermission   文件: TokenUtil.java
/**
 * 解析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();
}
 
源代码19 项目: sanshanblog   文件: JWTHelper.java
/**
 * 获取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));
}
 
源代码20 项目: sanshanblog   文件: JWTHelper.java
/**
 * 获取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));
}
 
 方法所在类
 同类方法