use of org.keycloak.representations.idm.OAuth2ErrorRepresentation in project keycloak by keycloak.
the class KeycloakErrorHandler method toResponse.
@Override
public Response toResponse(Throwable throwable) {
KeycloakSession session = Resteasy.getContextData(KeycloakSession.class);
KeycloakTransaction tx = session.getTransactionManager();
tx.setRollbackOnly();
int statusCode = getStatusCode(throwable);
if (statusCode >= 500 && statusCode <= 599) {
logger.error(UNCAUGHT_SERVER_ERROR_TEXT, throwable);
} else {
logger.debugv(throwable, ERROR_RESPONSE_TEXT, statusCode);
}
if (!MediaTypeMatcher.isHtmlRequest(headers)) {
OAuth2ErrorRepresentation error = new OAuth2ErrorRepresentation();
error.setError(getErrorCode(throwable));
return Response.status(statusCode).header(HttpHeaders.CONTENT_TYPE, javax.ws.rs.core.MediaType.APPLICATION_JSON_TYPE.toString()).entity(error).build();
}
try {
RealmModel realm = resolveRealm(session);
Theme theme = session.theme().getTheme(Theme.Type.LOGIN);
Locale locale = session.getContext().resolveLocale(null);
FreeMarkerUtil freeMarker = new FreeMarkerUtil();
Map<String, Object> attributes = initAttributes(session, realm, theme, locale, statusCode);
String templateName = "error.ftl";
String content = freeMarker.processTemplate(attributes, templateName, theme);
return Response.status(statusCode).type(MediaType.TEXT_HTML_UTF_8_TYPE).entity(content).build();
} catch (Throwable t) {
logger.error("Failed to create error page", t);
return Response.serverError().build();
}
}
use of org.keycloak.representations.idm.OAuth2ErrorRepresentation in project keycloak by keycloak.
the class ClientTest method createOrUpdateClientExpectingValidationErrors.
private void createOrUpdateClientExpectingValidationErrors(ClientRepresentation rep, boolean create, String... expectedErrors) {
Response response = null;
if (create) {
response = realm.clients().create(rep);
} else {
try {
realm.clients().get(rep.getId()).update(rep);
fail("Expected exception");
} catch (BadRequestException e) {
response = e.getResponse();
}
}
expectedErrors = Arrays.stream(expectedErrors).filter(Objects::nonNull).toArray(String[]::new);
assertEquals(response.getStatus(), 400);
OAuth2ErrorRepresentation errorRep = response.readEntity(OAuth2ErrorRepresentation.class);
List<String> actualErrors = asList(errorRep.getErrorDescription().split("; "));
assertThat(actualErrors, containsInAnyOrder(expectedErrors));
assertEquals("invalid_input", errorRep.getError());
}
use of org.keycloak.representations.idm.OAuth2ErrorRepresentation in project keycloak by keycloak.
the class TokenIntrospectionTest method testIntrospectionRequestParamsMoreThanOnce.
// KEYCLOAK-17259
@Test
public void testIntrospectionRequestParamsMoreThanOnce() throws Exception {
oauth.doLogin("test-user@localhost", "password");
String code = oauth.getCurrentQuery().get(OAuth2Constants.CODE);
AccessTokenResponse accessTokenResponse = oauth.doAccessTokenRequest(code, "password");
accessTokenResponse = oauth.doRefreshTokenRequest(accessTokenResponse.getRefreshToken(), "password");
String tokenResponse = introspectAccessTokenWithDuplicateParams("confidential-cli", "secret1", accessTokenResponse.getAccessToken());
OAuth2ErrorRepresentation errorRep = JsonSerialization.readValue(tokenResponse, OAuth2ErrorRepresentation.class);
assertEquals("duplicated parameter", errorRep.getErrorDescription());
assertEquals(OAuthErrorException.INVALID_REQUEST, errorRep.getError());
}
use of org.keycloak.representations.idm.OAuth2ErrorRepresentation in project keycloak by keycloak.
the class BackchannelAuthenticationEndpoint method authorizeClient.
private CIBAAuthenticationRequest authorizeClient(MultivaluedMap<String, String> params) {
ClientModel client = null;
try {
client = authenticateClient();
} catch (WebApplicationException wae) {
OAuth2ErrorRepresentation errorRep = (OAuth2ErrorRepresentation) wae.getResponse().getEntity();
throw new ErrorResponseException(errorRep.getError(), errorRep.getErrorDescription(), Response.Status.UNAUTHORIZED);
}
BackchannelAuthenticationEndpointRequest endpointRequest = BackchannelAuthenticationEndpointRequestParserProcessor.parseRequest(event, session, client, params, realm.getCibaPolicy());
UserModel user = resolveUser(endpointRequest, realm.getCibaPolicy().getAuthRequestedUserHint());
CIBAAuthenticationRequest request = new CIBAAuthenticationRequest(session, user, client);
request.setClient(client);
String scope = endpointRequest.getScope();
if (scope == null) {
throw new ErrorResponseException(OAuthErrorException.INVALID_REQUEST, "missing parameter : scope", Response.Status.BAD_REQUEST);
}
request.setScope(scope);
// optional parameters
if (endpointRequest.getBindingMessage() != null) {
validateBindingMessage(endpointRequest.getBindingMessage());
request.setBindingMessage(endpointRequest.getBindingMessage());
}
if (endpointRequest.getAcr() != null)
request.setAcrValues(endpointRequest.getAcr());
CibaConfig policy = realm.getCibaPolicy();
// create JWE encoded auth_req_id from Auth Req ID.
Integer expiresIn = Optional.ofNullable(endpointRequest.getRequestedExpiry()).orElse(policy.getExpiresIn());
request.exp(request.getIat() + expiresIn.longValue());
StringBuilder scopes = new StringBuilder(Optional.ofNullable(request.getScope()).orElse(""));
client.getClientScopes(true).forEach((key, value) -> {
if (value.isDisplayOnConsentScreen())
scopes.append(" ").append(value.getName());
});
request.setScope(scopes.toString());
if (endpointRequest.getClientNotificationToken() != null) {
if (!policy.getBackchannelTokenDeliveryMode(client).equals(CibaConfig.CIBA_PING_MODE)) {
throw new ErrorResponseException(OAuthErrorException.INVALID_REQUEST, "Client Notification token supported only for the ping mode", Response.Status.BAD_REQUEST);
}
if (endpointRequest.getClientNotificationToken().length() > 1024) {
throw new ErrorResponseException(OAuthErrorException.INVALID_REQUEST, "Client Notification token length is limited to 1024 characters", Response.Status.BAD_REQUEST);
}
request.setClientNotificationToken(endpointRequest.getClientNotificationToken());
}
if (endpointRequest.getClientNotificationToken() == null && policy.getBackchannelTokenDeliveryMode(client).equals(CibaConfig.CIBA_PING_MODE)) {
throw new ErrorResponseException(OAuthErrorException.INVALID_REQUEST, "Client Notification token needs to be provided with the ping mode", Response.Status.BAD_REQUEST);
}
if (endpointRequest.getUserCode() != null) {
throw new ErrorResponseException(OAuthErrorException.INVALID_REQUEST, "User code not supported", Response.Status.BAD_REQUEST);
}
extractAdditionalParams(endpointRequest, request);
try {
session.clientPolicy().triggerOnEvent(new BackchannelAuthenticationRequestContext(endpointRequest, request, params));
} catch (ClientPolicyException cpe) {
throw new ErrorResponseException(cpe.getError(), cpe.getErrorDetail(), Response.Status.BAD_REQUEST);
}
return request;
}
use of org.keycloak.representations.idm.OAuth2ErrorRepresentation in project keycloak by keycloak.
the class ResourcesRestServiceTest method testGetResource.
@Test
public void testGetResource() {
Resource resource = doGet("/" + getMyResources().get(0).getId(), Resource.class);
String uri = resource.getUri();
int id = Integer.parseInt(uri.substring(uri.lastIndexOf('/') + 1));
assertNotNull(resource.getId());
assertEquals("Resource " + id, resource.getName());
assertEquals("Display Name " + id, resource.getDisplayName());
assertEquals("Icon Uri " + id, resource.getIconUri());
assertEquals("my-resource-server", resource.getClient().getClientId());
assertEquals("My Resource Server", resource.getClient().getName());
assertEquals("http://resourceserver.com", resource.getClient().getBaseUrl());
assertEquals(4, resource.getScopes().size());
OAuth2ErrorRepresentation response = doGet("/invalid_resource", OAuth2ErrorRepresentation.class);
assertEquals("resource_not_found", response.getError());
response = doGet("/" + getMyResources().get(0).getId(), authzClient.obtainAccessToken("jdoe", "password").getToken(), OAuth2ErrorRepresentation.class);
assertEquals("invalid_resource", response.getError());
}
Aggregations