當前位置: 首頁>>代碼示例>>Java>>正文


Java SignedJWT.getJWTClaimsSet方法代碼示例

本文整理匯總了Java中com.nimbusds.jwt.SignedJWT.getJWTClaimsSet方法的典型用法代碼示例。如果您正苦於以下問題:Java SignedJWT.getJWTClaimsSet方法的具體用法?Java SignedJWT.getJWTClaimsSet怎麽用?Java SignedJWT.getJWTClaimsSet使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在com.nimbusds.jwt.SignedJWT的用法示例。


在下文中一共展示了SignedJWT.getJWTClaimsSet方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: parseAndVerifyToken

import com.nimbusds.jwt.SignedJWT; //導入方法依賴的package包/類
public SignedJWT parseAndVerifyToken(String jwtString) throws WebApiClientException {
    try {
        SignedJWT signedJWT = SignedJWT.parse(jwtString);

        JWSVerifier verifier = new RSASSAVerifier(jwtConfig.getRSAPublicKey());
        if (signedJWT.verify(verifier)) {
            JWTClaimsSet claimsSet = signedJWT.getJWTClaimsSet();
            if (claimsSet.getAudience().contains(jwtConfig.getServiceUUID()) &&
                    claimsSet.getIssuer().equalsIgnoreCase(JwtUtil.ISSUER)) {
                return signedJWT;
            }
        }
    } catch (ParseException | JOSEException e) {
        throw new WebApiClientException(e.getMessage());
    }
    throw new WebApiClientException("Authorization token cannot be verified");
}
 
開發者ID:vrk-kpa,項目名稱:roles-auths-client,代碼行數:18,代碼來源:JwtUtil.java

示例2: verifyToken

import com.nimbusds.jwt.SignedJWT; //導入方法依賴的package包/類
@Override
public Optional<Authentication> verifyToken(Optional<String> token) {
  if (!token.isPresent()) {
    return Optional.empty();
  }

  SignedJWT signedJwt;
  JWTClaimsSet claimSet;
  try {
    signedJwt = SignedJWT.parse(token.get());
    claimSet = signedJwt.getJWTClaimsSet();

    if (!signedJwt.verify(verifier)) {
      throw new BadCredentialsException("Invalid token");
    }
  } catch (ParseException | JOSEException e) {
    throw new IllegalArgumentException("Error while parsing and verifying token.", e);
  }


  if (claimSet.getExpirationTime().getTime() < System.currentTimeMillis()) {
    throw new BadCredentialsException("Token is expired");
  }

  return Optional.of(transformer.getAuthentication(claimSet));
}
 
開發者ID:visola,項目名稱:spring-security-token-filter,代碼行數:27,代碼來源:JwtTokenService.java

示例3: itShouldGenerateAValidToken

import com.nimbusds.jwt.SignedJWT; //導入方法依賴的package包/類
@Test
public void itShouldGenerateAValidToken() throws ParseException, JOSEException {
  JWTClaimsSet claimsSet = new JWTClaimsSet.Builder()
      .subject(USER.getUsername())
      .issueTime(NOW)
      .expirationTime(EXPIRATION)
      .build();

  Mockito.when(mockTransformer.getClaimsSet(AUTHENTICATION)).thenReturn(claimsSet);
  Mockito.when(mockSigner.sign(Matchers.any(), Matchers.any())).thenReturn(Base64URL.encode("MYSIGNATURE"));

  // Method being tested
  String token = jwtTokenService.generateToken(AUTHENTICATION);

  SignedJWT signedJwt = SignedJWT.parse(token);
  JWTClaimsSet fetchedClaimsSet = signedJwt.getJWTClaimsSet();

  Assertions.assertThat(signedJwt.verify(verifier)).isTrue();
  System.out.println(signedJwt.serialize());
  Assertions.assertThat(fetchedClaimsSet.getSubject()).isEqualTo(USERNAME);
}
 
開發者ID:visola,項目名稱:spring-security-token-filter,代碼行數:22,代碼來源:JwtTokenServiceTest.java

