本文整理匯總了Java中com.nimbusds.jwt.SignedJWT類的典型用法代碼示例。如果您正苦於以下問題:Java SignedJWT類的具體用法?Java SignedJWT怎麽用?Java SignedJWT使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
SignedJWT類屬於com.nimbusds.jwt包,在下文中一共展示了SignedJWT類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: readSignedJWT
import com.nimbusds.jwt.SignedJWT; //導入依賴的package包/類
private <T> JWTData<T> readSignedJWT(String data, KeySelector keySelector, Class<T> classType, JWTVerifier verifier) throws ParseException, JOSEException {
SignedJWT signedJWT = SignedJWT.parse(data);
String keyID = signedJWT.getHeader().getKeyID();
Key key = keySelector.selectSecretKey(keyID);
if (key == null) {
throw new InvalidJWTException(String.format("No key found for %s", keyID));
}
JWSVerifier jwsVerifier = jwsVerifierFactory.createJWSVerifier(signedJWT.getHeader(), key);
if (!signedJWT.verify(jwsVerifier)) {
throw new InvalidJWTException("JWT Signature verification failed");
}
if (verifier != null) {
if (!verifier.verify(signedJWT.getHeader(), signedJWT.getJWTClaimsSet())) {
throw new InvalidJWTException("JWT verification failed");
}
}
MetaJWTData metaJWTData = new MetaJWTData(keyID, signedJWT.getHeader().getCustomParams());
return readJSONString(signedJWT.getPayload().toString(), classType, metaJWTData);
}
示例2: retrieveUsernamePasswordFromLoginToken
import com.nimbusds.jwt.SignedJWT; //導入依賴的package包/類
/**
* retrieves username and password from JSON web tocken
*
* @param token - the serialized JSON web token from login
* @return username and password (combined by ":")
*/
public static String retrieveUsernamePasswordFromLoginToken(String token) {
JWEObject jweObject;
try {
jweObject = JWEObject.parse(token);
// Decrypt with shared key
jweObject.decrypt(new RSADecrypter(RSA_KEYS.getPrivate()));
// Extract payload
SignedJWT signedJWT = jweObject.getPayload().toSignedJWT();
RSAKey serverPublicKey = RSAKey.parse(signedJWT.getHeader().getJWK().toJSONObject());
if (signedJWT.verify(new RSASSAVerifier(serverPublicKey))) {
//Token is valid
String username = signedJWT.getJWTClaimsSet().getSubject();
String password = signedJWT.getJWTClaimsSet().getStringClaim("password");
return username + ":" + password;
}
} catch (ParseException | JOSEException e) {
LOGGER.error(e);
}
return null;
}
示例3: testRolesEndpointToJWTString
import com.nimbusds.jwt.SignedJWT; //導入依賴的package包/類
/**
*
* @throws Exception
*/
@Test
public void testRolesEndpointToJWTString() throws Exception {
// Transform the JSON content into a signed JWT
String jwt = TokenUtils.generateTokenString("/Token1.json");
System.out.println(jwt);
/* Note that if you try to validate this token string via jwt.io debugger, you need to take the
/publicKey.pem contents, and use
-----BEGIN PUBLIC KEY-----
...
-----END PUBLIC KEY-----
rather than the:
-----BEGIN RSA PUBLIC KEY-----
...
-----END RSA PUBLIC KEY-----
in the file.
*/
// Validate the string via Nimbus
SignedJWT signedJWT = SignedJWT.parse(jwt);
PublicKey publicKey = TokenUtils.readPublicKey("/publicKey.pem");
Assert.assertTrue(publicKey instanceof RSAPublicKey, "publicKey isa RSAPublicKey");
JWSVerifier verifier = new RSASSAVerifier((RSAPublicKey)publicKey);
Assert.assertTrue(signedJWT.verify(verifier));
}
示例4: generateCookieBody
import com.nimbusds.jwt.SignedJWT; //導入依賴的package包/類
String generateCookieBody(int secondsToLive) {
RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
JWSSigner signer = new RSASSASigner(privateKey);
DateTime expDate = new DateTime((new Date()).getTime() + secondsToLive * 1000);
JWTClaimsSet claimsSet = new JWTClaimsSet.Builder()
.issuer("digital-display-garden")
.claim("exp", expDate.toString())
.build();
SignedJWT signedJWT = new SignedJWT(
new JWSHeader(JWSAlgorithm.RS256),
claimsSet
);
try {
signedJWT.sign(signer);
return signedJWT.serialize();
} catch (JOSEException e) {
e.printStackTrace();
return "";
}
}
示例5: generateSharedGoogleSecret
import com.nimbusds.jwt.SignedJWT; //導入依賴的package包/類
String generateSharedGoogleSecret(String originatingURL) {
RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
JWSSigner signer = new RSASSASigner(privateKey);
// Expire in 60 seconds
DateTime expDate = new DateTime((new Date()).getTime() + 60 * 1000);
JWTClaimsSet claimsSet = new JWTClaimsSet.Builder()
.issuer("digital-display-garden")
.claim("originatingURL", originatingURL)
.claim("exp", expDate.toString())
.build();
SignedJWT signedJWT = new SignedJWT(
new JWSHeader(JWSAlgorithm.RS256),
claimsSet
);
try {
signedJWT.sign(signer);
return signedJWT.serialize();
} catch (JOSEException e) {
e.printStackTrace();
return "";
}
}
示例6: validateToken
import com.nimbusds.jwt.SignedJWT; //導入依賴的package包/類
/**
* This method provides a single method for validating the JWT for use in
* request processing. It provides for the override of specific aspects of
* this implementation through submethods used within but also allows for the
* override of the entire token validation algorithm.
*
* @param jwtToken the token to validate
* @return true if valid
*/
protected boolean validateToken(SignedJWT jwtToken) {
boolean sigValid = validateSignature(jwtToken);
if (!sigValid) {
LOG.warn("Signature could not be verified");
}
boolean audValid = validateAudiences(jwtToken);
if (!audValid) {
LOG.warn("Audience validation failed.");
}
boolean expValid = validateExpiration(jwtToken);
if (!expValid) {
LOG.info("Expiration validation failed.");
}
return sigValid && audValid && expValid;
}
示例7: validateSignature
import com.nimbusds.jwt.SignedJWT; //導入依賴的package包/類
/**
* Verify the signature of the JWT token in this method. This method depends
* on the public key that was established during init based upon the
* provisioned public key. Override this method in subclasses in order to
* customize the signature verification behavior.
*
* @param jwtToken the token that contains the signature to be validated
* @return valid true if signature verifies successfully; false otherwise
*/
protected boolean validateSignature(SignedJWT jwtToken) {
boolean valid = false;
if (JWSObject.State.SIGNED == jwtToken.getState()) {
LOG.debug("JWT token is in a SIGNED state");
if (jwtToken.getSignature() != null) {
LOG.debug("JWT token signature is not null");
try {
JWSVerifier verifier = new RSASSAVerifier(publicKey);
if (jwtToken.verify(verifier)) {
valid = true;
LOG.debug("JWT token has been successfully verified");
} else {
LOG.warn("JWT signature verification failed.");
}
} catch (JOSEException je) {
LOG.warn("Error while validating signature", je);
}
}
}
return valid;
}
示例8: validateExpiration
import com.nimbusds.jwt.SignedJWT; //導入依賴的package包/類
/**
* Validate that the expiration time of the JWT token has not been violated.
* If it has then throw an AuthenticationException. Override this method in
* subclasses in order to customize the expiration validation behavior.
*
* @param jwtToken the token that contains the expiration date to validate
* @return valid true if the token has not expired; false otherwise
*/
protected boolean validateExpiration(SignedJWT jwtToken) {
boolean valid = false;
try {
Date expires = jwtToken.getJWTClaimsSet().getExpirationTime();
if (expires != null && new Date().before(expires)) {
LOG.debug("JWT token expiration date has been "
+ "successfully validated");
valid = true;
} else {
LOG.warn("JWT expiration date validation failed.");
}
} catch (ParseException pe) {
LOG.warn("JWT expiration date validation failed.", pe);
}
return valid;
}
示例9: getJWT
import com.nimbusds.jwt.SignedJWT; //導入依賴的package包/類
protected SignedJWT getJWT(String sub, Date expires, RSAPrivateKey privateKey)
throws Exception {
JWTClaimsSet claimsSet = new JWTClaimsSet();
claimsSet.setSubject(sub);
claimsSet.setIssueTime(new Date(new Date().getTime()));
claimsSet.setIssuer("https://c2id.com");
claimsSet.setCustomClaim("scope", "openid");
claimsSet.setExpirationTime(expires);
List<String> aud = new ArrayList<String>();
aud.add("bar");
claimsSet.setAudience("bar");
JWSHeader header = new JWSHeader.Builder(JWSAlgorithm.RS256).build();
SignedJWT signedJWT = new SignedJWT(header, claimsSet);
Base64URL sigInput = Base64URL.encode(signedJWT.getSigningInput());
JWSSigner signer = new RSASSASigner(privateKey);
signedJWT.sign(signer);
return signedJWT;
}
示例10: getIdToken
import com.nimbusds.jwt.SignedJWT; //導入依賴的package包/類
protected JWT getIdToken(@Nonnull ClientID clientId, @Nullable Nonce nonce, @Nullable AccessTokenHash atHash,
@Nullable CodeHash cHash) throws GeneralSecurityException, JOSEException, ParseException {
JWTClaimsSet claims = getIdTokenClaims(clientId, nonce, atHash, cHash);
RSAKey key = getSigningJwk();
JWSHeader.Builder headerBuilder = new JWSHeader.Builder(JWSAlgorithm.RS256)
.type(JOSEObjectType.JWT);
if (params.getBool(INCLUDE_SIGNING_CERT)) {
headerBuilder = headerBuilder.jwk(key.toPublicJWK());
}
JWSHeader header = headerBuilder.build();
SignedJWT signedJwt = new SignedJWT(header, claims);
JWSSigner signer = new RSASSASigner(key);
signedJwt.sign(signer);
return signedJwt;
}
示例11: method_verifySignature_should_validate_signedJWT
import com.nimbusds.jwt.SignedJWT; //導入依賴的package包/類
@Test
public void method_verifySignature_should_validate_signedJWT() throws Exception {
sharedSecret = TOKEN.getBytes();
signedJWT = spy(SignedJWT.parse(TOKEN));
mockStatic(SignedJWT.class);
when(SignedJWT.class, "parse", TOKEN).thenReturn(signedJWT);
when(sessionIndentifierStream.filter(any())).thenReturn(sessionIndentifierStream);
when(sessionIndentifierStream.findFirst()).thenReturn(sessionIdentifierOptional);
when(sessionIdentifierOptional.get()).thenReturn(sessionIdentifier);
when(sessionIdentifier.getSecretKey()).thenReturn(sharedSecret);
whenNew(MACVerifier.class).withArguments(sharedSecret).thenReturn(verifier);
when(signedJWT.verify(verifier)).thenReturn(POSITIVE_ANSWER);
assertTrue(securityContext.verifySignature(TOKEN));
}
示例12: setUp
import com.nimbusds.jwt.SignedJWT; //導入依賴的package包/類
@Before
public void setUp() throws Exception {
secretKey = TOKEN.getBytes();
sessionIdentifier = spy(new SessionIdentifier(TOKEN, secretKey, authenticationData));
signer = new MACSigner(secretKey);
whenNew(MACSigner.class).withArguments(secretKey).thenReturn(signer);
JWTClaimsSet.Builder builder = new JWTClaimsSet.Builder();
builder.issuer(USER);
builder.claim("mode", MODE);
JWTClaimsSet buildClaim = builder.build();
when(authenticationData.buildClaimSet()).thenReturn(buildClaim);
jwsHeader = new JWSHeader(JWSAlgorithm.HS256);
signedJWT = spy(new SignedJWT(jwsHeader, buildClaim));
whenNew(SignedJWT.class).withAnyArguments().thenReturn(signedJWT);
}
示例13: 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");
}
示例14: retrievePublicKeyFromLoginToken
import com.nimbusds.jwt.SignedJWT; //導入依賴的package包/類
/**
* retrieves the client public key from Login Token
*
* @param token - the serialized JSON Web Token from login
* @return the public key as JWK object
*/
public static JWK retrievePublicKeyFromLoginToken(String token) {
JWK result = null;
JWEObject jweObject;
try {
jweObject = JWEObject.parse(token);
// Decrypt with shared key
jweObject.decrypt(new RSADecrypter(RSA_KEYS.getPrivate()));
// Extract payload
SignedJWT signedJWT = jweObject.getPayload().toSignedJWT();
result = signedJWT.getHeader().getJWK();
RSAKey publicKey = RSAKey.parse(result.toJSONObject());
if (signedJWT.verify(new RSASSAVerifier(publicKey))) {
return result;
}
} catch (ParseException | JOSEException e) {
LOGGER.error(e);
}
return null;
}
示例15: createEmptyJWTwithPublicKey
import com.nimbusds.jwt.SignedJWT; //導入依賴的package包/類
/**
* creates an empty JSON Web Token
*
* @param webAppBaseURL - the base url of the application
*
* @return the JSON WebToken
*/
public static SignedJWT createEmptyJWTwithPublicKey(String webAppBaseURL) {
ZonedDateTime currentTime = ZonedDateTime.now(ZoneOffset.UTC);
JWTClaimsSet claims = new JWTClaimsSet.Builder().issuer(webAppBaseURL).jwtID(UUID.randomUUID().toString())
.issueTime(Date.from(currentTime.toInstant())).build();
String keyID = UUID.randomUUID().toString();
JWK jwk = new RSAKey.Builder((RSAPublicKey) RSA_KEYS.getPublic()).keyID(keyID).build();
JWSHeader jwsHeader = new JWSHeader.Builder(JWSAlgorithm.RS256).jwk(jwk).build();
SignedJWT signedJWT = new SignedJWT(jwsHeader, claims);
try {
signedJWT.sign(new RSASSASigner(RSA_KEYS.getPrivate()));
} catch (JOSEException e) {
LOGGER.error(e);
}
return signedJWT;
}