Search in sources :

Example 1 with ForbiddenException

use of org.keycloak.services.ForbiddenException in project keycloak by keycloak.

the class QuarkusWelcomeResource method csrfCheck.

private void csrfCheck(final MultivaluedMap<String, String> formData) {
    String formStateChecker = formData.getFirst("stateChecker");
    Cookie cookie = headers.getCookies().get(KEYCLOAK_STATE_CHECKER);
    if (cookie == null) {
        throw new ForbiddenException();
    }
    String cookieStateChecker = cookie.getValue();
    if (cookieStateChecker == null || !cookieStateChecker.equals(formStateChecker)) {
        throw new ForbiddenException();
    }
}
Also used : Cookie(javax.ws.rs.core.Cookie) ForbiddenException(org.keycloak.services.ForbiddenException)

Example 2 with ForbiddenException

use of org.keycloak.services.ForbiddenException in project keycloak by keycloak.

the class UserResource method removeCredential.

/**
 * Remove a credential for a user
 */
@Path("credentials/{credentialId}")
@DELETE
@NoCache
public void removeCredential(@PathParam("credentialId") final String credentialId) {
    auth.users().requireManage(user);
    CredentialModel credential = session.userCredentialManager().getStoredCredentialById(realm, user, credentialId);
    if (credential == null) {
        // we do this to make sure somebody can't phish ids
        if (auth.users().canQuery())
            throw new NotFoundException("Credential not found");
        else
            throw new ForbiddenException();
    }
    session.userCredentialManager().removeStoredCredential(realm, user, credentialId);
    adminEvent.operation(OperationType.ACTION).resourcePath(session.getContext().getUri()).success();
}
Also used : ForbiddenException(org.keycloak.services.ForbiddenException) UserCredentialModel(org.keycloak.models.UserCredentialModel) CredentialModel(org.keycloak.credential.CredentialModel) NotFoundException(javax.ws.rs.NotFoundException) Path(javax.ws.rs.Path) DELETE(javax.ws.rs.DELETE) NoCache(org.jboss.resteasy.annotations.cache.NoCache)

Example 3 with ForbiddenException

use of org.keycloak.services.ForbiddenException in project keycloak by keycloak.

the class UsersResource method createUser.

/**
 * Create a new user
 *
 * Username must be unique.
 *
 * @param rep
 * @return
 */
