本文整理汇总了Java中org.jose4j.jwt.consumer.JwtConsumer类的典型用法代码示例。如果您正苦于以下问题:Java JwtConsumer类的具体用法?Java JwtConsumer怎么用?Java JwtConsumer使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
JwtConsumer类属于org.jose4j.jwt.consumer包,在下文中一共展示了JwtConsumer类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: getJwtClaims
import org.jose4j.jwt.consumer.JwtConsumer; //导入依赖的package包/类
private JwtClaims getJwtClaims(String token) {
HttpsJwks httpsJkws = new HttpsJwks(jwksBaseURL);
HttpsJwksVerificationKeyResolver httpsJwksKeyResolver = new HttpsJwksVerificationKeyResolver(httpsJkws);
JwtConsumer jwtConsumer = new JwtConsumerBuilder().setRequireExpirationTime().setAllowedClockSkewInSeconds(3600)
.setExpectedIssuer(jwksIssuer)
// whom the JWT needs to have been issued by
.setExpectedAudience(jwksAudience).setVerificationKeyResolver(httpsJwksKeyResolver).build();
try {
// Validate the JWT and process it to the Claims
JwtClaims jwtClaims = jwtConsumer.processToClaims(token);
return jwtClaims;
} catch (InvalidJwtException e) {
// Anyway here throws the exception , so no need to log the error.
// log the error if required from where this function invokes
// logger.error("Invalid JWT! " + e);
throw new AuthenticationServiceException("Invalid Token");
}
}
示例2: newJwsConsumer
import org.jose4j.jwt.consumer.JwtConsumer; //导入依赖的package包/类
private JwtConsumer newJwsConsumer(){
// If we don't have a JWK we can't create a consumer to verify anything.
// Why might we not have one? If the remote authentication service was down when Stroom started
// then we wouldn't. It might not be up now but we're going to try and fetch it.
if(jwk == null){
fetchNewPublicKeys();
}
final String expectedIssuer = stroomPropertyService.getPropertyOrThrow("stroom.stats.auth.expectedIssuer");
JwtConsumerBuilder builder = new JwtConsumerBuilder()
.setAllowedClockSkewInSeconds(30) // allow some leeway in validating time based claims to account for clock skew
.setRequireSubject() // the JWT must have a subject claim
.setVerificationKey(this.jwk.getPublicKey()) // verify the signature with the public key
.setRelaxVerificationKeyValidation() // relaxes key length requirement
.setJwsAlgorithmConstraints( // only allow the expected signature algorithm(s) in the given context
new AlgorithmConstraints(AlgorithmConstraints.ConstraintType.WHITELIST, // which is only RS256 here
AlgorithmIdentifiers.RSA_USING_SHA256))
.setExpectedIssuer(expectedIssuer);
return builder.build();
}
示例3: buildConsumer
import org.jose4j.jwt.consumer.JwtConsumer; //导入依赖的package包/类
public JwtConsumer buildConsumer(final HttpsJwks jwks,
final List<String> audience) {
final JwtConsumerBuilder builder = new JwtConsumerBuilder()
.setRequireJwtId();
if (jwks != null) {
builder
.setVerificationKeyResolver(new HttpsJwksVerificationKeyResolver(jwks));
} else {
builder.setSkipSignatureVerification();
}
if (audience != null) {
builder
.setExpectedAudience(audience.toArray(new String[audience.size()]));
} else {
builder.setSkipDefaultAudienceValidation();
}
return builder.build();
}
示例4: toClaimsSet
import org.jose4j.jwt.consumer.JwtConsumer; //导入依赖的package包/类
/**
* {@inheritDoc}
*/
@Override
public JwtClaims toClaimsSet(final String jwt,
final String audience,
final HttpsJwks httpsJwks) {
final JwtConsumerBuilder builder = new JwtConsumerBuilder()
.setVerificationKeyResolver(new HttpsJwksVerificationKeyResolver(httpsJwks));
if (audience == null) {
builder.setSkipDefaultAudienceValidation();
} else {
builder.setExpectedAudience(audience);
}
final JwtConsumer jwtConsumer = builder
.build();
try {
return jwtConsumer.processToClaims(jwt);
} catch (final InvalidJwtException e) {
throw new InternalServerErrorException(e);
}
}
示例5: validateJwtToken
import org.jose4j.jwt.consumer.JwtConsumer; //导入依赖的package包/类
public static String validateJwtToken( String jwt ) throws InvalidJwtException {
JwtConsumer jwtConsumer = new JwtConsumerBuilder()
// the JWT must have an expiration time
.setRequireExpirationTime()
// but the expiration time can't be too crazy
.setMaxFutureValidityInMinutes( 300 )
// allow some leeway in validating time based claims to account for clock skew
.setAllowedClockSkewInSeconds( 30 )
// whom the JWT needs to have been issued by
.setExpectedIssuer( issuer )
// verify the signature with the public key
.setVerificationKey( rsaJsonWebKey.getKey() )
.build();
// Validate the JWT and process it to the Claims
JwtClaims jwtClaims = jwtConsumer.processToClaims( jwt );
System.out.println( "JWT validation succeeded! " + jwtClaims );
// validate and return the encoded user id
return jwtClaims.getClaimsMap().get("id").toString();
}
示例6: isTokenExpired
import org.jose4j.jwt.consumer.JwtConsumer; //导入依赖的package包/类
private static boolean isTokenExpired(String authorization) {
boolean expired = false;
String jwt = getJwtFromAuthorization(authorization);
if(jwt != null) {
JwtConsumer consumer = new JwtConsumerBuilder()
.setDisableRequireSignature()
.setSkipSignatureVerification()
.build();
try {
consumer.processToClaims(jwt);
} catch (InvalidJwtException e) {
if(e.hasExpired()) expired = true;
}
}
return expired;
}
示例7: validateSharedResourceToken
import org.jose4j.jwt.consumer.JwtConsumer; //导入依赖的package包/类
public static String validateSharedResourceToken(Key key, String jwt) {
JwtConsumer jwtConsumer = new JwtConsumerBuilder()
.setVerificationKey(key)
.setRelaxVerificationKeyValidation()
.build();
try {
JwtClaims jwtClaims = jwtConsumer.processToClaims(jwt);
String subject = jwtClaims.getSubject();
try (JsonReader reader = Json.createReader(new StringReader(subject))) {
JsonObject subjectObject = reader.readObject(); // JsonParsingException
return subjectObject.getString(SHARED_ENTITY_UUID); // Npe
}
} catch (InvalidJwtException | MalformedClaimException | JsonParsingException | NullPointerException e) {
LOGGER.log(Level.SEVERE, "Cannot validate jwt token", e);
}
return null;
}
示例8: validateEntityToken
import org.jose4j.jwt.consumer.JwtConsumer; //导入依赖的package包/类
public static String validateEntityToken(Key key, String jwt) {
JwtConsumer jwtConsumer = new JwtConsumerBuilder()
.setVerificationKey(key)
.setRelaxVerificationKeyValidation()
.build();
try {
JwtClaims jwtClaims = jwtConsumer.processToClaims(jwt);
String subject = jwtClaims.getSubject();
try (JsonReader reader = Json.createReader(new StringReader(subject))) {
JsonObject subjectObject = reader.readObject(); // JsonParsingException
return subjectObject.getString(ENTITY_KEY); // Npe
}
} catch (InvalidJwtException | MalformedClaimException | JsonParsingException | NullPointerException e) {
LOGGER.log(Level.SEVERE, "Cannot validate jwt token", e);
}
return null;
}
示例9: authJwt
import org.jose4j.jwt.consumer.JwtConsumer; //导入依赖的package包/类
public static String authJwt(Audience audience, String jwt) {
if(DataHelper.isJwtExists(jwt)) {
JwtConsumer jwtConsumer = new JwtConsumerBuilder()
.setRequireExpirationTime() // the JWT must have an expiration time
.setRequireSubject() // the JWT must have a subject claim
.setExpectedIssuer(RAuthCore.JWT_ISSUER) // whom the JWT needs to have been issued by
.setExpectedAudience(audience.name()) // to whom the JWT is intended for
.setVerificationKey(RAuthCore.RSAKEY.getKey()) // verify the signature with the public key
.build(); // create the JwtConsumer instance
try {
// Validate the JWT and process it to the Claims
JwtClaims payload = jwtConsumer.processToClaims(jwt);
if(RAuthCore.USE_REDIS_EXPIRE && audience.equals(Audience.WEB))
DataHelper.setJwtExp(jwt, RAuthCore.REDIS_WEB_EXP);
return payload.toString();
} catch (InvalidJwtException e) {
// InvalidJwtException will be thrown, if the JWT failed processing or validation in anyway.
// Hopefully with meaningful explanations(s) about what went wrong.
e.printStackTrace();
}
}
return null;
}
示例10: validateToken
import org.jose4j.jwt.consumer.JwtConsumer; //导入依赖的package包/类
/**
* Check if it was issued by the server and if it's not expired
* @param java_web_token
* @throws InvalidJwtException if the token is invalid
*/
private String validateToken(String java_web_token) throws InvalidJwtException {
String username = null;
RsaJsonWebKey rsaJsonWebKey = RsaKeyProducer.produce();
System.out.println("RSA hash code... " + rsaJsonWebKey.hashCode());
JwtConsumer jwtConsumer = new JwtConsumerBuilder()
.setRequireSubject() // the JWT must have a subject claim
.setVerificationKey(rsaJsonWebKey.getKey()) // verify the signature with the public key
.build(); // create the JwtConsumer instance
try {
// Validate the JWT and process it to the Claims
JwtClaims jwtClaims = jwtConsumer.processToClaims(java_web_token);
username = (String) jwtClaims.getClaimValue("sub");
System.out.println("JWT validation succeeded! " + jwtClaims);
} catch (InvalidJwtException e) {
e.printStackTrace(); //on purpose
throw e;
}
return username;
}
示例11: verifyToken
import org.jose4j.jwt.consumer.JwtConsumer; //导入依赖的package包/类
public static User verifyToken(String data) {
JwtConsumer jwtConsumer = new JwtConsumerBuilder()
.setRequireExpirationTime() // the JWT must have an expiration time
.setMaxFutureValidityInMinutes(60*24) // but the expiration time can't be too crazy
.setAllowedClockSkewInSeconds(30) // allow some leeway in validating time based claims to account for clock skew
.setRequireSubject() // the JWT must have a subject claim
.setExpectedIssuer("server") // whom the JWT needs to have been issued by
.setExpectedAudience("client") // to whom the JWT is intended for
.setVerificationKey(new HmacKey(secret.getBytes())) // verify the signature with the public key
.build(); // create the JwtConsumer instance
try
{
// Validate the JWT and process it to the Claims
JwtClaims jwtClaims = jwtConsumer.processToClaims(data);
ObjectMapper mapper = new ObjectMapper();
String json = (String) jwtClaims.getClaimValue("userData");
byte[] bytes = json.getBytes("UTF-8");
return mapper.readValue(bytes, User.class);
}
catch (Exception e) {
return null;
}
}
示例12: validateToken
import org.jose4j.jwt.consumer.JwtConsumer; //导入依赖的package包/类
public static void validateToken(byte[] accessToken, String aud, int contentFormat) throws MalformedClaimException, JSONException, JoseException {
if(contentFormat == MediaTypeRegistry.APPLICATION_JSON) {
try
{
JwtConsumer jwtConsumer = new JwtConsumerBuilder()
.setAllowedClockSkewInSeconds(30)
.setExpectedAudience(aud)
.setVerificationKey(config.getSignAndEncryptKey().getPublicKey())
.build();
// Validate the JWT and process it to the Claims
JwtClaims jwtClaims = jwtConsumer.processToClaims(new String(accessToken));
Assert.assertTrue(jwtClaims.getAudience().contains(aud));
}
catch (Exception e)
{
Assert.fail("Could not validate token.");
}
}
else if(contentFormat == MediaTypeRegistry.APPLICATION_CBOR) {
Assert.fail("Not implemented.");
}
}
示例13: validateJWT
import org.jose4j.jwt.consumer.JwtConsumer; //导入依赖的package包/类
@Test
public void validateJWT() throws Exception {
Assert.assertEquals("myAud", token.getAudience());
JwtConsumer jwtConsumer = new JwtConsumerBuilder()
.setAllowedClockSkewInSeconds(30)
.setExpectedAudience("myAud")
.setVerificationKey(config.getSignAndEncryptKey().getPublicKey())
.build();
try
{
// Validate the JWT and process it to the Claims
JwtClaims jwtClaims = jwtConsumer.processToClaims(token.getAccessToken());
Assert.assertTrue(jwtClaims.getAudience().contains("myAud"));
}
catch (InvalidJwtException e)
{
Assert.fail("Could not validate token.");
}
}
示例14: read
import org.jose4j.jwt.consumer.JwtConsumer; //导入依赖的package包/类
public JwtClaimsAdapter read(String jwt) {
JwtConsumer jwtConsumer = new JwtConsumerBuilder()
.setRequireExpirationTime()
.setAllowedClockSkewInSeconds(30)
.setRequireSubject()
.setExpectedIssuer("registry")
.setVerificationKey(key)
.build();
try {
JwtClaims jwtClaims = jwtConsumer.processToClaims(jwt);
return new JwtClaimsAdapter(jwtClaims);
} catch (InvalidJwtException e) {
throw new RuntimeException(e);
}
}
示例15: readToken
import org.jose4j.jwt.consumer.JwtConsumer; //导入依赖的package包/类
public Optional<TokenDTO> readToken(String token) {
try {
Key key = new HmacKey(secret.getBytes("UTF-8"));
JwtConsumer jwtConsumer = new JwtConsumerBuilder().setVerificationKey(key).build();
JwtClaims jwtClaims = jwtConsumer.processToClaims(token);
Map<String, Object> claimsMap = jwtClaims.getClaimsMap();
TokenDTO data = new TokenDTO();
data.setEmail((String) claimsMap.get(EMAIL_KEY));
data.setIssuer((String) claimsMap.get(ReservedClaimNames.ISSUER));
data.setSubject((String) claimsMap.get(ReservedClaimNames.SUBJECT));
return Optional.of(data);
} catch (Exception e) {
return Optional.empty();
}
}