Search in sources :

Example 21 with RealmManager

use of org.keycloak.services.managers.RealmManager in project keycloak by keycloak.

the class ClientResource method updateClientFromRep.

private void updateClientFromRep(ClientRepresentation rep, ClientModel client, KeycloakSession session) throws ModelDuplicateException {
    UserModel serviceAccount = this.session.users().getServiceAccount(client);
    if (TRUE.equals(rep.isServiceAccountsEnabled())) {
        if (serviceAccount == null) {
            new ClientManager(new RealmManager(session)).enableServiceAccount(client);
        }
    } else {
        if (serviceAccount != null) {
            new UserManager(session).removeUser(realm, serviceAccount);
        }
    }
    if (rep.getClientId() != null && !rep.getClientId().equals(client.getClientId())) {
        new ClientManager(new RealmManager(session)).clientIdChanged(client, rep);
    }
    if (rep.isFullScopeAllowed() != null && rep.isFullScopeAllowed() != client.isFullScopeAllowed()) {
        auth.clients().requireManage(client);
    }
    if ((rep.isBearerOnly() != null && rep.isBearerOnly()) || (rep.isPublicClient() != null && rep.isPublicClient())) {
        rep.setAuthorizationServicesEnabled(false);
    }
    RepresentationToModel.updateClient(rep, client);
    RepresentationToModel.updateClientProtocolMappers(rep, client);
    updateAuthorizationSettings(rep);
}
Also used : UserModel(org.keycloak.models.UserModel) UserManager(org.keycloak.models.UserManager) ClientManager(org.keycloak.services.managers.ClientManager) RealmManager(org.keycloak.services.managers.RealmManager)

Example 22 with RealmManager

use of org.keycloak.services.managers.RealmManager in project keycloak by keycloak.

the class ClientsResource method createClient.

/**
 * Create a new client
 *
 * Client's client_id must be unique!
 *
 * @param rep
 * @return
 */
@POST
@Consumes(MediaType.APPLICATION_JSON)
public Response createClient(final ClientRepresentation rep) {
    auth.clients().requireManage();
    try {
        session.clientPolicy().triggerOnEvent(new AdminClientRegisterContext(rep, auth.adminAuth()));
        ClientModel clientModel = ClientManager.createClient(session, realm, rep);
        if (TRUE.equals(rep.isServiceAccountsEnabled())) {
            UserModel serviceAccount = session.users().getServiceAccount(clientModel);
            if (serviceAccount == null) {
                new ClientManager(new RealmManager(session)).enableServiceAccount(clientModel);
            }
        }
        adminEvent.operation(OperationType.CREATE).resourcePath(session.getContext().getUri(), clientModel.getId()).representation(rep).success();
        if (Profile.isFeatureEnabled(Profile.Feature.AUTHORIZATION) && TRUE.equals(rep.getAuthorizationServicesEnabled())) {
            AuthorizationService authorizationService = getAuthorizationService(clientModel);
            authorizationService.enable(true);
            ResourceServerRepresentation authorizationSettings = rep.getAuthorizationSettings();
            if (authorizationSettings != null) {
                authorizationService.resourceServer().importSettings(authorizationSettings);
            }
        }
        ValidationUtil.validateClient(session, clientModel, true, r -> {
            session.getTransactionManager().setRollbackOnly();
            throw new ErrorResponseException(Errors.INVALID_INPUT, r.getAllLocalizedErrorsAsString(AdminRoot.getMessages(session, realm, auth.adminAuth().getToken().getLocale())), Response.Status.BAD_REQUEST);
        });
        session.clientPolicy().triggerOnEvent(new AdminClientRegisteredContext(clientModel, auth.adminAuth()));
        return Response.created(session.getContext().getUri().getAbsolutePathBuilder().path(clientModel.getId()).build()).build();
    } catch (ModelDuplicateException e) {
        return ErrorResponse.exists("Client " + rep.getClientId() + " already exists");
    } catch (ClientPolicyException cpe) {
        throw new ErrorResponseException(cpe.getError(), cpe.getErrorDetail(), Response.Status.BAD_REQUEST);
    }
}
Also used : UserModel(org.keycloak.models.UserModel) ClientModel(org.keycloak.models.ClientModel) AdminClientRegisteredContext(org.keycloak.services.clientpolicy.context.AdminClientRegisteredContext) AuthorizationService(org.keycloak.authorization.admin.AuthorizationService) ResourceServerRepresentation(org.keycloak.representations.idm.authorization.ResourceServerRepresentation) ClientManager(org.keycloak.services.managers.ClientManager) ModelDuplicateException(org.keycloak.models.ModelDuplicateException) ErrorResponseException(org.keycloak.services.ErrorResponseException) RealmManager(org.keycloak.services.managers.RealmManager) AdminClientRegisterContext(org.keycloak.services.clientpolicy.context.AdminClientRegisterContext) ClientPolicyException(org.keycloak.services.clientpolicy.ClientPolicyException) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes)

Example 23 with RealmManager

use of org.keycloak.services.managers.RealmManager in project keycloak by keycloak.

the class AdminConsole method whoAmI.

/**
 * Permission information
 *
 * @param headers
 * @return
 */
