use of org.keycloak.common.VerificationException in project keycloak by keycloak.
the class RSAVerifierTest method testNotBeforeGood.
@Test
public void testNotBeforeGood() throws Exception {
token.notBefore(Time.currentTime() - 100);
String encoded = new JWSBuilder().jsonContent(token).rsa256(idpPair.getPrivate());
AccessToken v = null;
try {
v = verifySkeletonKeyToken(encoded);
} catch (VerificationException ignored) {
throw ignored;
}
}
use of org.keycloak.common.VerificationException in project keycloak by keycloak.
the class ServerECDSASignatureVerifierContext method verify.
@Override
public boolean verify(byte[] data, byte[] signature) throws VerificationException {
try {
/*
Fallback for backwards compatibility of ECDSA signed tokens which were issued in previous versions.
TODO remove by https://issues.jboss.org/browse/KEYCLOAK-11911
*/
int expectedSize = ECDSASignatureProvider.ECDSA.valueOf(getAlgorithm()).getSignatureLength();
byte[] derSignature = expectedSize != signature.length && signature[0] == 0x30 ? signature : ECDSASignatureProvider.concatenatedRSToASN1DER(signature, expectedSize);
return super.verify(data, derSignature);
} catch (Exception e) {
throw new VerificationException("Signing failed", e);
}
}
use of org.keycloak.common.VerificationException in project keycloak by keycloak.
the class ClientECDSASignatureVerifierContext method verify.
@Override
public boolean verify(byte[] data, byte[] signature) throws VerificationException {
try {
/*
Fallback for backwards compatibility of ECDSA signed tokens which were issued in previous versions.
TODO remove by https://issues.jboss.org/browse/KEYCLOAK-11911
*/
int expectedSize = ECDSASignatureProvider.ECDSA.valueOf(getAlgorithm()).getSignatureLength();
byte[] derSignature = expectedSize != signature.length && signature[0] == 0x30 ? signature : ECDSASignatureProvider.concatenatedRSToASN1DER(signature, expectedSize);
return super.verify(data, derSignature);
} catch (Exception e) {
throw new VerificationException("Signing failed", e);
}
}
use of org.keycloak.common.VerificationException in project keycloak by keycloak.
the class AuthenticationManager method verifyIdentityToken.
public static AuthResult verifyIdentityToken(KeycloakSession session, RealmModel realm, UriInfo uriInfo, ClientConnection connection, boolean checkActive, boolean checkTokenType, String checkAudience, boolean isCookie, String tokenString, HttpHeaders headers, Predicate<? super AccessToken>... additionalChecks) {
try {
TokenVerifier<AccessToken> verifier = TokenVerifier.create(tokenString, AccessToken.class).withDefaultChecks().realmUrl(Urls.realmIssuer(uriInfo.getBaseUri(), realm.getName())).checkActive(checkActive).checkTokenType(checkTokenType).withChecks(additionalChecks);
if (checkAudience != null) {
verifier.audience(checkAudience);
}
// Check token revocation in case of access token
if (checkTokenType) {
verifier.withChecks(new TokenManager.TokenRevocationCheck(session));
}
String kid = verifier.getHeader().getKeyId();
String algorithm = verifier.getHeader().getAlgorithm().name();
SignatureVerifierContext signatureVerifier = session.getProvider(SignatureProvider.class, algorithm).verifier(kid);
verifier.verifierContext(signatureVerifier);
AccessToken token = verifier.verify().getToken();
if (checkActive) {
if (!token.isActive() || token.getIssuedAt() < realm.getNotBefore()) {
logger.debug("Identity cookie expired");
return null;
}
}
UserSessionModel userSession = null;
UserModel user = null;
if (token.getSessionState() == null) {
user = TokenManager.lookupUserFromStatelessToken(session, realm, token);
if (!isUserValid(session, realm, user, token)) {
return null;
}
} else {
userSession = session.sessions().getUserSession(realm, token.getSessionState());
if (userSession != null) {
user = userSession.getUser();
if (!isUserValid(session, realm, user, token)) {
return null;
}
}
}
if (token.getSessionState() != null && !isSessionValid(realm, userSession)) {
// Check if accessToken was for the offline session.
if (!isCookie) {
UserSessionModel offlineUserSession = session.sessions().getOfflineUserSession(realm, token.getSessionState());
if (isOfflineSessionValid(realm, offlineUserSession)) {
user = offlineUserSession.getUser();
ClientModel client = realm.getClientByClientId(token.getIssuedFor());
if (!isClientValid(offlineUserSession, client, token)) {
return null;
}
return new AuthResult(user, offlineUserSession, token, client);
}
}
if (userSession != null)
backchannelLogout(session, realm, userSession, uriInfo, connection, headers, true);
logger.debug("User session not active");
return null;
}
session.setAttribute("state_checker", token.getOtherClaims().get("state_checker"));
ClientModel client;
if (isCookie) {
client = null;
} else {
client = realm.getClientByClientId(token.getIssuedFor());
if (!isClientValid(userSession, client, token)) {
return null;
}
}
return new AuthResult(user, userSession, token, client);
} catch (VerificationException e) {
logger.debugf("Failed to verify identity token: %s", e.getMessage());
}
return null;
}
use of org.keycloak.common.VerificationException in project keycloak by keycloak.
the class LogoutEndpoint method logout.
/**
* Logout user session. User must be logged in via a session cookie.
*
* When the logout is initiated by a remote idp, the parameter "initiating_idp" can be supplied. This param will
* prevent upstream logout (since the logout procedure has already been started in the remote idp).
*
* @param redirectUri
* @param initiatingIdp The alias of the idp initiating the logout.
* @return
*/
@GET
@NoCache
public // deprecated
Response logout(// deprecated
@QueryParam(OIDCLoginProtocol.REDIRECT_URI_PARAM) String redirectUri, @QueryParam("id_token_hint") String encodedIdToken, @QueryParam("post_logout_redirect_uri") String postLogoutRedirectUri, @QueryParam("state") String state, @QueryParam("initiating_idp") String initiatingIdp) {
String redirect = postLogoutRedirectUri != null ? postLogoutRedirectUri : redirectUri;
IDToken idToken = null;
if (encodedIdToken != null) {
try {
idToken = tokenManager.verifyIDTokenSignature(session, encodedIdToken);
TokenVerifier.createWithoutSignature(idToken).tokenType(TokenUtil.TOKEN_TYPE_ID).verify();
} catch (OAuthErrorException | VerificationException e) {
event.event(EventType.LOGOUT);
event.error(Errors.INVALID_TOKEN);
return ErrorPage.error(session, null, Response.Status.BAD_REQUEST, Messages.SESSION_NOT_ACTIVE);
}
}
if (redirect != null) {
String validatedUri;
ClientModel client = (idToken == null || idToken.getIssuedFor() == null) ? null : realm.getClientByClientId(idToken.getIssuedFor());
if (client != null) {
validatedUri = RedirectUtils.verifyRedirectUri(session, redirect, client);
} else {
validatedUri = RedirectUtils.verifyRealmRedirectUri(session, redirect);
}
if (validatedUri == null) {
event.event(EventType.LOGOUT);
event.detail(Details.REDIRECT_URI, redirect);
event.error(Errors.INVALID_REDIRECT_URI);
return ErrorPage.error(session, null, Response.Status.BAD_REQUEST, Messages.INVALID_REDIRECT_URI);
}
redirect = validatedUri;
}
UserSessionModel userSession = null;
if (idToken != null) {
try {
userSession = session.sessions().getUserSession(realm, idToken.getSessionState());
if (userSession != null) {
checkTokenIssuedAt(idToken, userSession);
}
} catch (OAuthErrorException e) {
event.event(EventType.LOGOUT);
event.error(Errors.INVALID_TOKEN);
return ErrorPage.error(session, null, Response.Status.BAD_REQUEST, Messages.SESSION_NOT_ACTIVE);
}
}
// authenticate identity cookie, but ignore an access token timeout as we're logging out anyways.
AuthenticationManager.AuthResult authResult = AuthenticationManager.authenticateIdentityCookie(session, realm, false);
if (authResult != null) {
userSession = userSession != null ? userSession : authResult.getSession();
return initiateBrowserLogout(userSession, redirect, state, initiatingIdp);
} else if (userSession != null) {
// identity cookie is missing but there's valid id_token_hint which matches session cookie => continue with browser logout
if (idToken != null && idToken.getSessionState().equals(AuthenticationManager.getSessionIdFromSessionCookie(session))) {
return initiateBrowserLogout(userSession, redirect, state, initiatingIdp);
}
// this might happen when a backChannelLogout is already initiated from AuthenticationManager.authenticateIdentityCookie
if (userSession.getState() != LOGGING_OUT && userSession.getState() != LOGGED_OUT) {
// non browser logout
event.event(EventType.LOGOUT);
AuthenticationManager.backchannelLogout(session, realm, userSession, session.getContext().getUri(), clientConnection, headers, true);
event.user(userSession.getUser()).session(userSession).success();
}
}
if (redirect != null) {
UriBuilder uriBuilder = UriBuilder.fromUri(redirect);
if (state != null)
uriBuilder.queryParam(OIDCLoginProtocol.STATE_PARAM, state);
return Response.status(302).location(uriBuilder.build()).build();
} else {
// TODO Empty content with ok makes no sense. Should it display a page? Or use noContent?
session.getProvider(SecurityHeadersProvider.class).options().allowEmptyContentType();
return Response.ok().build();
}
}
Aggregations