示例4: interceptRequest

import com.nimbusds.jwt.SignedJWT; //導入方法依賴的package包/類
@Override
public boolean interceptRequest(Request request, Response response) throws Exception {
    HttpHeaders headers = request.getHeaders();
    if (headers != null) {
        String jwtHeader = headers.getHeaderString(JWT_HEADER);
        if (jwtHeader != null) {
            SignedJWT signedJWT = SignedJWT.parse(jwtHeader);
            ReadOnlyJWTClaimsSet readOnlyJWTClaimsSet = signedJWT.getJWTClaimsSet();
            if (readOnlyJWTClaimsSet != null) {
                // Do something with claims
                return true;
            }
        }
    }
    response.setHeader(javax.ws.rs.core.HttpHeaders.WWW_AUTHENTICATE, AUTH_TYPE_JWT);
    response.setStatus(javax.ws.rs.core.Response.Status.UNAUTHORIZED.getStatusCode());
    return false;
}
 
開發者ID:wso2,項目名稱:msf4j,代碼行數:19,代碼來源:CustomJWTClaimsInterceptor.java

示例5: validToken

import com.nimbusds.jwt.SignedJWT; //導入方法依賴的package包/類
@Test
public void validToken() throws JOSEException, ParseException {
    JWTClaimsSet jwtClaims = getJWTClaimsSet("issuer", "subject", new Date(), new Date(), new Date(new Date().getTime() + 100000));

    JWSHeader header = new JWSHeader(JWSAlgorithm.HS256);

    Payload payload = new Payload(jwtClaims.toJSONObject());

    JWSObject jwsObject = new JWSObject(header, payload);

    JWSSigner signer = new MACSigner(sharedKey);
    jwsObject.sign(signer);
    String token = jwsObject.serialize();

    SignedJWT signed = SignedJWT.parse(token);
    JWSVerifier verifier = new MACVerifierExtended(sharedKey, signed.getJWTClaimsSet());
    signed.verify(verifier);

    Assert.assertTrue("Must be valid", signed.verify(verifier));
}
 
開發者ID:panchitoboy,項目名稱:shiro-jwt,代碼行數:21,代碼來源:MACVerifierExtendedTest.java

示例6: invalidTokenNotBeforeTime

import com.nimbusds.jwt.SignedJWT; //導入方法依賴的package包/類
@Test
public void invalidTokenNotBeforeTime() throws JOSEException, ParseException {
    JWTClaimsSet jwtClaims = getJWTClaimsSet("issuer", "subject", new Date(), new Date(new Date().getTime() + 100000), new Date(new Date().getTime() + 200000));

    JWSHeader header = new JWSHeader(JWSAlgorithm.HS256);

    Payload payload = new Payload(jwtClaims.toJSONObject());

    JWSObject jwsObject = new JWSObject(header, payload);

    JWSSigner signer = new MACSigner(sharedKey);
    jwsObject.sign(signer);
    String token = jwsObject.serialize();

    SignedJWT signed = SignedJWT.parse(token);
    JWSVerifier verifier = new MACVerifierExtended(sharedKey, signed.getJWTClaimsSet());
    signed.verify(verifier);

    Assert.assertFalse("Must be invalid", signed.verify(verifier));
}
 
開發者ID:panchitoboy,項目名稱:shiro-jwt,代碼行數:21,代碼來源:MACVerifierExtendedTest.java

示例7: invalidTokenExpirationTime

import com.nimbusds.jwt.SignedJWT; //導入方法依賴的package包/類
@Test
public void invalidTokenExpirationTime() throws JOSEException, ParseException {
    JWTClaimsSet jwtClaims = getJWTClaimsSet("issuer", "subject", new Date(), new Date(), new Date());

    JWSHeader header = new JWSHeader(JWSAlgorithm.HS256);

    Payload payload = new Payload(jwtClaims.toJSONObject());

    JWSObject jwsObject = new JWSObject(header, payload);

    JWSSigner signer = new MACSigner(sharedKey);
    jwsObject.sign(signer);
    String token = jwsObject.serialize();

    SignedJWT signed = SignedJWT.parse(token);
    JWSVerifier verifier = new MACVerifierExtended(sharedKey, signed.getJWTClaimsSet());
    signed.verify(verifier);

    Assert.assertFalse("Must be invalid", signed.verify(verifier));
}
 
