use of org.keycloak.jose.jws.JWSInputException in project keycloak by keycloak.
the class AdminRoot method authenticateRealmAdminRequest.
protected AdminAuth authenticateRealmAdminRequest(HttpHeaders headers) {
String tokenString = AppAuthManager.extractAuthorizationHeaderToken(headers);
if (tokenString == null)
throw new NotAuthorizedException("Bearer");
AccessToken token;
try {
JWSInput input = new JWSInput(tokenString);
token = input.readJsonContent(AccessToken.class);
} catch (JWSInputException e) {
throw new NotAuthorizedException("Bearer token format error");
}
String realmName = token.getIssuer().substring(token.getIssuer().lastIndexOf('/') + 1);
RealmManager realmManager = new RealmManager(session);
RealmModel realm = realmManager.getRealmByName(realmName);
if (realm == null) {
throw new NotAuthorizedException("Unknown realm in token");
}
session.getContext().setRealm(realm);
AuthenticationManager.AuthResult authResult = new AppAuthManager.BearerTokenAuthenticator(session).setRealm(realm).setConnection(clientConnection).setHeaders(headers).authenticate();
if (authResult == null) {
logger.debug("Token not valid");
throw new NotAuthorizedException("Bearer");
}
return new AdminAuth(realm, authResult.getToken(), authResult.getUser(), authResult.getClient());
}
use of org.keycloak.jose.jws.JWSInputException in project keycloak by keycloak.
the class BearerTokenRequestAuthenticator method authenticateToken.
protected AuthOutcome authenticateToken(HttpFacade exchange, String tokenString) {
log.debug("Verifying access_token");
if (log.isTraceEnabled()) {
try {
JWSInput jwsInput = new JWSInput(tokenString);
String wireString = jwsInput.getWireString();
log.tracef("\taccess_token: %s", wireString.substring(0, wireString.lastIndexOf(".")) + ".signature");
} catch (JWSInputException e) {
log.errorf(e, "Failed to parse access_token: %s", tokenString);
}
}
try {
token = AdapterTokenVerifier.verifyToken(tokenString, deployment);
} catch (VerificationException e) {
log.debug("Failed to verify token");
challenge = challengeResponse(exchange, OIDCAuthenticationError.Reason.INVALID_TOKEN, "invalid_token", e.getMessage());
return AuthOutcome.FAILED;
}
if (token.getIssuedAt() < deployment.getNotBefore()) {
log.debug("Stale token");
challenge = challengeResponse(exchange, OIDCAuthenticationError.Reason.STALE_TOKEN, "invalid_token", "Stale token");
return AuthOutcome.FAILED;
}
boolean verifyCaller = false;
if (deployment.isUseResourceRoleMappings()) {
verifyCaller = token.isVerifyCaller(deployment.getResourceName());
} else {
verifyCaller = token.isVerifyCaller();
}
surrogate = null;
if (verifyCaller) {
if (token.getTrustedCertificates() == null || token.getTrustedCertificates().isEmpty()) {
log.warn("No trusted certificates in token");
challenge = clientCertChallenge();
return AuthOutcome.FAILED;
}
// for now, we just make sure Undertow did two-way SSL
// assume JBoss Web verifies the client cert
X509Certificate[] chain = new X509Certificate[0];
try {
chain = exchange.getCertificateChain();
} catch (Exception ignore) {
}
if (chain == null || chain.length == 0) {
log.warn("No certificates provided by undertow to verify the caller");
challenge = clientCertChallenge();
return AuthOutcome.FAILED;
}
surrogate = chain[0].getSubjectDN().getName();
}
log.debug("successful authorized");
return AuthOutcome.AUTHENTICATED;
}
use of org.keycloak.jose.jws.JWSInputException in project keycloak by keycloak.
the class OAuthRequestAuthenticator method logToken.
private void logToken(String name, String token) {
try {
JWSInput jwsInput = new JWSInput(token);
String wireString = jwsInput.getWireString();
log.tracef("\t%s: %s", name, wireString.substring(0, wireString.lastIndexOf(".")) + ".signature");
} catch (JWSInputException e) {
log.errorf(e, "Failed to parse %s: %s", name, token);
}
}
use of org.keycloak.jose.jws.JWSInputException in project keycloak by keycloak.
the class CookieTokenStore method getPrincipalFromCookie.
public static KeycloakPrincipal<RefreshableKeycloakSecurityContext> getPrincipalFromCookie(KeycloakDeployment deployment, HttpFacade facade, AdapterTokenStore tokenStore) {
OIDCHttpFacade.Cookie cookie = facade.getRequest().getCookie(AdapterConstants.KEYCLOAK_ADAPTER_STATE_COOKIE);
if (cookie == null) {
log.debug("Not found adapter state cookie in current request");
return null;
}
String cookieVal = cookie.getValue();
String[] tokens = cookieVal.split(DELIM);
if (tokens.length != 3) {
log.warnf("Invalid format of %s cookie. Count of tokens: %s, expected 3", AdapterConstants.KEYCLOAK_ADAPTER_STATE_COOKIE, tokens.length);
return null;
}
String accessTokenString = tokens[0];
String idTokenString = tokens[1];
String refreshTokenString = tokens[2];
try {
// Skip check if token is active now. It's supposed to be done later by the caller
TokenVerifier<AccessToken> tokenVerifier = AdapterTokenVerifier.createVerifier(accessTokenString, deployment, true, AccessToken.class).checkActive(false).verify();
AccessToken accessToken = tokenVerifier.getToken();
IDToken idToken;
if (idTokenString != null && idTokenString.length() > 0) {
try {
JWSInput input = new JWSInput(idTokenString);
idToken = input.readJsonContent(IDToken.class);
} catch (JWSInputException e) {
throw new VerificationException(e);
}
} else {
idToken = null;
}
log.debug("Token Verification succeeded!");
RefreshableKeycloakSecurityContext secContext = new RefreshableKeycloakSecurityContext(deployment, tokenStore, accessTokenString, accessToken, idTokenString, idToken, refreshTokenString);
return new KeycloakPrincipal<>(AdapterUtils.getPrincipalName(deployment, accessToken), secContext);
} catch (VerificationException ve) {
log.warn("Failed verify token", ve);
return null;
}
}
use of org.keycloak.jose.jws.JWSInputException in project keycloak by keycloak.
the class JOSEParser method parse.
/**
* Parses the given encoded {@code jwt} and returns either a {@link JWSInput} or {@link JWE}
* depending on the JOSE header configuration.
*
* @param jwt the encoded JWT
* @return a {@link JOSE}
*/
public static JOSE parse(String jwt) {
String[] parts = jwt.split("\\.");
if (parts.length == 0) {
throw new RuntimeException("Could not infer header from JWT");
}
JsonNode header;
try {
header = JsonSerialization.readValue(Base64Url.decode(parts[0]), JsonNode.class);
} catch (IOException cause) {
throw new RuntimeException("Failed to parse JWT header", cause);
}
if (header.has("enc")) {
return new JWE(jwt);
}
try {
return new JWSInput(jwt);
} catch (JWSInputException cause) {
throw new RuntimeException("Failed to build JWS", cause);
}
}
Aggregations