@POST
@Consumes(MediaType.APPLICATION_JSON)
public Response createUser(final UserRepresentation rep) {
    // first check if user has manage rights
    try {
        auth.users().requireManage();
    } catch (ForbiddenException exception) {
        if (!canCreateGroupMembers(rep)) {
            throw exception;
        }
    }
    String username = rep.getUsername();
    if (realm.isRegistrationEmailAsUsername()) {
        username = rep.getEmail();
    }
    if (ObjectUtil.isBlank(username)) {
        return ErrorResponse.error("User name is missing", Response.Status.BAD_REQUEST);
    }
    // Double-check duplicated username and email here due to federation
    if (session.users().getUserByUsername(realm, username) != null) {
        return ErrorResponse.exists("User exists with same username");
    }
    if (rep.getEmail() != null && !realm.isDuplicateEmailsAllowed()) {
        try {
            if (session.users().getUserByEmail(realm, rep.getEmail()) != null) {
                return ErrorResponse.exists("User exists with same email");
            }
        } catch (ModelDuplicateException e) {
            return ErrorResponse.exists("User exists with same email");
        }
    }
    UserProfileProvider profileProvider = session.getProvider(UserProfileProvider.class);
    UserProfile profile = profileProvider.create(USER_API, rep.toAttributes());
    try {
        Response response = UserResource.validateUserProfile(profile, null, session);
        if (response != null) {
            return response;
        }
        UserModel user = profile.create();
        UserResource.updateUserFromRep(profile, user, rep, session, false);
        RepresentationToModel.createFederatedIdentities(rep, session, realm, user);
        RepresentationToModel.createGroups(rep, realm, user);
        RepresentationToModel.createCredentials(rep, session, realm, user, true);
        adminEvent.operation(OperationType.CREATE).resourcePath(session.getContext().getUri(), user.getId()).representation(rep).success();
        if (session.getTransactionManager().isActive()) {
            session.getTransactionManager().commit();
        }
        return Response.created(session.getContext().getUri().getAbsolutePathBuilder().path(user.getId()).build()).build();
    } catch (ModelDuplicateException e) {
        if (session.getTransactionManager().isActive()) {
            session.getTransactionManager().setRollbackOnly();
        }
        return ErrorResponse.exists("User exists with same username or email");
    } catch (PasswordPolicyNotMetException e) {
        if (session.getTransactionManager().isActive()) {
            session.getTransactionManager().setRollbackOnly();
        }
        return ErrorResponse.error("Password policy not met", Response.Status.BAD_REQUEST);
    } catch (ModelException me) {
        if (session.getTransactionManager().isActive()) {
            session.getTransactionManager().setRollbackOnly();
        }
        logger.warn("Could not create user", me);
        return ErrorResponse.error("Could not create user", Response.Status.BAD_REQUEST);
    }
}
Also used : Response(javax.ws.rs.core.Response) ErrorResponse(org.keycloak.services.ErrorResponse) UserModel(org.keycloak.models.UserModel) ForbiddenException(org.keycloak.services.ForbiddenException) UserProfile(org.keycloak.userprofile.UserProfile) ModelException(org.keycloak.models.ModelException) UserProfileProvider(org.keycloak.userprofile.UserProfileProvider) ModelDuplicateException(org.keycloak.models.ModelDuplicateException) PasswordPolicyNotMetException(org.keycloak.policy.PasswordPolicyNotMetException) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes)

Example 4 with ForbiddenException

use of org.keycloak.services.ForbiddenException in project keycloak by keycloak.

the class AccountFormService method forwardToPage.

private Response forwardToPage(String path, AccountPages page) {
    if (auth != null) {
        try {
            auth.require(AccountRoles.MANAGE_ACCOUNT);
        } catch (ForbiddenException e) {
            return session.getProvider(LoginFormsProvider.class).setError(Messages.NO_ACCESS).createErrorPage(Response.Status.FORBIDDEN);
        }
        setReferrerOnPage();
        UserSessionModel userSession = auth.getSession();
        String tabId = session.getContext().getUri().getQueryParameters().getFirst(org.keycloak.models.Constants.TAB_ID);
        if (tabId != null) {
            AuthenticationSessionModel authSession = new AuthenticationSessionManager(session).getAuthenticationSessionByIdAndClient(realm, userSession.getId(), client, tabId);
            if (authSession != null) {
                String forwardedError = authSession.getAuthNote(ACCOUNT_MGMT_FORWARDED_ERROR_NOTE);
                if (forwardedError != null) {
                    try {
                        FormMessage errorMessage = JsonSerialization.readValue(forwardedError, FormMessage.class);
                        account.setError(Response.Status.INTERNAL_SERVER_ERROR, errorMessage.getMessage(), errorMessage.getParameters());
                        authSession.removeAuthNote(ACCOUNT_MGMT_FORWARDED_ERROR_NOTE);
                    } catch (IOException ioe) {
                        throw new RuntimeException(ioe);
                    }
                }
            }
        }
        String locale = session.getContext().getUri().getQueryParameters().getFirst(LocaleSelectorProvider.KC_LOCALE_PARAM);
        if (locale != null) {
            LocaleUpdaterProvider updater = session.getProvider(LocaleUpdaterProvider.class);
            updater.updateUsersLocale(auth.getUser(), locale);
        }
        return account.createResponse(page);
    } else {
        return login(path);
    }
}
Also used : AuthenticationSessionManager(org.keycloak.services.managers.AuthenticationSessionManager) ForbiddenException(org.keycloak.services.ForbiddenException) LoginFormsProvider(org.keycloak.forms.login.LoginFormsProvider) UserSessionModel(org.keycloak.models.UserSessionModel) AuthenticationSessionModel(org.keycloak.sessions.AuthenticationSessionModel) LocaleUpdaterProvider(org.keycloak.locale.LocaleUpdaterProvider) IOException(java.io.IOException) FormMessage(org.keycloak.models.utils.FormMessage)

