本文整理匯總了Java中org.jose4j.jwt.JwtClaims.getSubject方法的典型用法代碼示例。如果您正苦於以下問題:Java JwtClaims.getSubject方法的具體用法?Java JwtClaims.getSubject怎麽用?Java JwtClaims.getSubject使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類org.jose4j.jwt.JwtClaims
的用法示例。
在下文中一共展示了JwtClaims.getSubject方法的13個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: toUserInfo
import org.jose4j.jwt.JwtClaims; //導入方法依賴的package包/類
private static UserInfo toUserInfo(JwtClaims jwtClaims) {
try {
List<String> audiences = jwtClaims.getAudience();
if (audiences == null || audiences.isEmpty()) {
throw new UnauthenticatedException("Missing audience field");
}
String email = jwtClaims.getClaimValue(EMAIL_CLAIM_NAME, String.class);
String subject = jwtClaims.getSubject();
if (subject == null) {
throw new UnauthenticatedException("Missing subject field");
}
String issuer = jwtClaims.getIssuer();
if (issuer == null) {
throw new UnauthenticatedException("Missing issuer field");
}
return new UserInfo(audiences, email, subject, issuer);
} catch (MalformedClaimException exception) {
throw new UnauthenticatedException("Cannot read malformed claim", exception);
}
}
示例2: validateSharedResourceToken
import org.jose4j.jwt.JwtClaims; //導入方法依賴的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;
}
示例3: validateEntityToken
import org.jose4j.jwt.JwtClaims; //導入方法依賴的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;
}
示例4: validate
import org.jose4j.jwt.JwtClaims; //導入方法依賴的package包/類
@Override
public String validate(JwtContext jwtContext) throws MalformedClaimException
{
JwtClaims jwtClaims = jwtContext.getJwtClaims();
String subject = jwtClaims.getSubject();
if (subject == null && requireSubject)
{
return "No Subject (sub) claim is present.";
}
else if (expectedSubject != null && !expectedSubject.equals(subject))
{
return "Subject (sub) claim value (" + subject + ") doesn't match expected value of " + expectedSubject;
}
return null;
}
示例5: validateClaims
import org.jose4j.jwt.JwtClaims; //導入方法依賴的package包/類
@Override
protected Optional<String> validateClaims(JwtClaims jwtClaims) throws AuthenticationException {
try {
final String subject = jwtClaims.getSubject();
if ("good-one".equals(subject)) {
return Optional.of("good-one");
}
if ("bad-one".equals(subject)) {
throw new AuthenticationException("server ran out of entropy");
}
} catch (MalformedClaimException e) {
return Optional.absent();
}
return Optional.absent();
}
示例6: parseToken
import org.jose4j.jwt.JwtClaims; //導入方法依賴的package包/類
@Override
public String parseToken(final String token) {
try {
final String json = this.cipherExecutor.decode(token);
final JwtClaims claims = JwtClaims.parse(json);
if (!claims.getIssuer().equals(issuer)) {
LOGGER.error("Token issuer does not match CAS");
return null;
}
if (claims.getAudience().isEmpty() || !claims.getAudience().get(0).equals(issuer)) {
LOGGER.error("Token audience does not match CAS");
return null;
}
if (StringUtils.isBlank(claims.getSubject())) {
LOGGER.error("Token has no subject identifier");
return null;
}
final ClientInfo holder = ClientInfoHolder.getClientInfo();
if (!claims.getStringClaimValue("origin").equals(holder.getServerIpAddress())) {
LOGGER.error("Token origin does not match CAS");
return null;
}
if (!claims.getStringClaimValue("client").equals(holder.getClientIpAddress())) {
LOGGER.error("Token client does not match CAS");
return null;
}
if (claims.getExpirationTime().isBefore(NumericDate.now())) {
LOGGER.error("Token has expired.");
return null;
}
return claims.getSubject();
} catch (final Exception e) {
LOGGER.error(e.getMessage(), e);
}
return null;
}
示例7: JwtClaimsSetPrincipal
import org.jose4j.jwt.JwtClaims; //導入方法依賴的package包/類
/**
* Build the principal using a map.
*
* @param claimsSet
*/
public JwtClaimsSetPrincipal(final JwtClaims claimsSet) {
try {
this.claimsSet = claimsSet;
subject = claimsSet.getSubject();
authority = String.format("%[email protected]%s", subject, URI.create(claimsSet.getIssuer()).getHost());
} catch (final MalformedClaimException e) {
throw new ExceptionInInitializerError(e);
}
}
示例8: validateAuthToken
import org.jose4j.jwt.JwtClaims; //導入方法依賴的package包/類
public static JWTokenUserGroupMapping validateAuthToken(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
String login = subjectObject.getString(SUBJECT_LOGIN); // Npe
String groupName = subjectObject.getString(SUBJECT_GROUP_NAME); // Npe
if (login != null && !login.isEmpty() && groupName != null && !groupName.isEmpty()) {
return new JWTokenUserGroupMapping(jwtClaims, new UserGroupMapping(login, groupName));
}
}
} catch (InvalidJwtException | MalformedClaimException | JsonParsingException | NullPointerException e) {
LOGGER.log(Level.SEVERE, "Cannot validate jwt token", e);
}
return null;
}
示例9: getName
import org.jose4j.jwt.JwtClaims; //導入方法依賴的package包/類
/**
* This just parses the token without validation to extract one of the following in order to obtain
* the name to be used for the principal:
* upn
* preferred_username
* subject
*
* If there is an exception it sets the name to INVALID_TOKEN_NAME and saves the exception for access
* via {@link #getJwtException()}
*
* @return the name to use for the principal
*/
public String getName() {
if (name == null) {
name = "INVALID_TOKEN_NAME";
try {
// Build a JwtConsumer that doesn't check signatures or do any validation.
JwtConsumer firstPassJwtConsumer = new JwtConsumerBuilder()
.setSkipAllValidators()
.setDisableRequireSignature()
.setSkipSignatureVerification()
.build();
//The first JwtConsumer is basically just used to parse the JWT into a JwtContext object.
JwtContext jwtContext = firstPassJwtConsumer.process(bearerToken);
JwtClaims claimsSet = jwtContext.getJwtClaims();
// We have to determine the unique name to use as the principal name. It comes from upn, preferred_username, sub in that order
name = claimsSet.getClaimValue("upn", String.class);
if (name == null) {
name = claimsSet.getClaimValue("preferred_username", String.class);
if (name == null) {
name = claimsSet.getSubject();
}
}
} catch (Exception e) {
jwtException = e;
}
}
return name;
}
示例10: parseToken
import org.jose4j.jwt.JwtClaims; //導入方法依賴的package包/類
@Nullable
public static User parseToken(@NotNull JsonWebEncryption jwe, @NotNull String token, int tokenEnsureTime) {
try {
jwe.setCompactSerialization(token);
final JwtClaims claims = JwtClaims.parse(jwe.getPayload());
final NumericDate now = NumericDate.now();
final NumericDate expire = NumericDate.fromMilliseconds(now.getValueInMillis());
if (tokenEnsureTime > 0) {
expire.addSeconds(tokenEnsureTime);
}
if (claims.getExpirationTime() == null || claims.getExpirationTime().isBefore(expire)) {
return null;
}
if (claims.getNotBefore() == null || claims.getNotBefore().isAfter(now)) {
return null;
}
if (claims.getSubject() == null) {
return User.getAnonymous();
}
return User.create(
claims.getSubject(),
claims.getClaimValue("name", String.class),
claims.getClaimValue("email", String.class),
claims.getClaimValue("external", String.class)
);
} catch (JoseException | MalformedClaimException | InvalidJwtException e) {
log.warn("Token parsing error: " + e.getMessage());
return null;
}
}
示例11: getJWTData
import org.jose4j.jwt.JwtClaims; //導入方法依賴的package包/類
@Override
public JWTData getJWTData(String jwt) throws JWTError {
String keyId = null;
JWTData jwtData;
try {
JwtConsumer consumer = new JwtConsumerBuilder()
.setSkipAllValidators()
.setSkipSignatureVerification()
.build();
JwtContext jwtContext = consumer.process(jwt);
for (JsonWebStructure joseObject : jwtContext.getJoseObjects()) {
keyId = joseObject.getKeyIdHeaderValue();
if (keyId != null) {
break;
}
}
if (keyId == null) {
throw new JWTError("No kid found!", null);
}
JwtClaims claims = consumer.processToClaims(jwt);
jwtData = new JWTData(
claims.getIssuer(),
claims.getSubject(),
claims.getAudience().get(0),
keyId
);
} catch (InvalidJwtException|MalformedClaimException e) {
throw new JWTError("An error occurred parsing the JWT", e);
}
return jwtData;
}
示例12: handleJwtAssertionGrant
import org.jose4j.jwt.JwtClaims; //導入方法依賴的package包/類
/**
* Takes an assertion and converts it using an {@link InternalClaimsBuilder} to
* a JWT used internally
*
* @param assertion
* an external JWT assertion
* @param clientId
* client ID
* @return OAuth response
*/
private OAuthTokenResponse handleJwtAssertionGrant(final String assertion,
final String clientId,
final String audience) {
if (assertion == null) {
throw ErrorResponses.badRequest(ErrorCodes.INVALID_REQUEST, "Missing assertion");
}
if (clientId == null) {
throw ErrorResponses.badRequest(ErrorCodes.INVALID_REQUEST, "Missing client_id");
}
try {
final URI jwksUri = clientValidator.getJwksUri(clientId);
LOG.debug("jwksUri={}", jwksUri);
HttpsJwks httpsJwks = null;
if (jwksUri != null) {
httpsJwks = jwksMap.computeIfAbsent(jwksUri, uri -> new HttpsJwks(uri.toASCIIString()));
}
final JwtConsumerBuilder builder = new JwtConsumerBuilder();
if (httpsJwks == null) {
builder.setDisableRequireSignature()
.setSkipSignatureVerification();
} else {
builder.setVerificationKeyResolver(new HttpsJwksVerificationKeyResolver(httpsJwks));
}
if (audience == null) {
builder.setExpectedAudience(clientId);
} else {
builder.setExpectedAudience(clientId, audience);
}
final JwtConsumer jwtConsumer = builder
.build();
final JwtClaims internalClaims = internalClaimsBuilder.buildInternalJWTClaimsSet(jwtConsumer.processToClaims(assertion));
if (internalClaims.getSubject() == null) {
LOG.error("Subject is missing from {}", internalClaims);
throw ErrorResponses.internalServerError("Subject is missing from the resulting claims set.");
}
internalClaims.setGeneratedJwtId();
internalClaims.setIssuer(issuer.toASCIIString());
if (audience == null) {
internalClaims.setAudience(clientId);
} else {
internalClaims.setAudience(clientId, audience);
}
internalClaims.setIssuedAtToNow();
final Instant expirationTime = Instant.now().plus(jwtMaximumLifetimeInSeconds, ChronoUnit.SECONDS);
internalClaims.setExpirationTime(NumericDate.fromMilliseconds(expirationTime.toEpochMilli()));
return tokenCache.store(cryptoOps.sign(internalClaims), internalClaims.getAudience(), expirationTime);
} catch (final MalformedClaimException
| InvalidJwtException e) {
LOG.error("Unable to parse assertion", e);
throw ErrorResponses.badRequest(ErrorCodes.INVALID_REQUEST, "Unable to parse assertion");
}
}
示例13: getUserRoles
import org.jose4j.jwt.JwtClaims; //導入方法依賴的package包/類
@Override
public List<String> getUserRoles(DigilibRequest request) throws AuthOpException {
/*
* try token parameter first
*/
String id_token = request.getAsString("id_token");
if (id_token == null || id_token.isEmpty()) {
/*
* try token cookie next
*/
HttpServletRequest srvReq = ((DigilibServletRequest) request).getServletRequest();
Cookie[] cookies = srvReq.getCookies();
if (cookies != null) {
for (Cookie c : cookies) {
if (c.getName().equals(tokenCookieName)) {
id_token = c.getValue();
break;
}
}
}
if (id_token == null || id_token.isEmpty()) {
logger.error("Missing id token!");
return null;
}
}
// the first JwtConsumer is just used to parse the JWT into a JwtContext object.
try {
JwtContext jwtContext = firstPassJwtConsumer.process(id_token);
// extract issuer
String issuer = jwtContext.getJwtClaims().getIssuer();
// get validating consumer for this issuer
JwtConsumer secondPassJwtConsumer = idpJwtConsumers.get(issuer);
if (secondPassJwtConsumer == null) {
logger.error("Unknown id token issuer: "+issuer);
return null;
}
// validate token
secondPassJwtConsumer.processContext(jwtContext);
JwtClaims claims = jwtContext.getJwtClaims();
String sub = claims.getSubject();
// get roles
List<String> provided = idpRoles.get(issuer);
logger.debug("Roles provided by id_token (sub='"+sub+"'): "+provided);
return provided;
} catch (InvalidJwtException | MalformedClaimException e) {
logger.error("Error validating id token: "+e.getMessage());
return null;
}
}