Search in sources :

Example 1 with Auth

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

Example 2 with Auth

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();
    }
}
Also used : UserModel(org.keycloak.models.UserModel) RedirectUtils(org.keycloak.protocol.oidc.utils.RedirectUtils) Arrays(java.util.Arrays) Produces(javax.ws.rs.Produces) EventStoreProvider(org.keycloak.events.EventStoreProvider) Path(javax.ws.rs.Path) LocaleUpdaterProvider(org.keycloak.locale.LocaleUpdaterProvider) AuthenticationSessionManager(org.keycloak.services.managers.AuthenticationSessionManager) Messages(org.keycloak.services.messages.Messages) ResolveRelative(org.keycloak.services.util.ResolveRelative) MediaType(javax.ws.rs.core.MediaType) QueryParam(javax.ws.rs.QueryParam) FormMessage(org.keycloak.models.utils.FormMessage) AuthenticationManager(org.keycloak.services.managers.AuthenticationManager) Consumes(javax.ws.rs.Consumes) ReadOnlyException(org.keycloak.storage.ReadOnlyException) AuthenticatedClientSessionModel(org.keycloak.models.AuthenticatedClientSessionModel) Validation(org.keycloak.services.validation.Validation) AppAuthManager(org.keycloak.services.managers.AppAuthManager) Map(java.util.Map) Auth(org.keycloak.services.managers.Auth) UriBuilder(javax.ws.rs.core.UriBuilder) URI(java.net.URI) AuthorizationProvider(org.keycloak.authorization.AuthorizationProvider) Method(java.lang.reflect.Method) Time(org.keycloak.common.util.Time) CredentialValidation(org.keycloak.models.utils.CredentialValidation) UriUtils(org.keycloak.common.util.UriUtils) UserCredentialModel(org.keycloak.models.UserCredentialModel) AccountPages(org.keycloak.forms.account.AccountPages) AuthenticationSessionModel(org.keycloak.sessions.AuthenticationSessionModel) RealmModel(org.keycloak.models.RealmModel) Event(org.keycloak.events.Event) EnumMap(java.util.EnumMap) CredentialHelper(org.keycloak.utils.CredentialHelper) Set(java.util.Set) UUID(java.util.UUID) PolicyStore(org.keycloak.authorization.store.PolicyStore) Collectors(java.util.stream.Collectors) EventAuditingAttributeChangeListener(org.keycloak.userprofile.EventAuditingAttributeChangeListener) NotFoundException(javax.ws.rs.NotFoundException) StandardCharsets(java.nio.charset.StandardCharsets) Objects(java.util.Objects) List(java.util.List) Response(javax.ws.rs.core.Response) Details(org.keycloak.events.Details) PermissionTicketStore(org.keycloak.authorization.store.PermissionTicketStore) ForbiddenException(org.keycloak.services.ForbiddenException) UriInfo(javax.ws.rs.core.UriInfo) ClientModel(org.keycloak.models.ClientModel) UserProfile(org.keycloak.userprofile.UserProfile) Scope(org.keycloak.authorization.model.Scope) PathParam(javax.ws.rs.PathParam) RealmsResource(org.keycloak.services.resources.RealmsResource) Profile(org.keycloak.common.Profile) GET(javax.ws.rs.GET) MessageDigest(java.security.MessageDigest) Logger(org.jboss.logging.Logger) AbstractSecuredLocalService(org.keycloak.services.resources.AbstractSecuredLocalService) ServicesLogger(org.keycloak.services.ServicesLogger) PermissionTicket(org.keycloak.authorization.model.PermissionTicket) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) LocaleSelectorProvider(org.keycloak.locale.LocaleSelectorProvider) UserModel(org.keycloak.models.UserModel) EventBuilder(org.keycloak.events.EventBuilder) UserProfileProvider(org.keycloak.userprofile.UserProfileProvider) UserConsentManager(org.keycloak.services.managers.UserConsentManager) AccountProvider(org.keycloak.forms.account.AccountProvider) OTPPolicy(org.keycloak.models.OTPPolicy) Base64Url(org.keycloak.common.util.Base64Url) Status(javax.ws.rs.core.Response.Status) ResourceServer(org.keycloak.authorization.model.ResourceServer) FederatedIdentityModel(org.keycloak.models.FederatedIdentityModel) FormParam(javax.ws.rs.FormParam) Errors(org.keycloak.events.Errors) POST(javax.ws.rs.POST) Iterator(java.util.Iterator) KeycloakSession(org.keycloak.models.KeycloakSession) EventType(org.keycloak.events.EventType) IOException(java.io.IOException) UserSessionModel(org.keycloak.models.UserSessionModel) OTPCredentialModel(org.keycloak.models.credential.OTPCredentialModel) JsonSerialization(org.keycloak.util.JsonSerialization) MultivaluedMap(javax.ws.rs.core.MultivaluedMap) Policy(org.keycloak.authorization.model.Policy) AccountRoles(org.keycloak.models.AccountRoles) PasswordCredentialModel(org.keycloak.models.credential.PasswordCredentialModel) ModelException(org.keycloak.models.ModelException) UserProfileContext(org.keycloak.userprofile.UserProfileContext) Urls(org.keycloak.services.Urls) LoginFormsProvider(org.keycloak.forms.login.LoginFormsProvider) ValidationException(org.keycloak.userprofile.ValidationException) Resource(org.keycloak.authorization.model.Resource) ErrorResponse(org.keycloak.services.ErrorResponse) FederatedIdentityModel(org.keycloak.models.FederatedIdentityModel) MessageDigest(java.security.MessageDigest) URI(java.net.URI) ReadOnlyException(org.keycloak.storage.ReadOnlyException) NotFoundException(javax.ws.rs.NotFoundException) ForbiddenException(org.keycloak.services.ForbiddenException) IOException(java.io.IOException) ModelException(org.keycloak.models.ModelException) ValidationException(org.keycloak.userprofile.ValidationException) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes)