Example 5 with ForbiddenException

use of org.keycloak.services.ForbiddenException in project keycloak by keycloak.

the class AccountFormService method init.

public void init() {
    eventStore = session.getProvider(EventStoreProvider.class);
    account = session.getProvider(AccountProvider.class).setRealm(realm).setUriInfo(session.getContext().getUri()).setHttpHeaders(headers);
    AuthenticationManager.AuthResult authResult = authManager.authenticateIdentityCookie(session, realm);
    if (authResult != null) {
        stateChecker = (String) session.getAttribute("state_checker");
        auth = new Auth(realm, authResult.getToken(), authResult.getUser(), client, authResult.getSession(), true);
        account.setStateChecker(stateChecker);
    }
    String requestOrigin = UriUtils.getOrigin(session.getContext().getUri().getBaseUri());
    String origin = headers.getRequestHeaders().getFirst("Origin");
    if (origin != null && !origin.equals("null") && !requestOrigin.equals(origin)) {
        throw new ForbiddenException();
    }
    if (!request.getHttpMethod().equals("GET")) {
        String referrer = headers.getRequestHeaders().getFirst("Referer");
        if (referrer != null && !requestOrigin.equals(UriUtils.getOrigin(referrer))) {
            throw new ForbiddenException();
        }
    }
    if (authResult != null) {
        UserSessionModel userSession = authResult.getSession();
        if (userSession != null) {
            AuthenticatedClientSessionModel clientSession = userSession.getAuthenticatedClientSessionByClient(client.getId());
            if (clientSession == null) {
                clientSession = session.sessions().createClientSession(userSession.getRealm(), client, userSession);
            }
            auth.setClientSession(clientSession);
        }
        account.setUser(auth.getUser());
    }
    account.setFeatures(realm.isIdentityFederationEnabled(), eventStore != null && realm.isEventsEnabled(), true, Profile.isFeatureEnabled(Profile.Feature.AUTHORIZATION));
}
Also used : AuthenticationManager(org.keycloak.services.managers.AuthenticationManager) ForbiddenException(org.keycloak.services.ForbiddenException) UserSessionModel(org.keycloak.models.UserSessionModel) Auth(org.keycloak.services.managers.Auth) AuthenticatedClientSessionModel(org.keycloak.models.AuthenticatedClientSessionModel) EventStoreProvider(org.keycloak.events.EventStoreProvider)

Aggregations

ForbiddenException (org.keycloak.services.ForbiddenException)17 Path (javax.ws.rs.Path)9 NotFoundException (javax.ws.rs.NotFoundException)7 POST (javax.ws.rs.POST)4 ClientModel (org.keycloak.models.ClientModel)4 Consumes (javax.ws.rs.Consumes)3 CredentialModel (org.keycloak.credential.CredentialModel)3 UserCredentialModel (org.keycloak.models.UserCredentialModel)3 UserModel (org.keycloak.models.UserModel)3 NotAuthorizedException (javax.ws.rs.NotAuthorizedException)2 PUT (javax.ws.rs.PUT)2 Produces (javax.ws.rs.Produces)2 Cookie (javax.ws.rs.core.Cookie)2 Response (javax.ws.rs.core.Response)2 ModelDuplicateException (org.keycloak.models.ModelDuplicateException)2 ModelException (org.keycloak.models.ModelException)2 RealmModel (org.keycloak.models.RealmModel)2 UserSessionModel (org.keycloak.models.UserSessionModel)2 ErrorResponse (org.keycloak.services.ErrorResponse)2 RealmManager (org.keycloak.services.managers.RealmManager)2