開發者ID:panchitoboy,項目名稱:shiro-jwt,代碼行數:21,代碼來源:MACVerifierExtendedTest.java

示例8: isValidJWToken

import com.nimbusds.jwt.SignedJWT; //導入方法依賴的package包/類
/**
 * Validates a JWT token.
 * @param secret secret used for generating the token
 * @param jwt token to validate
 * @return true if token is valid
 */
public static boolean isValidJWToken(String secret, SignedJWT jwt) {
	try {
		if (secret != null && jwt != null) {
			JWSVerifier verifier = new MACVerifier(secret);
			if (jwt.verify(verifier)) {
				Date referenceTime = new Date();
				JWTClaimsSet claims = jwt.getJWTClaimsSet();

				Date expirationTime = claims.getExpirationTime();
				Date notBeforeTime = claims.getNotBeforeTime();
				boolean expired = expirationTime == null || expirationTime.before(referenceTime);
				boolean notYetValid = notBeforeTime == null || notBeforeTime.after(referenceTime);

				return !(expired || notYetValid);
			}
		}
	} catch (JOSEException e) {
		logger.warn(null, e);
	} catch (ParseException ex) {
		logger.warn(null, ex);
	}
	return false;
}
 
開發者ID:Erudika,項目名稱:para,代碼行數:30,代碼來源:SecurityUtils.java

示例9: jwtMAC

import com.nimbusds.jwt.SignedJWT; //導入方法依賴的package包/類
/**
     * JWT
     * 使用HMAC SHA-256 進行加密 與 解密
     * 基於相同的 secret (對稱算法)
     * <p/>
     * 算法     Secret長度
     * HS256   32
     * HS384   64
     * HS512   64
     *
     * @throws Exception
     */
    @Test
    public void jwtMAC() throws Exception {

        String sharedSecret = RandomStringUtils.random(64, true, true);
        JWSSigner jwsSigner = new MACSigner(sharedSecret);

        //生成idToken
        final String payloadText = "I am MyOIDC";
        JWTClaimsSet claimsSet = new JWTClaimsSet.Builder()
                .subject("subject")
                .issuer("https://andaily.com")
                .claim("payloadText", payloadText)
                .expirationTime(new Date(new Date().getTime() + 60 * 1000))
                .build();

//        final JWSHeader header = new JWSHeader(JWSAlgorithm.HS256);
//        final JWSHeader header = new JWSHeader(JWSAlgorithm.HS384);
        final JWSHeader header = new JWSHeader(JWSAlgorithm.HS512);
        SignedJWT signedJWT = new SignedJWT(header, claimsSet);
        signedJWT.sign(jwsSigner);

        final String idToken = signedJWT.serialize();

        //校驗idToken
        final SignedJWT parseJWT = SignedJWT.parse(idToken);
        JWSVerifier jwsVerifier = new MACVerifier(sharedSecret);
        final boolean verify = parseJWT.verify(jwsVerifier);

        assertTrue(verify);
//        final Payload payload = parseJWT.getPayload();
        final JWTClaimsSet jwtClaimsSet = parseJWT.getJWTClaimsSet();
        assertEquals(jwtClaimsSet.getSubject(), "subject");

    }
 
開發者ID:monkeyk,項目名稱:MyOIDC,代碼行數:47,代碼來源:NimbusJoseJwtTest.java

示例10: decodeToken

import com.nimbusds.jwt.SignedJWT; //導入方法依賴的package包/類
public JWTClaimsSet decodeToken(String authHeader) throws ParseException, JOSEException {
	SignedJWT signedJWT = SignedJWT.parse(getSerializedToken(authHeader));
	if (signedJWT.verify(new MACVerifier(tokenSecret))) {
		return signedJWT.getJWTClaimsSet();
	} else {
		throw new JOSEException("Signature verification failed");
	}
}
 
