本文整理汇总了Java中com.nimbusds.jwt.JWTClaimsSet.getSubject方法的典型用法代码示例。如果您正苦于以下问题:Java JWTClaimsSet.getSubject方法的具体用法?Java JWTClaimsSet.getSubject怎么用?Java JWTClaimsSet.getSubject使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类com.nimbusds.jwt.JWTClaimsSet
的用法示例。
在下文中一共展示了JWTClaimsSet.getSubject方法的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: getUsername
import com.nimbusds.jwt.JWTClaimsSet; //导入方法依赖的package包/类
@Override
public String getUsername(Context ctx) {
String[] authTokenHeaderValues = ctx.request().headers().get(AuthUtils.AUTH_HEADER_KEY);
if ((authTokenHeaderValues != null) && (authTokenHeaderValues.length == 1) && (authTokenHeaderValues[0] != null)) {
String authHeader = authTokenHeaderValues[0];
try {
JWTClaimsSet claimSet = (JWTClaimsSet) authenticator.decodeToken(authHeader);
if (new DateTime(claimSet.getExpirationTime()).isAfter(DateTime.now())) {
return claimSet.getSubject();
}
} catch (ParseException | JOSEException e) {
Logger.error("Erro na validação do token: " + e.getMessage());
}
}
return null;
}
示例2: doFilter
import com.nimbusds.jwt.JWTClaimsSet; //导入方法依赖的package包/类
/**
* doFilter
* Perform Authorization Access via Token Validation.
*
* @param request Reference
* @param response Reference
* @param chain Filter Chain
* @throws java.io.IOException Thrown if IO Exceptions.
* @throws javax.servlet.ServletException Thrown if Servlet Exceptions.
*/
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
/**
* Obtain the JWT from the Authorization Header.
*/
HttpServletRequest httpRequest = (HttpServletRequest) request;
String authToken = YourMicroserviceSecurityConstants.obtainAuthorizationBearerToken(httpRequest);
/**
* Now Verify the Token and then, obtain the Subject Claim.
* Validate we have a username from an extracted token and we are not authenticated,
* then determine if the Token can be fully validated and has not Expired.
*/
if (authToken != null) {
try {
JWTClaimsSet jwtClaimsSet = yourMicroserviceToken.verifyToken(authToken);
if (jwtClaimsSet != null) {
/**
* Obtain our Subject from the Claims Set, which is our UserName, aka Your Microservice Person's
* Primary Email.
*/
String username = jwtClaimsSet.getSubject();
if (username != null && !username.isEmpty() &&
SecurityContextHolder.getContext().getAuthentication() == null) {
UserDetails userDetails = userDetailsService.loadUserByUsername(username);
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(httpRequest));
SecurityContextHolder.getContext().setAuthentication(authentication);
/**
* Perform Statistical Metric of a Token being Used.
*/
Integer countUpdated =
identityProviderEntityManager.incrementTokenHistoryUsage(jwtClaimsSet.getJWTID());
if (countUpdated == null || countUpdated != 1) {
/**
* We did not update the Usage Counter, this indicates that either the
* Token has Expired, Revoked or in some other state other than Active,
* so, immediately fail this token.
*/
SecurityContextHolder.getContext().setAuthentication(null);
}
}
}
} catch (YourMicroserviceInvalidTokenException iste) {
/**
* Do Nothing, as the attempt of the failed Token will be Denied...
*/
SecurityContextHolder.getContext().setAuthentication(null);
YourMicroserviceToken.LOGGER.warn("{}Invalid Token Denying Access.", YourMicroserviceToken.LOGGING_HEADER);
}
}
/**
* Continue filter chain.
*/
chain.doFilter(request, response);
}
示例3: retrieveCredential
import com.nimbusds.jwt.JWTClaimsSet; //导入方法依赖的package包/类
@Override
public JWTCredential retrieveCredential(String token) {
JWTCredential result = null;
try {
JWSObject jws = JWSObject.parse(token);
String apiKey = jws.getHeader().getKeyID();
if (apiKey != null && keys.contains(apiKey)) {
RSAKey rsaKey = (RSAKey) jwkSet.getKeyByKeyId(apiKey).toPublicJWK();
JWSVerifier verifier = new RSASSAVerifier(rsaKey);
if (jws.verify(verifier)) {
JWTClaimsSet claimsSet = JWTClaimsSet.parse(jws.getPayload().toJSONObject());
// Verify time validity of token.
Date creationTime = claimsSet.getIssueTime();
Date expirationTime = claimsSet.getExpirationTime();
Date now = new Date();
long validityPeriod = expirationTime.getTime() - creationTime.getTime();
if (creationTime.before(now) && now.before(expirationTime) && validityPeriod < 120000 /*2 minutes*/) {
JSONObject realmAccess = (JSONObject) claimsSet.getClaim("realm_access");
JSONArray rolesArray = (JSONArray) realmAccess.get("roles");
Set<String> roles = new HashSet<>();
rolesArray.forEach(r -> roles.add(r.toString()));
result = new JWTCredential(claimsSet.getSubject(), roles);
}
}
}
} catch (ParseException | JOSEException e) {
; // Token is not valid
}
return result;
}
示例4: createJwtProfile
import com.nimbusds.jwt.JWTClaimsSet; //导入方法依赖的package包/类
@SuppressWarnings("unchecked")
protected void createJwtProfile(final TokenCredentials credentials, final JWT jwt) throws ParseException {
final JWTClaimsSet claimSet = jwt.getJWTClaimsSet();
String subject = claimSet.getSubject();
if (subject == null) {
throw new TechnicalException("JWT must contain a subject ('sub' claim)");
}
if (!subject.contains(CommonProfile.SEPARATOR)) {
subject = JwtProfile.class.getName() + CommonProfile.SEPARATOR + subject;
}
final Date expirationTime = claimSet.getExpirationTime();
if (expirationTime != null) {
final Date now = new Date();
if (expirationTime.before(now)) {
logger.error("The JWT is expired: no profile is built");
return;
}
}
final Map<String, Object> attributes = new HashMap<>(claimSet.getClaims());
attributes.remove(JwtClaims.SUBJECT);
final List<String> roles = (List<String>) attributes.get(JwtGenerator.INTERNAL_ROLES);
attributes.remove(JwtGenerator.INTERNAL_ROLES);
final List<String> permissions = (List<String>) attributes.get(JwtGenerator.INTERNAL_PERMISSIONS);
attributes.remove(JwtGenerator.INTERNAL_PERMISSIONS);
final CommonProfile profile = ProfileHelper.buildProfile(subject, attributes);
if (roles != null) {
profile.addRoles(roles);
}
if (permissions != null) {
profile.addPermissions(permissions);
}
credentials.setUserProfile(profile);
}
示例5: retrieveCredential
import com.nimbusds.jwt.JWTClaimsSet; //导入方法依赖的package包/类
@Override
public JWTCredential retrieveCredential(String token) {
JWTCredential result = null;
try {
JWSObject jws = JWSObject.parse(token);
String apiKey = jws.getHeader().getKeyID();
if (apiKey != null && keys.containsKey(apiKey)) {
byte[] sharedSecret = keys.get(apiKey);
JWSVerifier verifier = new MACVerifier(sharedSecret);
if (jws.verify(verifier)) {
JWTClaimsSet claimsSet = JWTClaimsSet.parse(jws.getPayload().toJSONObject());
// Verify time validity of token.
Date creationTime = claimsSet.getIssueTime();
Date expirationTime = claimsSet.getExpirationTime();
Date now = new Date();
long validityPeriod = expirationTime.getTime() - creationTime.getTime();
if (creationTime.before(now) && now.before(expirationTime) && validityPeriod < 120000 /*2 minutes*/) {
JSONObject realmAccess = (JSONObject) claimsSet.getClaim("realm_access");
JSONArray rolesArray = (JSONArray) realmAccess.get("roles");
Set<String> roles = new HashSet<>();
rolesArray.forEach(r -> roles.add(r.toString()));
result = new JWTCredential(claimsSet.getSubject(), roles);
result.addInfo(API_KEY, apiKey);
}
}
}
} catch (ParseException | JOSEException e) {
; // Token is not valid
}
return result;
}
示例6: getYourMicroserviceClaimsVerifier
import com.nimbusds.jwt.JWTClaimsSet; //导入方法依赖的package包/类
/**
* getYourMicroserviceClaimsVerifier
* Obtains our Standard Claims Verifier.
*
* @return JWTClaimsVerifier Claims Verifier to be performed against a Claims Set.
*/
protected JWTClaimsVerifier getYourMicroserviceClaimsVerifier() {
/**
* Default JWT claims verifier. This class is thread-safe.
*
* Performs the following checks:
*
* + If an expiration time (exp) claim is present, makes sure it is ahead of the current time, else the JWT claims set is rejected.
* + If a not-before-time (nbf) claim is present, makes sure it is before the current time, else the JWT claims set is rejected.
* This class may be extended to perform additional checks.
*/
return new DefaultJWTClaimsVerifier() {
@Override
public void verify(JWTClaimsSet claimsSet)
throws BadJWTException {
/**
* Verify the Expiration of the Token and Not Before Use.
*/
super.verify(claimsSet);
/**
* Ensure Correct Issuer is from our own Eco-System.
*/
String issuer = claimsSet.getIssuer();
if (issuer == null || !issuer.equals(YourMicroserviceToken.YOUR_ORGANIZATION_ISSUER)) {
throw new BadJWTException("Invalid Token issuer");
}
/**
* Ensure Subject Specified.
*/
String subject = claimsSet.getSubject();
if (subject == null || subject.isEmpty()) {
throw new BadJWTException("Invalid Token Subject");
}
/**
* Ensure Subject Specified.
*/
String jti = claimsSet.getJWTID();
if (!isUUIDValid(jti)) {
throw new BadJWTException("Invalid Token Identifier");
}
/**
* Validate Audience, we need at least Once Specified.
*/
if (claimsSet.getAudience() == null || claimsSet.getAudience().isEmpty()) {
throw new BadJWTException("Invalid Audience");
}
/**
* Ensure Your Microservice was Specified.
*/
JSONObject yms = (JSONObject) claimsSet.getClaim(CLAIM_NAME_YOUR_MICROSERVICE);
if (yms == null || yms.isEmpty()) {
throw new BadJWTException("Invalid Your Microservice Claim");
}
/**
* Add Additional Claims Verification Here if and when Applicable...
*/
}
};
}
示例7: OIDCPrincipalExt
import com.nimbusds.jwt.JWTClaimsSet; //导入方法依赖的package包/类
protected OIDCPrincipalExt(JWTClaimsSet claimsSet, AccessToken accessToken) throws ParseException {
super(claimsSet.getSubject(), claimsSet.getClaims());
this.claimsSet = claimsSet;
this.accessToken = accessToken;
}
示例8: retrieveCredential
import com.nimbusds.jwt.JWTClaimsSet; //导入方法依赖的package包/类
@Override
public JWTCredential retrieveCredential(String token) {
JWTCredential result = null;
try {
// Parse the JWE string
JWEObject jweObject = JWEObject.parse(token);
String apiKey = jweObject.getHeader().getKeyID();
// Use this apiKey to select the correct privateKey
RSAKey privateKey = (RSAKey) jwkSet.getKeyByKeyId(apiKey);
// Decrypt with shared key
jweObject.decrypt(new RSADecrypter(privateKey));
// Extract payload
SignedJWT signedJWT = jweObject.getPayload().toSignedJWT();
// Check the HMAC, Optional
signedJWT.verify(new MACVerifier(apiKey));
// Retrieve the JWT claims...
JWTClaimsSet claimsSet = signedJWT.getJWTClaimsSet();
// Verify time validity of token.
Date creationTime = claimsSet.getIssueTime();
Date expirationTime = claimsSet.getExpirationTime();
Date now = new Date();
long validityPeriod = expirationTime.getTime() - creationTime.getTime();
if (creationTime.before(now) && now.before(expirationTime) && validityPeriod < 120000 /*2 minutes*/) {
JSONObject realmAccess = (JSONObject) claimsSet.getClaim("realm_access");
JSONArray rolesArray = (JSONArray) realmAccess.get("roles");
Set<String> roles = new HashSet<>();
rolesArray.forEach(r -> roles.add(r.toString()));
result = new JWTCredential(claimsSet.getSubject(), roles);
result.addInfo(API_KEY, apiKey);
result.addInfo(API_KEY, apiKey);
}
} catch (ParseException | JOSEException e) {
; // Token is not valid
}
return result;
}
示例9: getAuthentication
import com.nimbusds.jwt.JWTClaimsSet; //导入方法依赖的package包/类
@Override
public Authentication getAuthentication(JWTClaimsSet claimsSet) {
List<? extends GrantedAuthority> authorities = getAuthorities(claimsSet);
return new UsernamePasswordAuthenticationToken(claimsSet.getSubject(), EMPTY_PASSWORD, authorities);
}
开发者ID:visola,项目名称:spring-security-token-filter,代码行数:6,代码来源:UsernamePasswordAuthenticationTokenJwtClaimsSetTransformer.java