Java源码示例:org.keycloak.models.ClientModel

示例1
protected Response exchangeStoredToken(UriInfo uriInfo, EventBuilder event, ClientModel authorizedClient, UserSessionModel tokenUserSession, UserModel tokenSubject) {
    FederatedIdentityModel model = session.users().getFederatedIdentity(tokenSubject, getConfig().getAlias(), authorizedClient.getRealm());
    if (model == null || model.getToken() == null) {
        event.detail(Details.REASON, "requested_issuer is not linked");
        event.error(Errors.INVALID_TOKEN);
        return exchangeNotLinked(uriInfo, authorizedClient, tokenUserSession, tokenSubject);
    }
    String accessToken = extractTokenFromResponse(model.getToken(), getAccessTokenResponseParameter());
    if (accessToken == null) {
        model.setToken(null);
        session.users().updateFederatedIdentity(authorizedClient.getRealm(), tokenSubject, model);
        event.detail(Details.REASON, "requested_issuer token expired");
        event.error(Errors.INVALID_TOKEN);
        return exchangeTokenExpired(uriInfo, authorizedClient, tokenUserSession, tokenSubject);
    }
    AccessTokenResponse tokenResponse = new AccessTokenResponse();
    tokenResponse.setToken(accessToken);
    tokenResponse.setIdToken(null);
    tokenResponse.setRefreshToken(null);
    tokenResponse.setRefreshExpiresIn(0);
    tokenResponse.getOtherClaims().clear();
    tokenResponse.getOtherClaims().put(OAuth2Constants.ISSUED_TOKEN_TYPE, OAuth2Constants.ACCESS_TOKEN_TYPE);
    tokenResponse.getOtherClaims().put(ACCOUNT_LINK_URL, getLinkingUrl(uriInfo, authorizedClient, tokenUserSession));
    event.success();
    return Response.ok(tokenResponse).type(MediaType.APPLICATION_JSON_TYPE).build();
}
 
示例2
@Test
public void ipTest() {
    final String ip = "146.58.69.12";

    String sessionId = "abcdefg";
    testingClient.server().run(session -> {
        RealmModel realm = session.realms().getRealmByName(TEST);
        ClientModel client = session.clientLocalStorage().getClientByClientId(TEST_CLIENT_ID, realm);
        UserModel user = session.users().getUserByUsername("test", realm); // cannot use testUser.getUsername() because it throws NotSerializableException for no apparent reason (or maybe I'm just stupid :D)

        UserSessionModel userSession = session.sessions().createUserSession(sessionId, realm, user, "test", ip, "form", false, null, null);
        session.sessions().createClientSession(realm, client, userSession);
    });

    deviceActivityPage.clickRefreshPage();

    assertEquals(ip, deviceActivityPage.getSession(sessionId).getIp());
}
 
示例3
@Override
public void authenticateClient(ClientAuthenticationFlowContext context) {
    ClientIdAndSecretAuthenticator authenticator = new ClientIdAndSecretAuthenticator();
    authenticator.authenticateClient(context);
    if (context.getStatus().equals(FlowStatus.SUCCESS)) {
        return;
    }

    String clientId = context.getUriInfo().getQueryParameters().getFirst("client_id");

    if (clientId == null) {
        clientId = context.getSession().getAttribute("client_id", String.class);
    }

    ClientModel client = context.getRealm().getClientByClientId(clientId);
    if (client == null) {
        context.failure(AuthenticationFlowError.CLIENT_NOT_FOUND, null);
        return;
    }

    context.getEvent().client(client);
    context.setClient(client);
    context.success();
}
 
