use of com.nimbusds.jwt.SignedJWT in project SEPA by arces-wot.
the class KeyCloakSecurityManager method validateToken.
/**
* Requesting Party Token
*
* If you want to validate these tokens without a call to the remote introspection endpoint, you can decode the RPT and query for its validity locally.
* Once you decode the token, you can also use the permissions within the token to enforce authorization decisions.
*
* This is essentially what the policy enforcers do. Be sure to:
* 1) Validate the signature of the RPT (based on the realm’s public key)
* 2) Query for token validity based on its exp, iat, and aud claims
*
* The claim "preferred_username" is used to identify the user
*/
@Override
public synchronized ClientAuthorization validateToken(String accessToken) {
logger.log(Level.getLevel("oauth"), "VALIDATE TOKEN");
// Parse token
SignedJWT signedJWT = null;
try {
signedJWT = SignedJWT.parse(accessToken);
} catch (ParseException e) {
logger.log(Level.getLevel("oauth"), e.getMessage());
return new ClientAuthorization("invalid_request", "ParseException: " + e.getMessage());
}
// Verify token
try {
if (!signedJWT.verify(verifier)) {
logger.log(Level.getLevel("oauth"), "Signed JWT not verified");
return new ClientAuthorization("invalid_grant", "Signed JWT not verified");
}
} catch (JOSEException e) {
logger.log(Level.getLevel("oauth"), e.getMessage());
return new ClientAuthorization("invalid_grant", "JOSEException: " + e.getMessage());
}
String uid;
// Process token (validate)
JWTClaimsSet claimsSet = null;
try {
claimsSet = signedJWT.getJWTClaimsSet();
logger.log(Level.getLevel("oauth"), claimsSet);
// Get client credentials for accessing the SPARQL endpoint
uid = claimsSet.getStringClaim("username");
if (uid == null) {
logger.log(Level.getLevel("oauth"), "<username> claim is null. Look for <preferred_username>");
uid = claimsSet.getStringClaim("preferred_username");
if (uid == null) {
logger.log(Level.getLevel("oauth"), "USER ID not found...");
return new ClientAuthorization("invalid_grant", "Username claim not found");
}
}
logger.log(Level.getLevel("oauth"), "Subject: " + claimsSet.getSubject());
logger.log(Level.getLevel("oauth"), "Issuer: " + claimsSet.getIssuer());
logger.log(Level.getLevel("oauth"), "Username: " + uid);
} catch (ParseException e) {
logger.error(e.getMessage());
return new ClientAuthorization("invalid_grant", "ParseException. " + e.getMessage());
}
// Check token expiration (an "invalid_grant" error is raised if the token is
// expired)
Date now = new Date();
long nowUnixSeconds = (now.getTime() / 1000) * 1000;
Date expiring = claimsSet.getExpirationTime();
Date notBefore = claimsSet.getNotBeforeTime();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
if (expiring.getTime() - nowUnixSeconds < 0) {
logger.log(Level.getLevel("oauth"), "Token is expired: " + sdf.format(claimsSet.getExpirationTime()) + " < " + sdf.format(new Date(nowUnixSeconds)));
return new ClientAuthorization("invalid_grant", "Token issued at " + sdf.format(claimsSet.getIssueTime()) + " is expired: " + sdf.format(claimsSet.getExpirationTime()) + " < " + sdf.format(now));
}
if (notBefore != null && nowUnixSeconds < notBefore.getTime()) {
logger.log(Level.getLevel("oauth"), "Token can not be used before: " + claimsSet.getNotBeforeTime());
return new ClientAuthorization("invalid_grant", "Token can not be used before: " + claimsSet.getNotBeforeTime());
}
Credentials cred = null;
try {
cred = getEndpointCredentials(uid);
logger.log(Level.getLevel("oauth"), "Endpoint credentials: " + cred);
} catch (SEPASecurityException e) {
logger.log(Level.getLevel("oauth"), "Failed to retrieve credentials (" + uid + ")");
return new ClientAuthorization("invalid_grant", "Failed to get credentials (" + uid + ")");
}
return new ClientAuthorization(cred);
}
use of com.nimbusds.jwt.SignedJWT in project SEPA by arces-wot.
the class LdapSecurityManager method getTokenExpiringDate.
@Override
public Date getTokenExpiringDate(String uid) throws SEPASecurityException {
logger.log(Level.getLevel("ldap"), "[LDAP] getTokenExpiringDate " + uid + " uid=" + uid + ",ou=tokens," + prop.getBase(), "(objectclass=*)");
bind();
try {
cursor = ldap.search("uid=" + uid + ",ou=tokens," + prop.getBase(), "(objectclass=*)", SearchScope.OBJECT, "*");
if (!cursor.next())
throw new SEPASecurityException("uid=" + uid + ",ou=tokens," + prop.getBase() + " NOT FOUND");
SignedJWT jwt = SignedJWT.parse(cursor.get().get("javaSerializedData").getString());
return jwt.getJWTClaimsSet().getExpirationTime();
} catch (LdapException | CursorException | ParseException e) {
logger.error("[LDAP] getTokenExpiringDate exception " + e.getMessage());
throw new SEPASecurityException("getTokenExpiringDate exception " + e.getMessage());
} finally {
unbind();
}
}
use of com.nimbusds.jwt.SignedJWT in project SEPA by arces-wot.
the class SecurityManagerTest method tokens.
// @Test
public void tokens() throws SEPASecurityException, KeyStoreException, NoSuchAlgorithmException, CertificateException, FileNotFoundException, ParseException, IOException, JOSEException {
String uid = UUID.randomUUID().toString();
DigitalIdentity device = new DeviceIdentity(uid);
auth.storeCredentials(device, uid);
SignedJWT token = generateToken(device, uid);
Date expirationDate = token.getJWTClaimsSet().getExpirationTime();
auth.addJwt(uid, token);
assertFalse("Failed to check token presence", !auth.containsJwt(uid));
assertFalse("Failed to get expiring period", auth.getTokenExpiringPeriod(uid) != auth.getDeviceExpiringPeriod());
assertFalse("Failed to get expiring date", !auth.getTokenExpiringDate(uid).equals(expirationDate));
SignedJWT stored = auth.getJwt(uid);
assertFalse("Token does not match", !stored.serialize().equals(token.serialize()));
auth.setTokenExpiringPeriod(uid, 0);
assertFalse("Failed to set expiring period", auth.getTokenExpiringPeriod(uid) != 0);
}
use of com.nimbusds.jwt.SignedJWT in project Payara by payara.
the class GCPSecretsConfigSource method buildJwt.
// Helpers
private static SignedJWT buildJwt(final String issuer, final String scope) {
Instant now = Instant.now();
Instant expiry = now.plus(1, ChronoUnit.MINUTES);
JWTClaimsSet claims = new JWTClaimsSet.Builder().issuer(issuer).audience(AUTH_URL).issueTime(Date.from(now)).expirationTime(Date.from(expiry)).claim("scope", scope).build();
JWSHeader header = new JWSHeader.Builder(JWSAlgorithm.RS256).type(JOSEObjectType.JWT).build();
return new SignedJWT(header, claims);
}
use of com.nimbusds.jwt.SignedJWT in project cruise-control by linkedin.
the class JwtLoginService method login.
@Override
public UserIdentity login(String username, Object credentials, ServletRequest request) {
if (!(credentials instanceof SignedJWT)) {
return null;
}
if (!(request instanceof HttpServletRequest)) {
return null;
}
SignedJWT jwtToken = (SignedJWT) credentials;
JWTClaimsSet claimsSet;
boolean valid;
try {
claimsSet = jwtToken.getJWTClaimsSet();
valid = validateToken(jwtToken, claimsSet, username);
} catch (ParseException e) {
JWT_LOGGER.warn(String.format("%s: Couldn't parse a JWT token", username), e);
return null;
}
if (valid) {
String serializedToken = (String) request.getAttribute(JwtAuthenticator.JWT_TOKEN_REQUEST_ATTRIBUTE);
UserIdentity rolesDelegate = _authorizationService.getUserIdentity((HttpServletRequest) request, username);
if (rolesDelegate == null) {
return null;
} else {
return getUserIdentity(jwtToken, claimsSet, serializedToken, username, rolesDelegate);
}
} else {
return null;
}
}
Aggregations