開發者ID:nazareno,項目名稱:diferentonas-server,代碼行數:9,代碼來源:AuthUtils.java

示例11: getAuthorization

import com.nimbusds.jwt.SignedJWT; //導入方法依賴的package包/類
public Authorization getAuthorization(String jwtString, String principalId) throws WebApiClientException {
    try {
        SignedJWT signedJWT = parseAndVerifyToken(jwtString);
        JWTClaimsSet claimsSet = signedJWT.getJWTClaimsSet();
        if (claimsSet.getStringClaim(JwtUtil.PRINCIPAL).equalsIgnoreCase(principalId) &&
                claimsSet.getSubject().equalsIgnoreCase(SUBJECT_AUTHORIZATION)) {

            String responseString = claimsSet.getStringClaim(RESPONSE);
            return new Authorization(Authorization.Result.valueOf(responseString));
        }
        throw new WebApiClientException("Authorization token cannot be verified");
    } catch (ParseException e) {
        throw new WebApiClientException(e.getMessage());
    }
}
 
開發者ID:vrk-kpa,項目名稱:roles-auths-client,代碼行數:16,代碼來源:JwtUtil.java

示例12: getAuthorizationList

import com.nimbusds.jwt.SignedJWT; //導入方法依賴的package包/類
public AuthorizationList getAuthorizationList(String jwtString, String principalId) throws WebApiClientException {
    try {
        SignedJWT signedJWT = parseAndVerifyToken(jwtString);
        JWTClaimsSet claimsSet = signedJWT.getJWTClaimsSet();
        if (claimsSet.getStringClaim(JwtUtil.PRINCIPAL).equalsIgnoreCase(principalId) &&
                claimsSet.getSubject().equalsIgnoreCase(SUBJECT_AUTHORIZATION_LIST)) {
            String responseString = claimsSet.getStringClaim(RESPONSE);
            List<String> roles = objectMapper.readValue(responseString, List.class);
            return new AuthorizationList(roles);
        }
        throw new WebApiClientException("Authorization token cannot be verified");
    } catch (ParseException | IOException e) {
        throw new WebApiClientException(e.getMessage());
    }
}
 
開發者ID:vrk-kpa,項目名稱:roles-auths-client,代碼行數:16,代碼來源:JwtUtil.java

示例13: getCompanies

import com.nimbusds.jwt.SignedJWT; //導入方法依賴的package包/類
public List<YpaOrganization> getCompanies(String jwtString, String delegateId) throws WebApiClientException {
    try {
        SignedJWT signedJWT = parseAndVerifyToken(jwtString);
        JWTClaimsSet claimsSet = signedJWT.getJWTClaimsSet();
        if (claimsSet.getStringClaim(JwtUtil.END_USER).equalsIgnoreCase(delegateId) &&
                claimsSet.getSubject().equalsIgnoreCase(SUBJECT_ORG_ROLES)) {
            String responseString = claimsSet.getStringClaim(RESPONSE);
            List<YpaOrganization> orgRoles = objectMapper.readValue(responseString, new TypeReference<List<YpaOrganization>>(){});
            return orgRoles;
        }
        throw new WebApiClientException("OrganizationList token cannot be verified");
    } catch (ParseException | IOException e) {
        throw new WebApiClientException(e.getMessage());
    }
}
 
開發者ID:vrk-kpa,項目名稱:roles-auths-client,代碼行數:16,代碼來源:JwtUtil.java

示例14: verifyJwt

