use of org.keycloak.services.managers.Auth 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));
}
use of org.keycloak.services.managers.Auth in project keycloak by keycloak.
the class AccountFormService method processFederatedIdentityUpdate.
@Path("identity")
@POST
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Response processFederatedIdentityUpdate() {
MultivaluedMap<String, String> formData = request.getDecodedFormParameters();
if (auth == null) {
return login("identity");
}
auth.require(AccountRoles.MANAGE_ACCOUNT);
csrfCheck(formData);
UserModel user = auth.getUser();
String action = formData.getFirst("action");
String providerId = formData.getFirst("providerId");
if (Validation.isEmpty(providerId)) {
setReferrerOnPage();
return account.setError(Status.OK, Messages.MISSING_IDENTITY_PROVIDER).createResponse(AccountPages.FEDERATED_IDENTITY);
}
AccountSocialAction accountSocialAction = AccountSocialAction.getAction(action);
if (accountSocialAction == null) {
setReferrerOnPage();
return account.setError(Status.OK, Messages.INVALID_FEDERATED_IDENTITY_ACTION).createResponse(AccountPages.FEDERATED_IDENTITY);
}
if (!realm.getIdentityProvidersStream().anyMatch(model -> Objects.equals(model.getAlias(), providerId))) {
setReferrerOnPage();
return account.setError(Status.OK, Messages.IDENTITY_PROVIDER_NOT_FOUND).createResponse(AccountPages.FEDERATED_IDENTITY);
}
if (!user.isEnabled()) {
setReferrerOnPage();
return account.setError(Status.OK, Messages.ACCOUNT_DISABLED).createResponse(AccountPages.FEDERATED_IDENTITY);
}
switch(accountSocialAction) {
case ADD:
String redirectUri = UriBuilder.fromUri(Urls.accountFederatedIdentityPage(session.getContext().getUri().getBaseUri(), realm.getName())).build().toString();
try {
String nonce = UUID.randomUUID().toString();
MessageDigest md = MessageDigest.getInstance("SHA-256");
String input = nonce + auth.getSession().getId() + client.getClientId() + providerId;
byte[] check = md.digest(input.getBytes(StandardCharsets.UTF_8));
String hash = Base64Url.encode(check);
URI linkUrl = Urls.identityProviderLinkRequest(this.session.getContext().getUri().getBaseUri(), providerId, realm.getName());
linkUrl = UriBuilder.fromUri(linkUrl).queryParam("nonce", nonce).queryParam("hash", hash).queryParam("client_id", client.getClientId()).queryParam("redirect_uri", redirectUri).build();
return Response.seeOther(linkUrl).build();
} catch (Exception spe) {
setReferrerOnPage();
return account.setError(Response.Status.INTERNAL_SERVER_ERROR, Messages.IDENTITY_PROVIDER_REDIRECT_ERROR).createResponse(AccountPages.FEDERATED_IDENTITY);
}
case REMOVE:
FederatedIdentityModel link = session.users().getFederatedIdentity(realm, user, providerId);
if (link != null) {
// Removing last social provider is not possible if you don't have other possibility to authenticate
if (session.users().getFederatedIdentitiesStream(realm, user).count() > 1 || user.getFederationLink() != null || isPasswordSet(session, realm, user)) {
session.users().removeFederatedIdentity(realm, user, providerId);
logger.debugv("Social provider {0} removed successfully from user {1}", providerId, user.getUsername());
event.event(EventType.REMOVE_FEDERATED_IDENTITY).client(auth.getClient()).user(auth.getUser()).detail(Details.USERNAME, auth.getUser().getUsername()).detail(Details.IDENTITY_PROVIDER, link.getIdentityProvider()).detail(Details.IDENTITY_PROVIDER_USERNAME, link.getUserName()).success();
setReferrerOnPage();
return account.setSuccess(Messages.IDENTITY_PROVIDER_REMOVED).createResponse(AccountPages.FEDERATED_IDENTITY);
} else {
setReferrerOnPage();
return account.setError(Status.OK, Messages.FEDERATED_IDENTITY_REMOVING_LAST_PROVIDER).createResponse(AccountPages.FEDERATED_IDENTITY);
}
} else {
setReferrerOnPage();
return account.setError(Status.OK, Messages.FEDERATED_IDENTITY_NOT_ACTIVE).createResponse(AccountPages.FEDERATED_IDENTITY);
}
default:
throw new IllegalArgumentException();
}
}
use of org.keycloak.services.managers.Auth in project keycloak by keycloak.
the class AccountLoader method getAccountRestService.
private AccountRestService getAccountRestService(ClientModel client, String versionStr) {
AuthenticationManager.AuthResult authResult = new AppAuthManager.BearerTokenAuthenticator(session).setAudience(client.getClientId()).authenticate();
if (authResult == null) {
throw new NotAuthorizedException("Bearer token required");
}
Auth auth = new Auth(session.getContext().getRealm(), authResult.getToken(), authResult.getUser(), client, authResult.getSession(), false);
Cors.add(request).allowedOrigins(auth.getToken()).allowedMethods("GET", "PUT", "POST", "DELETE").auth().build(response);
if (authResult.getUser().getServiceAccountClientLink() != null) {
throw new NotAuthorizedException("Service accounts are not allowed to access this service");
}
AccountRestApiVersion version;
if (versionStr == null) {
version = AccountRestApiVersion.DEFAULT;
} else {
version = AccountRestApiVersion.get(versionStr);
if (version == null) {
throw new NotFoundException("API version not found");
}
}
AccountRestService accountRestService = new AccountRestService(session, auth, client, event, version);
ResteasyProviderFactory.getInstance().injectProperties(accountRestService);
accountRestService.init();
return accountRestService;
}
use of org.keycloak.services.managers.Auth in project keycloak by keycloak.
the class AccountConsole method getMainPage.
@GET
@NoCache
public Response getMainPage() throws IOException, FreeMarkerException {
UriInfo uriInfo = session.getContext().getUri(UrlType.FRONTEND);
URI accountBaseUrl = uriInfo.getBaseUriBuilder().path(RealmsResource.class).path(realm.getName()).path(Constants.ACCOUNT_MANAGEMENT_CLIENT_ID).path("/").build(realm);
if (!session.getContext().getUri().getRequestUri().getPath().endsWith("/")) {
UriBuilder redirectUri = session.getContext().getUri().getRequestUriBuilder().uri(accountBaseUrl);
return Response.status(302).location(redirectUri.build()).build();
} else {
Map<String, Object> map = new HashMap<>();
URI adminBaseUri = session.getContext().getUri(UrlType.ADMIN).getBaseUri();
URI authUrl = uriInfo.getBaseUri();
map.put("authUrl", authUrl.getPath().endsWith("/") ? authUrl : authUrl + "/");
map.put("baseUrl", accountBaseUrl);
map.put("realm", realm);
map.put("resourceUrl", Urls.themeRoot(authUrl).getPath() + "/" + Constants.ACCOUNT_MANAGEMENT_CLIENT_ID + "/" + theme.getName());
map.put("resourceCommonUrl", Urls.themeRoot(adminBaseUri).getPath() + "/common/keycloak");
map.put("resourceVersion", Version.RESOURCES_VERSION);
String[] referrer = getReferrer();
if (referrer != null) {
map.put("referrer", referrer[0]);
map.put("referrerName", referrer[1]);
map.put("referrer_uri", referrer[2]);
}
UserModel user = null;
if (auth != null)
user = auth.getUser();
Locale locale = session.getContext().resolveLocale(user);
map.put("locale", locale.toLanguageTag());
Properties messages = theme.getMessages(locale);
messages.putAll(realm.getRealmLocalizationTextsByLocale(locale.toLanguageTag()));
map.put("msg", new MessageFormatterMethod(locale, messages));
map.put("msgJSON", messagesToJsonString(messages));
map.put("supportedLocales", supportedLocales(messages));
map.put("properties", theme.getProperties());
map.put("theme", (Function<String, String>) file -> {
try {
final InputStream resource = theme.getResourceAsStream(file);
return new Scanner(resource, "UTF-8").useDelimiter("\\A").next();
} catch (IOException e) {
throw new RuntimeException("could not load file", e);
}
});
EventStoreProvider eventStore = session.getProvider(EventStoreProvider.class);
map.put("isEventsEnabled", eventStore != null && realm.isEventsEnabled());
map.put("isAuthorizationEnabled", Profile.isFeatureEnabled(Profile.Feature.AUTHORIZATION));
boolean isTotpConfigured = false;
boolean deleteAccountAllowed = false;
if (user != null) {
isTotpConfigured = session.userCredentialManager().isConfiguredFor(realm, user, realm.getOTPPolicy().getType());
RoleModel deleteAccountRole = realm.getClientByClientId(Constants.ACCOUNT_MANAGEMENT_CLIENT_ID).getRole(AccountRoles.DELETE_ACCOUNT);
deleteAccountAllowed = deleteAccountRole != null && user.hasRole(deleteAccountRole) && realm.getRequiredActionProviderByAlias(DeleteAccount.PROVIDER_ID).isEnabled();
}
map.put("isTotpConfigured", isTotpConfigured);
map.put("deleteAccountAllowed", deleteAccountAllowed);
FreeMarkerUtil freeMarkerUtil = new FreeMarkerUtil();
String result = freeMarkerUtil.processTemplate(map, "index.ftl", theme);
Response.ResponseBuilder builder = Response.status(Response.Status.OK).type(MediaType.TEXT_HTML_UTF_8).language(Locale.ENGLISH).entity(result);
return builder.build();
}
}
Aggregations