示例4
private void checkRealmAdminManagementRoles(RealmModel realm) {
    if (realm.getName().equals(Config.getAdminRealm())) { return; } // don't need to do this for master realm

    String realmAdminClientId = getRealmAdminClientId(realm);
    ClientModel realmAdminClient = realm.getClientByClientId(realmAdminClientId);
    RoleModel adminRole = realmAdminClient.getRole(AdminRoles.REALM_ADMIN);

    // if realm-admin role isn't in the realm model, create it
    if (adminRole == null) {
        adminRole = realmAdminClient.addRole(AdminRoles.REALM_ADMIN);
        adminRole.setDescription("${role_" + AdminRoles.REALM_ADMIN + "}");
    }

    for (String r : AdminRoles.ALL_REALM_ROLES) {
        RoleModel found = realmAdminClient.getRole(r);
        if (found == null) {
            addAndSetAdminRole(r, realmAdminClient, adminRole);
        }
    }
    addQueryCompositeRoles(realmAdminClient);
}
 
示例5
@Override
public Set<RoleModel> getClientRoleMappings(ClientModel client) {
    if (roleContainer.equals(client)) {
        Set<RoleModel> ldapRoleMappings = getLDAPRoleMappingsConverted();

        if (config.getMode() == LDAPGroupMapperMode.LDAP_ONLY) {
            // Use just role mappings from LDAP
            return ldapRoleMappings;
        } else {
            // Merge mappings from both DB and LDAP
            Set<RoleModel> modelRoleMappings = super.getClientRoleMappings(client);
            ldapRoleMappings.addAll(modelRoleMappings);
            return ldapRoleMappings;
        }
    } else {
        return super.getClientRoleMappings(client);
    }
}
 
示例6
protected void migrateRealm(RealmModel realm) {
    DefaultAuthenticationFlows.migrateFlows(realm); // add reset credentials flo
    realm.setOTPPolicy(OTPPolicy.DEFAULT_POLICY);
    realm.setBrowserFlow(realm.getFlowByAlias(DefaultAuthenticationFlows.BROWSER_FLOW));
    realm.setRegistrationFlow(realm.getFlowByAlias(DefaultAuthenticationFlows.REGISTRATION_FLOW));
    realm.setDirectGrantFlow(realm.getFlowByAlias(DefaultAuthenticationFlows.DIRECT_GRANT_FLOW));

    AuthenticationFlowModel resetFlow = realm.getFlowByAlias(DefaultAuthenticationFlows.RESET_CREDENTIALS_FLOW);
    if (resetFlow == null) {
        DefaultAuthenticationFlows.resetCredentialsFlow(realm);
    } else {
        realm.setResetCredentialsFlow(resetFlow);
    }

    AuthenticationFlowModel clientAuthFlow = realm.getFlowByAlias(DefaultAuthenticationFlows.CLIENT_AUTHENTICATION_FLOW);
    if (clientAuthFlow == null) {
        DefaultAuthenticationFlows.clientAuthFlow(realm);
    } else {
        realm.setClientAuthenticationFlow(clientAuthFlow);
    }

    for (ClientModel client : realm.getClients()) {
        client.setClientAuthenticatorType(KeycloakModelUtils.getDefaultClientAuthenticatorType());
    }
}
 
示例7
protected void migrateRealm(KeycloakSession session, RealmModel realm, boolean jsn) {
    MigrationProvider migrationProvider = session.getProvider(MigrationProvider.class);

    // create 'microprofile-jwt' optional client scope in the realm.
    ClientScopeModel mpJWTScope = migrationProvider.addOIDCMicroprofileJWTClientScope(realm);

    LOG.debugf("Added '%s' optional client scope", mpJWTScope.getName());

    // assign 'microprofile-jwt' optional client scope to all the OIDC clients.
    for (ClientModel client : realm.getClients()) {
        if ((client.getProtocol() == null || "openid-connect".equals(client.getProtocol())) && (!client.isBearerOnly())) {
            client.addClientScope(mpJWTScope, false);
        }
    }

    LOG.debugf("Client scope '%s' assigned to all the clients", mpJWTScope.getName());
}
 
