com.nimbusds.jwt.JWT类的使用及代码示例

x33g5p2x  于2022-01-22 转载在 其他  
字(10.3k)|赞(0)|评价(0)|浏览(320)

本文整理了Java中com.nimbusds.jwt.JWT类的一些代码示例,展示了JWT类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。JWT类的具体详情如下:
包路径:com.nimbusds.jwt.JWT
类名称:JWT

JWT介绍

[英]JSON Web Token (JWT) interface.
[中]JSON Web令牌(JWT)接口。

代码示例

代码示例来源:origin: mitreid-connect/OpenID-Connect-Java-Spring-Server

/**
 * Create an unauthenticated token with the given subject and jwt
 * @param subject
 * @param jwt
 */
public JWTBearerAssertionAuthenticationToken(JWT jwt) {
  super(null);
  try {
    // save the subject of the JWT in case the credentials get erased later
    this.subject = jwt.getJWTClaimsSet().getSubject();
  } catch (ParseException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
  }
  this.jwt = jwt;
  setAuthenticated(false);
}

代码示例来源:origin: mitreid-connect/OpenID-Connect-Java-Spring-Server

@Override
public String convertToDatabaseColumn(JWT attribute) {
  if (attribute != null) {
    return attribute.serialize();
  } else {
    return null;
  }
}

代码示例来源:origin: spring-projects/spring-security

private Jwt createJwt(JWT parsedJwt, JWTClaimsSet jwtClaimsSet) {
  Map<String, Object> headers = new LinkedHashMap<>(parsedJwt.getHeader().toJSONObject());
  Map<String, Object> claims = this.claimSetConverter.convert(jwtClaimsSet.getClaims());
  Instant expiresAt = (Instant) claims.get(JwtClaimNames.EXP);
  Instant issuedAt = (Instant) claims.get(JwtClaimNames.IAT);
  return new Jwt(parsedJwt.getParsedString(), issuedAt, expiresAt, headers, claims);
}

代码示例来源:origin: mitreid-connect/OpenID-Connect-Java-Spring-Server