Example 3 with Auth

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;
}
Also used : AuthenticationManager(org.keycloak.services.managers.AuthenticationManager) Auth(org.keycloak.services.managers.Auth) AccountRestApiVersion(org.keycloak.common.enums.AccountRestApiVersion) NotFoundException(javax.ws.rs.NotFoundException) NotAuthorizedException(javax.ws.rs.NotAuthorizedException)

Example 4 with Auth

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();
    }
}
Also used : Locale(java.util.Locale) ClientModel(org.keycloak.models.ClientModel) Theme(org.keycloak.theme.Theme) RedirectUtils(org.keycloak.protocol.oidc.utils.RedirectUtils) RealmsResource(org.keycloak.services.resources.RealmsResource) Profile(org.keycloak.common.Profile) GET(javax.ws.rs.GET) Logger(org.jboss.logging.Logger) EventStoreProvider(org.keycloak.events.EventStoreProvider) Constants(org.keycloak.models.Constants) Path(javax.ws.rs.Path) Scanner(java.util.Scanner) HashMap(java.util.HashMap) Version(org.keycloak.common.Version) Function(java.util.function.Function) ResolveRelative(org.keycloak.services.util.ResolveRelative) UserModel(org.keycloak.models.UserModel) Matcher(java.util.regex.Matcher) AuthenticationManager(org.keycloak.services.managers.AuthenticationManager) Validation(org.keycloak.services.validation.Validation) Locale(java.util.Locale) AppAuthManager(org.keycloak.services.managers.AppAuthManager) Map(java.util.Map) Json(javax.json.Json) Auth(org.keycloak.services.managers.Auth) UriBuilder(javax.ws.rs.core.UriBuilder) URI(java.net.URI) UrlType(org.keycloak.urls.UrlType) RealmModel(org.keycloak.models.RealmModel) Context(javax.ws.rs.core.Context) Properties(java.util.Properties) KeycloakSession(org.keycloak.models.KeycloakSession) RoleModel(org.keycloak.models.RoleModel) IOException(java.io.IOException) DeleteAccount(org.keycloak.authentication.requiredactions.DeleteAccount) FreeMarkerUtil(org.keycloak.theme.FreeMarkerUtil) Collectors(java.util.stream.Collectors) MessageFormatterMethod(org.keycloak.theme.beans.MessageFormatterMethod) AccountRoles(org.keycloak.models.AccountRoles) MediaType(org.keycloak.utils.MediaType) NoCache(org.jboss.resteasy.annotations.cache.NoCache) Response(javax.ws.rs.core.Response) Urls(org.keycloak.services.Urls) Pattern(java.util.regex.Pattern) UriInfo(javax.ws.rs.core.UriInfo) FreeMarkerException(org.keycloak.theme.FreeMarkerException) JsonObjectBuilder(javax.json.JsonObjectBuilder) InputStream(java.io.InputStream) Scanner(java.util.Scanner) HashMap(java.util.HashMap) InputStream(java.io.InputStream) RoleModel(org.keycloak.models.RoleModel) IOException(java.io.IOException) Properties(java.util.Properties) URI(java.net.URI) UserModel(org.keycloak.models.UserModel) Response(javax.ws.rs.core.Response) FreeMarkerUtil(org.keycloak.theme.FreeMarkerUtil) UriBuilder(javax.ws.rs.core.UriBuilder) MessageFormatterMethod(org.keycloak.theme.beans.MessageFormatterMethod) UriInfo(javax.ws.rs.core.UriInfo) EventStoreProvider(org.keycloak.events.EventStoreProvider) GET(javax.ws.rs.GET) NoCache(org.jboss.resteasy.annotations.cache.NoCache)

Aggregations

Auth (org.keycloak.services.managers.Auth)4 AuthenticationManager (org.keycloak.services.managers.AuthenticationManager)4 EventStoreProvider (org.keycloak.events.EventStoreProvider)3 IOException (java.io.IOException)2 URI (java.net.URI)2 Map (java.util.Map)2 Collectors (java.util.stream.Collectors)2 GET (javax.ws.rs.GET)2 NotFoundException (javax.ws.rs.NotFoundException)2 Path (javax.ws.rs.Path)2 Response (javax.ws.rs.core.Response)2 UriBuilder (javax.ws.rs.core.UriBuilder)2 UriInfo (javax.ws.rs.core.UriInfo)2 Logger (org.jboss.logging.Logger)2 AuthenticatedClientSessionModel (org.keycloak.models.AuthenticatedClientSessionModel)2 UserSessionModel (org.keycloak.models.UserSessionModel)2 ForbiddenException (org.keycloak.services.ForbiddenException)2 InputStream (java.io.InputStream)1 Method (java.lang.reflect.Method)1 StandardCharsets (java.nio.charset.StandardCharsets)1