示例8
@Override
public void beforeUpdate(ClientRegistrationContext context, ClientModel clientModel) throws ClientRegistrationPolicyException {
    if (context.getClient().isConsentRequired() == null) {
        return;
    }
    if (clientModel == null) {
        return;
    }

    boolean isEnabled = clientModel.isConsentRequired();
    boolean newEnabled = context.getClient().isConsentRequired();

    if (isEnabled && !newEnabled) {
        throw new ClientRegistrationPolicyException("Not permitted to update consentRequired to false");
    }
}
 
示例9
private RoleContainerModel getRoleContainer(KeycloakSession session, String roleContainer) {
    String[] parts = roleContainer.split("/");
    String realmName = parts[0];

    RealmModel realm = session.realms().getRealmByName(realmName);
    if (realm == null) {
        log.errorf("Unknown realm: %s", realmName);
        throw new HandledException();
    }

    if (parts.length == 1) {
        return realm;
    } else {
        String clientId = parts[1];
        ClientModel client = session.realms().getClientByClientId(clientId, realm);
        if (client == null) {
            log.errorf("Unknown client: %s", clientId);
            throw new HandledException();
        }

        return client;
    }
}
 
示例10
protected GlobalRequestResult pushRevocationPolicy(RealmModel realm, ClientModel resource, int notBefore) {
    List<String> mgmtUrls = getAllManagementUrls(resource);
    if (mgmtUrls.isEmpty()) {
        logger.debugf("No management URL or no registered cluster nodes for the client %s", resource.getClientId());
        return new GlobalRequestResult();
    }

    if (logger.isDebugEnabled()) logger.debug("Sending push revocation to URLS: " + mgmtUrls);

    // Propagate this to all hosts
    GlobalRequestResult result = new GlobalRequestResult();
    for (String mgmtUrl : mgmtUrls) {
        if (sendPushRevocationPolicyRequest(realm, resource, notBefore, mgmtUrl)) {
            result.addSuccessRequest(mgmtUrl);
        } else {
            result.addFailedRequest(mgmtUrl);
        }
    }
    return result;
}
 
示例11
private boolean isClientScopePermittedForUser(ClientScopeModel clientScope) {
    if (clientScope instanceof ClientModel) {
        return true;
    }

    Set<RoleModel> clientScopeRoles = clientScope.getScopeMappings();

    // Client scope is automatically permitted if it doesn't have any role scope mappings
    if (clientScopeRoles.isEmpty()) {
        return true;
    }

    // Expand (resolve composite roles)
    clientScopeRoles = RoleUtils.expandCompositeRoles(clientScopeRoles);

    // Check if expanded roles of clientScope has any intersection with expanded roles of user. If not, it is not permitted
    clientScopeRoles.retainAll(getUserRoles());
    return !clientScopeRoles.isEmpty();
}
 
示例12
private ClientModel setUpClient(RealmModel realm) {
    ClientModel client = realm.addClient("application");
    client.setName("Application");
    client.setDescription("Description");
    client.setBaseUrl("http://base");
    client.setManagementUrl("http://management");
    client.setClientId("app-name");
    client.setProtocol("openid-connect");
    client.addRole("role-1");
    client.addRole("role-2");
    client.addRole("role-3");
    client.addDefaultRole("role-1");
    client.addDefaultRole("role-2");
    client.addRedirectUri("redirect-1");
    client.addRedirectUri("redirect-2");
    client.addWebOrigin("origin-1");
    client.addWebOrigin("origin-2");
    client.registerNode("node1", 10);
    client.registerNode("10.20.30.40", 50);
    client.addProtocolMapper(AddressMapper.createAddressMapper());
    client.updateClient();
    return client;
}
 
