Search in sources :

Example 11 with OAuth2ErrorRepresentation

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();
    }
}
Also used : RealmModel(org.keycloak.models.RealmModel) Locale(java.util.Locale) FreeMarkerUtil(org.keycloak.theme.FreeMarkerUtil) KeycloakSession(org.keycloak.models.KeycloakSession) OAuth2ErrorRepresentation(org.keycloak.representations.idm.OAuth2ErrorRepresentation) Theme(org.keycloak.theme.Theme) KeycloakTransaction(org.keycloak.models.KeycloakTransaction)

Example 12 with OAuth2ErrorRepresentation

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());
}
Also used : AccessTokenResponse(org.keycloak.testsuite.util.OAuthClient.AccessTokenResponse) Response(javax.ws.rs.core.Response) Objects(java.util.Objects) BadRequestException(javax.ws.rs.BadRequestException) OAuth2ErrorRepresentation(org.keycloak.representations.idm.OAuth2ErrorRepresentation)

Example 13 with OAuth2ErrorRepresentation

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());
}
Also used : OAuth2ErrorRepresentation(org.keycloak.representations.idm.OAuth2ErrorRepresentation) AccessTokenResponse(org.keycloak.testsuite.util.OAuthClient.AccessTokenResponse) AbstractOIDCScopeTest(org.keycloak.testsuite.oidc.AbstractOIDCScopeTest) OIDCScopeTest(org.keycloak.testsuite.oidc.OIDCScopeTest) Test(org.junit.Test) AbstractTestRealmKeycloakTest(org.keycloak.testsuite.AbstractTestRealmKeycloakTest)

Example 14 with OAuth2ErrorRepresentation

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;
}
Also used : BackchannelAuthenticationRequestContext(org.keycloak.protocol.oidc.grants.ciba.clientpolicy.context.BackchannelAuthenticationRequestContext) WebApplicationException(javax.ws.rs.WebApplicationException) OAuth2ErrorRepresentation(org.keycloak.representations.idm.OAuth2ErrorRepresentation) CIBAAuthenticationRequest(org.keycloak.protocol.oidc.grants.ciba.channel.CIBAAuthenticationRequest) BackchannelAuthenticationEndpointRequest(org.keycloak.protocol.oidc.grants.ciba.endpoints.request.BackchannelAuthenticationEndpointRequest) ClientPolicyException(org.keycloak.services.clientpolicy.ClientPolicyException) UserModel(org.keycloak.models.UserModel) ClientModel(org.keycloak.models.ClientModel) CibaConfig(org.keycloak.models.CibaConfig) ErrorResponseException(org.keycloak.services.ErrorResponseException)

Example 15 with OAuth2ErrorRepresentation

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());
}
Also used : Resource(org.keycloak.services.resources.account.resources.AbstractResourceService.Resource) AuthorizationResource(org.keycloak.admin.client.resource.AuthorizationResource) ClientsResource(org.keycloak.admin.client.resource.ClientsResource) ClientResource(org.keycloak.admin.client.resource.ClientResource) OAuth2ErrorRepresentation(org.keycloak.representations.idm.OAuth2ErrorRepresentation) Test(org.junit.Test)

Aggregations

OAuth2ErrorRepresentation (org.keycloak.representations.idm.OAuth2ErrorRepresentation)17 Test (org.junit.Test)8 AccessTokenResponse (org.keycloak.testsuite.util.OAuthClient.AccessTokenResponse)5 IOException (java.io.IOException)4 HttpPost (org.apache.http.client.methods.HttpPost)4 CloseableHttpClient (org.apache.http.impl.client.CloseableHttpClient)3 AbstractKeycloakTest (org.keycloak.testsuite.AbstractKeycloakTest)3 InputStream (java.io.InputStream)2 ArrayList (java.util.ArrayList)2 Objects (java.util.Objects)2 Response (javax.ws.rs.core.Response)2 HttpEntity (org.apache.http.HttpEntity)2 HttpResponse (org.apache.http.HttpResponse)2 NameValuePair (org.apache.http.NameValuePair)2 HttpClient (org.apache.http.client.HttpClient)2 UrlEncodedFormEntity (org.apache.http.client.entity.UrlEncodedFormEntity)2 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)2 StringEntity (org.apache.http.entity.StringEntity)2 BasicNameValuePair (org.apache.http.message.BasicNameValuePair)2 BadRequestException (org.jboss.resteasy.spi.BadRequestException)2