JWTClaimsSet idClaims = idToken.getJWTClaimsSet();
Algorithm tokenAlg = idToken.getHeader().getAlgorithm();
if (idClaims.getIssuer() == null) {
  throw new AuthenticationServiceException("Id Token Issuer is null");
} else if (!idClaims.getIssuer().equals(serverConfig.getIssuer())){
  throw new AuthenticationServiceException("Issuers do not match, expected " + serverConfig.getIssuer() + " got " + idClaims.getIssuer());

代码示例来源:origin: mitreid-connect/OpenID-Connect-Java-Spring-Server

JWTClaimsSet jwtClaims = jwt.getJWTClaimsSet();
if (jwtClaims.getIssuer() == null) {
  throw new AuthenticationServiceException("Assertion Token Issuer is null");
} else if (!jwtClaims.getIssuer().equals(client.getClientId())){
  throw new AuthenticationServiceException("Issuers do not match, expected " + client.getClientId() + " got " + jwtClaims.getIssuer());

代码示例来源:origin: io.gravitee.am.gateway.handlers/gravitee-am-gateway-handler

JWT jwt = JWTParser.parse(assertion);
String iss = jwt.getJWTClaimsSet().getIssuer();
String sub = jwt.getJWTClaimsSet().getSubject();
List<String> aud = jwt.getJWTClaimsSet().getAudience();
Date exp = jwt.getJWTClaimsSet().getExpirationTime();

代码示例来源:origin: mitreid-connect/OpenID-Connect-Java-Spring-Server

JWTClaimsSet claimSet = newClient.getSoftwareStatement().getJWTClaimsSet();
for (String claim : claimSet.getClaims().keySet()) {
  switch (claim) {
    case SOFTWARE_STATEMENT:
      throw new ValidationException("invalid_client_metadata", "Software statement can't include another software statement", HttpStatus.BAD_REQUEST);
    case CLAIMS_REDIRECT_URIS:
      newClient.setClaimsRedirectUris(Sets.newHashSet(claimSet.getStringListClaim(claim)));
      break;
    case CLIENT_SECRET_EXPIRES_AT:
      throw new ValidationException("invalid_client_metadata", "Software statement can't include a client registration access token", HttpStatus.BAD_REQUEST);
    case REQUEST_URIS:
      newClient.setRequestUris(Sets.newHashSet(claimSet.getStringListClaim(claim)));
      break;
    case POST_LOGOUT_REDIRECT_URIS:

代码示例来源:origin: org.wso2.carbon.apimgt/org.wso2.carbon.apimgt.hostobjects.oidc

String clientId = authClient.getClientId();
String clientAlgorithm = authClient.getClientAlgorithm();
Algorithm tokenAlg = idToken.getHeader().getAlgorithm();
if (idClaims.getIssuer() == null) {
  isValid = false;
  log.error("Id Token Issuer is null");
} else if (!idClaims.getIssuer().equals(serverConfiguration.getIssuer())) {
  isValid = false;
  log.error("Issuers do not match, expected " + serverConfiguration.getIssuer() +
      " got " + idClaims.getIssuer());

代码示例来源:origin: org.springframework.security/spring-security-oauth2-jose

private Jwt createJwt(JWT parsedJwt, JWTClaimsSet jwtClaimsSet) {
  Instant expiresAt = null;
  if (jwtClaimsSet.getExpirationTime() != null) {
    expiresAt = jwtClaimsSet.getExpirationTime().toInstant();
  }
  Instant issuedAt = null;
  if (jwtClaimsSet.getIssueTime() != null) {
    issuedAt = jwtClaimsSet.getIssueTime().toInstant();
  } else if (expiresAt != null) {
    // Default to expiresAt - 1 second
    issuedAt = Instant.from(expiresAt).minusSeconds(1);
  }
  Map<String, Object> headers = new LinkedHashMap<>(parsedJwt.getHeader().toJSONObject());
  return new Jwt(parsedJwt.getParsedString(), issuedAt, expiresAt, headers, jwtClaimsSet.getClaims());
}

代码示例来源:origin: org.apache.kerby/token-provider

private boolean verifyExpiration(JWT jwtToken) throws IOException {
  try {
    Date expire = jwtToken.getJWTClaimsSet().getExpirationTime();
    if (expire != null && new Date().after(expire)) {
      return false;
    }
    Date notBefore = jwtToken.getJWTClaimsSet().getNotBeforeTime();
    if (notBefore != null && new Date().before(notBefore)) {
      return false;
    }
  } catch (ParseException e) {
    throw new IOException("Failed to get JWT claims set", e);
  }
  return true;
}

代码示例来源:origin: org.pac4j/pac4j-jwt

@SuppressWarnings("unchecked")
protected void createJwtProfile(final TokenCredentials credentials, final JWT jwt) throws ParseException {
  final JWTClaimsSet claimSet = jwt.getJWTClaimsSet();
  final String subject = claimSet.getSubject();
  if (subject == null) {
    throw new TechnicalException("JWT must contain a subject ('sub' claim)");
  final Date expTime = claimSet.getExpirationTime();
  if (expTime != null) {
    final Date now = new Date();
  final Map<String, Object> attributes = new HashMap<>(claimSet.getClaims());
  attributes.remove(JwtClaims.SUBJECT);

代码示例来源:origin: mitreid-connect/OpenID-Connect-Java-Spring-Server

@Override
public Collection<? extends GrantedAuthority> mapAuthorities(JWT idToken, UserInfo userInfo) {
  Set<GrantedAuthority> out = new HashSet<>();
  try {
    JWTClaimsSet claims = idToken.getJWTClaimsSet();
    SubjectIssuerGrantedAuthority authority = new SubjectIssuerGrantedAuthority(claims.getSubject(), claims.getIssuer());
    out.add(authority);
    if (admins.contains(authority)) {
      out.add(ROLE_ADMIN);
    }
    // everybody's a user by default
    out.add(ROLE_USER);
  } catch (ParseException e) {
    logger.error("Unable to parse ID Token inside of authorities mapper (huh?)");
  }
  return out;
}

代码示例来源:origin: mitreid-connect/OpenID-Connect-Java-Spring-Server

idTokenClaims = idToken.getJWTClaimsSet();
  String clientId = Iterables.getOnlyElement(idTokenClaims.getAudience());
String subject = idTokenClaims.getSubject();

代码示例来源:origin: mitreid-connect/OpenID-Connect-Java-Spring-Server

private String getIssuer(String accessToken) {
  try {
    JWT jwt = JWTParser.parse(accessToken);
    String issuer = jwt.getJWTClaimsSet().getIssuer();
    return issuer;
  } catch (ParseException e) {
    throw new IllegalArgumentException("Unable to parse JWT", e);
  }
}

代码示例来源:origin: mitreid-connect/OpenID-Connect-Java-Spring-Server

@Override
public OAuth2Request createOAuth2Request(ClientDetails client, TokenRequest tokenRequest, JWT assertion) {
  try {
    JWTClaimsSet claims = assertion.getJWTClaimsSet();
    Set<String> scope = OAuth2Utils.parseParameterList(claims.getStringClaim("scope"));
    Set<String> resources = Sets.newHashSet(claims.getAudience());
    return new OAuth2Request(tokenRequest.getRequestParameters(), client.getClientId(), client.getAuthorities(), true, scope, resources, null, null, null);
  } catch (ParseException e) {
    return null;
  }
}

代码示例来源:origin: mitreid-connect/OpenID-Connect-Java-Spring-Server

private OAuth2AccessTokenEntity fetchValidRegistrationToken(OAuth2Authentication auth, ClientDetailsEntity client) {
  OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails) auth.getDetails();
  OAuth2AccessTokenEntity token = tokenService.readAccessToken(details.getTokenValue());
  if (config.getRegTokenLifeTime() != null) {
    try {
      // Re-issue the token if it has been issued before [currentTime - validity]
      Date validToDate = new Date(System.currentTimeMillis() - config.getRegTokenLifeTime() * 1000);
      if(token.getJwt().getJWTClaimsSet().getIssueTime().before(validToDate)) {
        logger.info("Rotating the registration access token for " + client.getClientId());
        tokenService.revokeAccessToken(token);
        OAuth2AccessTokenEntity newToken = connectTokenService.createResourceAccessToken(client);
        tokenService.saveAccessToken(newToken);
        return newToken;
      } else {
        // it's not expired, keep going
        return token;
      }
    } catch (ParseException e) {
      logger.error("Couldn't parse a known-valid token?", e);
      return token;
    }
  } else {
    // tokens don't expire, just return it
    return token;
  }
}

代码示例来源:origin: apache/nifi

claimsSet = successResponse.getUserInfo().toJWTClaimsSet();
} else {
  claimsSet = successResponse.getUserInfoJWT().getJWTClaimsSet();
final String email = claimsSet.getStringClaim(EMAIL_CLAIM_NAME);

代码示例来源:origin: org.wso2.carbon.identity/org.wso2.carbon.identity.oauth

JWTClaimsSet claimsSet = new JWTClaimsSet();
claimsSet.setIssuer(API_GATEWAY_ID);
claimsSet.setSubject(authzUser);
claimsSet.setIssueTime(new Date(issuedTime));
claimsSet.setExpirationTime(new Date(expireIn));
  log.debug("JWT Assertion Value : " + jwt.serialize());
token = messageContext.getResponseDTO().new AuthorizationContextToken("JWT", jwt.serialize());
messageContext.getResponseDTO().setAuthorizationContextToken(token);

代码示例来源:origin: org.wso2.carbon.apimgt/org.wso2.carbon.apimgt.hostobjects.oidc

private static boolean validateSignature(ServerConfiguration serverConfiguration, AuthClient authClient,
                 AuthenticationToken oidcAuthenticationToken, String nonce) throws Exception {
  boolean isSignatureValid;
  JWT idToken = JWTParser.parse(oidcAuthenticationToken.getIdTokenValue());
  JWTClaimsSet idClaims = idToken.getJWTClaimsSet();
  // Supports only signedJWT
  if (idToken instanceof SignedJWT) {
    SignedJWT signedIdToken = (SignedJWT) idToken;
    isSignatureValid = Util.verifySignature(signedIdToken, serverConfiguration);
  } else if (idToken instanceof PlainJWT) {
    log.error("Plain JWT not supported");
    throw new Exception("Plain JWT not supported");
  } else {
    log.error("JWT type not supported");
    throw new Exception("JWT type not supported");
  }
  boolean isValidClaimSet = Util.validateIdClaims(serverConfiguration, authClient, idToken, nonce, idClaims);
  return  isSignatureValid && isValidClaimSet;
}

代码示例来源:origin: org.pac4j/pac4j-oidc

@Override
  public boolean isExpired() {
    if (getTokenExpirationAdvance() < 0)
      return false;
    else {
      try {
        JWT jwt = this.getIdToken();
        JWTClaimsSet claims = jwt.getJWTClaimsSet();
        Date expiresOn = claims.getExpirationTime();

        Calendar now = Calendar.getInstance();
        now.add( Calendar.SECOND, getTokenExpirationAdvance() );

        return expiresOn.before(now.getTime());
      } catch (ParseException e) {
        throw new TechnicalException(e);
      }
    }
  }
}

相关文章