示例13
protected void setupAdminConsole(RealmModel realm) {
    ClientModel adminConsole = realm.getClientByClientId(Constants.ADMIN_CONSOLE_CLIENT_ID);
    if (adminConsole == null) adminConsole = KeycloakModelUtils.createClient(realm, Constants.ADMIN_CONSOLE_CLIENT_ID);
    adminConsole.setName("${client_" + Constants.ADMIN_CONSOLE_CLIENT_ID + "}");

    adminConsole.setRootUrl(Constants.AUTH_ADMIN_URL_PROP);
    String baseUrl = "/admin/" + realm.getName() + "/console/";
    adminConsole.setBaseUrl(baseUrl);
    adminConsole.addRedirectUri(baseUrl + "*");
    adminConsole.setWebOrigins(Collections.singleton("+"));

    adminConsole.setEnabled(true);
    adminConsole.setAlwaysDisplayInConsole(false);
    adminConsole.setPublicClient(true);
    adminConsole.setFullScopeAllowed(false);
    adminConsole.setProtocol(OIDCLoginProtocol.LOGIN_PROTOCOL);

    adminConsole.setAttribute(OIDCConfigAttributes.PKCE_CODE_CHALLENGE_METHOD, "S256");
}
 
示例14
public static void createFederatedRoleMappings(UserFederatedStorageProvider federatedStorage, UserRepresentation userRep, RealmModel realm) {
    if (userRep.getRealmRoles() != null) {
        for (String roleString : userRep.getRealmRoles()) {
            RoleModel role = realm.getRole(roleString.trim());
            if (role == null) {
                role = realm.addRole(roleString.trim());
            }
            federatedStorage.grantRole(realm, userRep.getId(), role);
        }
    }
    if (userRep.getClientRoles() != null) {
        for (Map.Entry<String, List<String>> entry : userRep.getClientRoles().entrySet()) {
            ClientModel client = realm.getClientByClientId(entry.getKey());
            if (client == null) {
                throw new RuntimeException("Unable to find client role mappings for client: " + entry.getKey());
            }
            createFederatedClientRoleMappings(federatedStorage, realm, client, userRep, entry.getValue());
        }
    }
}
 
示例15
@Override
public void onExport(Policy policy, PolicyRepresentation representation, AuthorizationProvider authorizationProvider) {
    Map<String, String> config = new HashMap<>();
    Set<RolePolicyRepresentation.RoleDefinition> roles = toRepresentation(policy, authorizationProvider).getRoles();

    for (RolePolicyRepresentation.RoleDefinition roleDefinition : roles) {
        RoleModel role = authorizationProvider.getRealm().getRoleById(roleDefinition.getId());

        if (role.isClientRole()) {
            roleDefinition.setId(ClientModel.class.cast(role.getContainer()).getClientId() + "/" + role.getName());
        } else {
            roleDefinition.setId(role.getName());
        }
    }

    try {
        config.put("roles", JsonSerialization.writeValueAsString(roles));
    } catch (IOException cause) {
        throw new RuntimeException("Failed to export role policy [" + policy.getName() + "]", cause);
    }

    representation.setConfig(config);
}
 
示例16
/**
 * Should not be called from an import.  This really expects that the client is created from the admin console.
 *
 * @param session
 * @param realm
 * @param rep
 * @param addDefaultRoles
 * @return
 */
public static ClientModel createClient(KeycloakSession session, RealmModel realm, ClientRepresentation rep, boolean addDefaultRoles) {
    ClientModel client = RepresentationToModel.createClient(session, realm, rep, addDefaultRoles);

    if (rep.getProtocol() != null) {
        LoginProtocolFactory providerFactory = (LoginProtocolFactory) session.getKeycloakSessionFactory().getProviderFactory(LoginProtocol.class, rep.getProtocol());
        providerFactory.setupClientDefaults(rep, client);
    }


    // remove default mappers if there is a template
    if (rep.getProtocolMappers() == null && rep.getClientTemplate() != null) {
        Set<ProtocolMapperModel> mappers = client.getProtocolMappers();
        for (ProtocolMapperModel mapper : mappers) client.removeProtocolMapper(mapper);
    }
    return client;

}
 
