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();
}
}
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();
}
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);
}
}
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);
}
}
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));
}
Aggregations