@Path("whoami")
@GET
@Produces(MediaType.APPLICATION_JSON)
@NoCache
public Response whoAmI(@Context final HttpHeaders headers) {
    RealmManager realmManager = new RealmManager(session);
    AuthenticationManager.AuthResult authResult = new AppAuthManager.BearerTokenAuthenticator(session).setRealm(realm).setConnection(clientConnection).setHeaders(headers).authenticate();
    if (authResult == null) {
        return Response.status(401).build();
    }
    UserModel user = authResult.getUser();
    String displayName;
    if ((user.getFirstName() != null && !user.getFirstName().trim().equals("")) || (user.getLastName() != null && !user.getLastName().trim().equals(""))) {
        displayName = user.getFirstName();
        if (user.getLastName() != null) {
            displayName = displayName != null ? displayName + " " + user.getLastName() : user.getLastName();
        }
    } else {
        displayName = user.getUsername();
    }
    RealmModel masterRealm = getAdminstrationRealm(realmManager);
    Map<String, Set<String>> realmAccess = new HashMap<String, Set<String>>();
    if (masterRealm == null)
        throw new NotFoundException("No realm found");
    boolean createRealm = false;
    if (realm.equals(masterRealm)) {
        logger.debug("setting up realm access for a master realm user");
        createRealm = user.hasRole(masterRealm.getRole(AdminRoles.CREATE_REALM));
        addMasterRealmAccess(user, realmAccess);
    } else {
        logger.debug("setting up realm access for a realm user");
        addRealmAccess(realm, user, realmAccess);
    }
    Locale locale = session.getContext().resolveLocale(user);
    Cors.add(request).allowedOrigins(authResult.getToken()).allowedMethods("GET").auth().build(response);
    return Response.ok(new WhoAmI(user.getId(), realm.getName(), displayName, createRealm, realmAccess, locale)).build();
}
Also used : Locale(java.util.Locale) Set(java.util.Set) HashSet(java.util.HashSet) HashMap(java.util.HashMap) NotFoundException(javax.ws.rs.NotFoundException) RealmManager(org.keycloak.services.managers.RealmManager) AuthenticationManager(org.keycloak.services.managers.AuthenticationManager) UserModel(org.keycloak.models.UserModel) RealmModel(org.keycloak.models.RealmModel) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) NoCache(org.jboss.resteasy.annotations.cache.NoCache)

Example 24 with RealmManager

use of org.keycloak.services.managers.RealmManager in project keycloak by keycloak.

the class AdminRoot method authenticateRealmAdminRequest.

protected AdminAuth authenticateRealmAdminRequest(HttpHeaders headers) {
    String tokenString = AppAuthManager.extractAuthorizationHeaderToken(headers);
    if (tokenString == null)
        throw new NotAuthorizedException("Bearer");
    AccessToken token;
    try {
        JWSInput input = new JWSInput(tokenString);
        token = input.readJsonContent(AccessToken.class);
    } catch (JWSInputException e) {
        throw new NotAuthorizedException("Bearer token format error");
    }
    String realmName = token.getIssuer().substring(token.getIssuer().lastIndexOf('/') + 1);
    RealmManager realmManager = new RealmManager(session);
    RealmModel realm = realmManager.getRealmByName(realmName);
    if (realm == null) {
        throw new NotAuthorizedException("Unknown realm in token");
    }
    session.getContext().setRealm(realm);
    AuthenticationManager.AuthResult authResult = new AppAuthManager.BearerTokenAuthenticator(session).setRealm(realm).setConnection(clientConnection).setHeaders(headers).authenticate();
    if (authResult == null) {
        logger.debug("Token not valid");
        throw new NotAuthorizedException("Bearer");
    }
    return new AdminAuth(realm, authResult.getToken(), authResult.getUser(), authResult.getClient());
}
Also used : RealmModel(org.keycloak.models.RealmModel) AuthenticationManager(org.keycloak.services.managers.AuthenticationManager) AccessToken(org.keycloak.representations.AccessToken) JWSInputException(org.keycloak.jose.jws.JWSInputException) NotAuthorizedException(javax.ws.rs.NotAuthorizedException) JWSInput(org.keycloak.jose.jws.JWSInput) RealmManager(org.keycloak.services.managers.RealmManager)

Example 25 with RealmManager

use of org.keycloak.services.managers.RealmManager in project keycloak by keycloak.

the class AdminRoot method getAdminConsole.

/**
 * path to realm admin console ui
 *
 * @exclude
 * @param name Realm name (not id!)
 * @return
 */
@Path("{realm}/console")
public AdminConsole getAdminConsole(@PathParam("realm") final String name) {
    RealmManager realmManager = new RealmManager(session);
    RealmModel realm = locateRealm(name, realmManager);
    AdminConsole service = new AdminConsole(realm);
    ResteasyProviderFactory.getInstance().injectProperties(service);
    return service;
}
Also used : RealmModel(org.keycloak.models.RealmModel) RealmManager(org.keycloak.services.managers.RealmManager) Path(javax.ws.rs.Path)

Aggregations

RealmManager (org.keycloak.services.managers.RealmManager)47 RealmModel (org.keycloak.models.RealmModel)34 Test (org.junit.Test)19 UserModel (org.keycloak.models.UserModel)17 KeycloakSession (org.keycloak.models.KeycloakSession)16 ClientModel (org.keycloak.models.ClientModel)13 ClientManager (org.keycloak.services.managers.ClientManager)11 ModelTest (org.keycloak.testsuite.arquillian.annotation.ModelTest)10 AtomicReference (java.util.concurrent.atomic.AtomicReference)9 AbstractTestRealmKeycloakTest (org.keycloak.testsuite.AbstractTestRealmKeycloakTest)8 Path (javax.ws.rs.Path)6 UserSessionModel (org.keycloak.models.UserSessionModel)6 UserManager (org.keycloak.models.UserManager)5 AbstractAuthTest (org.keycloak.testsuite.AbstractAuthTest)4 LinkedList (java.util.LinkedList)3 GET (javax.ws.rs.GET)3 NotFoundException (javax.ws.rs.NotFoundException)3 Produces (javax.ws.rs.Produces)3 UserConsentModel (org.keycloak.models.UserConsentModel)3 ClientPolicyException (org.keycloak.services.clientpolicy.ClientPolicyException)3