示例17
public InstallationAdapterConfig toInstallationRepresentation(RealmModel realmModel, ClientModel clientModel, URI baseUri) {
    InstallationAdapterConfig rep = new InstallationAdapterConfig();
    rep.setAuthServerUrl(baseUri.toString());
    rep.setRealm(realmModel.getName());
    rep.setSslRequired(realmModel.getSslRequired().name().toLowerCase());

    if (clientModel.isPublicClient() && !clientModel.isBearerOnly()) rep.setPublicClient(true);
    if (clientModel.isBearerOnly()) rep.setBearerOnly(true);
    if (clientModel.getRoles().size() > 0) rep.setUseResourceRoleMappings(true);

    rep.setResource(clientModel.getClientId());

    if (showClientCredentialsAdapterConfig(clientModel)) {
        Map<String, Object> adapterConfig = getClientCredentialsAdapterConfig(clientModel);
        rep.setCredentials(adapterConfig);
    }

    return rep;
}
 
示例18
private UserConsentModel toConsentModel(RealmModel realm, FederatedUserConsentEntity entity) {
    if (entity == null) {
        return null;
    }

    StorageId clientStorageId = null;
    if ( entity.getClientId() == null) {
        clientStorageId = new StorageId(entity.getClientStorageProvider(), entity.getExternalClientId());
    } else {
        clientStorageId = new StorageId(entity.getClientId());
    }

    ClientModel client = realm.getClientById(clientStorageId.getId());
    UserConsentModel model = new UserConsentModel(client);
    model.setCreatedDate(entity.getCreatedDate());
    model.setLastUpdatedDate(entity.getLastUpdatedDate());

    Collection<FederatedUserConsentClientScopeEntity> grantedClientScopeEntities = entity.getGrantedClientScopes();
    if (grantedClientScopeEntities != null) {
        for (FederatedUserConsentClientScopeEntity grantedClientScope : grantedClientScopeEntities) {
            ClientScopeModel grantedClientScopeModel = realm.getClientScopeById(grantedClientScope.getScopeId());
            if (grantedClientScopeModel != null) {
                model.addGrantedClientScope(grantedClientScopeModel);
            }
        }
    }

    return model;
}
 
示例19
@Test
public void testIsCached() {
    testingClient.server().run(session -> {
        RealmModel realm = session.realms().getRealmByName("test");
        ClientModel hardcoded = realm.getClientByClientId("hardcoded-client");
        Assert.assertNotNull(hardcoded);
        Assert.assertTrue(hardcoded instanceof org.keycloak.models.cache.infinispan.ClientAdapter);
    });
}
 
示例20
private void addRealmAccess(RealmModel realm, UserModel user, Map<String, Set<String>> realmAdminAccess) {
    RealmManager realmManager = new RealmManager(session);
    ClientModel realmAdminApp = realm.getClientByClientId(realmManager.getRealmAdminClientId(realm));
    Set<RoleModel> roles = realmAdminApp.getRoles();
    for (RoleModel role : roles) {
        if (!user.hasRole(role)) continue;
        if (!realmAdminAccess.containsKey(realm.getName())) {
            realmAdminAccess.put(realm.getName(), new HashSet<String>());
        }
        realmAdminAccess.get(realm.getName()).add(role.getName());
    }

}
 
示例21
public static KeyWrapper getClientPublicKeyWrapper(KeycloakSession session, ClientModel client, JWSInput input) {
    String kid = input.getHeader().getKeyId();
    PublicKeyStorageProvider keyStorage = session.getProvider(PublicKeyStorageProvider.class);
    String modelKey = PublicKeyStorageUtils.getClientModelCacheKey(client.getRealm().getId(), client.getId());
    ClientPublicKeyLoader loader = new ClientPublicKeyLoader(session, client);
    return keyStorage.getPublicKey(modelKey, kid, loader);
}
 