import com.nimbusds.jwt.SignedJWT; //導入方法依賴的package包/類
private boolean verifyJwt(String jwtToken, String expectedAudience) throws Exception {

    // parse signed token into header / claims
    SignedJWT signedJwt = SignedJWT.parse(jwtToken);
    JWSHeader jwsHeader = signedJwt.getHeader();

    // header must have algorithm("alg") and "kid"
    Preconditions.checkNotNull(jwsHeader.getAlgorithm());
    Preconditions.checkNotNull(jwsHeader.getKeyID());

    JWTClaimsSet claims = signedJwt.getJWTClaimsSet();

    // claims must have audience, issuer
    Preconditions.checkArgument(claims.getAudience().contains(expectedAudience));
    Preconditions.checkArgument(claims.getIssuer().equals(IAP_ISSUER_URL));

    // claim must have issued at time in the past
    Date currentTime = Date.from(Instant.now(clock));
    Preconditions.checkArgument(claims.getIssueTime().before(currentTime));
    // claim must have expiration time in the future
    Preconditions.checkArgument(claims.getExpirationTime().after(currentTime));

    // must have subject, email
    Preconditions.checkNotNull(claims.getSubject());
    Preconditions.checkNotNull(claims.getClaim("email"));

    // verify using public key : lookup with key id, algorithm name provided
    ECPublicKey publicKey = getKey(jwsHeader.getKeyID(), jwsHeader.getAlgorithm().getName());

    Preconditions.checkNotNull(publicKey);
    JWSVerifier jwsVerifier = new ECDSAVerifier(publicKey);
    return signedJwt.verify(jwsVerifier);
  }
 
開發者ID:GoogleCloudPlatform,項目名稱:java-docs-samples,代碼行數:34,代碼來源:VerifyIapRequestHeader.java

示例15: jwtRSA

import com.nimbusds.jwt.SignedJWT; //導入方法依賴的package包/類
/**
     * JWT
     * 使用 RSA 算法 生成 id_token
     * 以及對其進行校驗(verify)
     * 需要公私鑰對
     * <p/>
     * 支持算法
     * RS256
     * RS384
     * RS512
     *
     * @throws Exception
     */
    @Test
    public void jwtRSA() throws Exception {

        // RSA keyPair Generator
        final KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        /**
         * 長度 至少 1024, 建議 2048
         */
        final int keySize = 2048;
        keyPairGenerator.initialize(keySize);

        final KeyPair keyPair = keyPairGenerator.genKeyPair();
        //公鑰
        final RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
        //私鑰
        final PrivateKey privateKey = keyPair.getPrivate();

        //keyId
        String keyId = RandomUtils.randomNumber();

        //生成id_token
        JWSSigner jwsSigner = new RSASSASigner(privateKey);

//        JWSHeader header = new JWSHeader.Builder(JWSAlgorithm.RS256).keyID(keyId).build();
//        JWSHeader header = new JWSHeader.Builder(JWSAlgorithm.RS384).keyID(keyId).build();
        JWSHeader header = new JWSHeader.Builder(JWSAlgorithm.RS512).keyID(keyId).build();

        final String payloadText = "I am MyOIDC [RSA]";
        JWTClaimsSet claimsSet = new JWTClaimsSet.Builder()
                .subject("subject")
                .issuer("Issuer")
                .audience("Audience")
                .claim("payloadText", payloadText)
                .expirationTime(new Date(new Date().getTime() + 60 * 1000))
                .build();

        SignedJWT signedJWT = new SignedJWT(header, claimsSet);

        signedJWT.sign(jwsSigner);
        final String idToken = signedJWT.serialize();
        System.out.println(payloadText + " -> id_token: " + idToken);


        //校驗 id_token
        final SignedJWT parseJWT = SignedJWT.parse(idToken);

        JWSVerifier verifier = new RSASSAVerifier(publicKey);
        final boolean verify = parseJWT.verify(verifier);
        assertTrue(verify);

        final JWTClaimsSet jwtClaimsSet = parseJWT.getJWTClaimsSet();
        assertNotNull(jwtClaimsSet);
        assertEquals(payloadText, jwtClaimsSet.getStringClaim("payloadText"));


    }
 
開發者ID:monkeyk,項目名稱:MyOIDC,代碼行數:70,代碼來源:NimbusJoseJwtTest.java


注:本文中的com.nimbusds.jwt.SignedJWT.getJWTClaimsSet方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。