示例22
public boolean hasAppRole(ClientModel app, String role) {
    if (client instanceof ClientModel) {
        RoleModel roleModel = app.getRole(role);
        if (roleModel == null) return false;
        return user.hasRole(roleModel) && client.hasScope(roleModel);
    } else {
        AccessToken.Access access = token.getResourceAccess(app.getClientId());
        return access != null && access.isUserInRole(role);
    }
}
 
示例23
public AccessTokenResponseBuilder(RealmModel realm, ClientModel client, EventBuilder event, KeycloakSession session,
                                  UserSessionModel userSession, ClientSessionContext clientSessionCtx) {
    this.realm = realm;
    this.client = client;
    this.event = event;
    this.session = session;
    this.userSession = userSession;
    this.clientSessionCtx = clientSessionCtx;
}
 
示例24
@Override
public ResourceServer realmResourceServer() {
    if (realmResourceServer != null) return realmResourceServer;
    ClientModel client = getRealmManagementClient();
    if (client == null) return null;
    ResourceServerStore resourceServerStore = authz.getStoreFactory().getResourceServerStore();
    realmResourceServer = resourceServerStore.findById(client.getId());
    return realmResourceServer;

}
 
示例25
private ClientModel authorizeClient() {
    ClientModel client = AuthorizeClientUtil.authorizeClient(session, event).getClient();

    if (client.isBearerOnly()) {
        throw new ErrorResponseException(Errors.INVALID_CLIENT, "Bearer-only not allowed", Response.Status.BAD_REQUEST);
    }

    return client;
}
 
示例26
@Override
public URI getActionUrl(String code) {
    ClientModel client = authenticationSession.getClient();
    return LoginActionsService.requiredActionProcessor(getUriInfo())
            .queryParam(LoginActionsService.SESSION_CODE, code)
            .queryParam(Constants.EXECUTION, getExecution())
            .queryParam(Constants.CLIENT_ID, client.getClientId())
            .queryParam(Constants.TAB_ID, authenticationSession.getTabId())
            .build(getRealm().getName());
}
 
示例27
public ClientScopeEvaluateResource(KeycloakSession session, UriInfo uriInfo, RealmModel realm, AdminPermissionEvaluator auth,
                             ClientModel client, ClientConnection clientConnection) {
    this.uriInfo = uriInfo;
    this.realm = realm;
    this.client = client;
    this.auth = auth;
    this.session = session;
    this.clientConnection = clientConnection;
}
 
示例28
@Test
public void importAuthorizationSettings() throws Exception {
    RealmRepresentation testRealm = loadJson(getClass().getResourceAsStream("/model/authz-bug.json"), RealmRepresentation.class);
    adminClient.realms().create(testRealm);

    testingClient.server().run(session -> {
        RealmModel realm = session.realms().getRealmByName("authz-bug");
        AuthorizationProvider authz = session.getProvider(AuthorizationProvider.class);
        ClientModel client = realm.getClientByClientId("appserver");
        ResourceServer resourceServer = authz.getStoreFactory().getResourceServerStore().findById(client.getId());
        Assert.assertEquals("AFFIRMATIVE", resourceServer.getDecisionStrategy().name());
    });
}
 
示例29
public boolean hasOneOfAppRole(ClientModel app, String... roles) {
    for (String r : roles) {
        if (hasClientRole(app, r)) {
            return true;
        }
    }
    return false;
}
 
示例30
private String getSectorIdentifier(ClientModel client, ProtocolMapperModel mappingModel) {
    String sectorIdentifierUri = PairwiseSubMapperHelper.getSectorIdentifierUri(mappingModel);
    if (sectorIdentifierUri != null && !sectorIdentifierUri.isEmpty()) {
        return PairwiseSubMapperUtils.resolveValidSectorIdentifier(sectorIdentifierUri);
    }
    return PairwiseSubMapperUtils.resolveValidSectorIdentifier(client.getRootUrl(), client.getRedirectUris());
}