org.keycloak.representations.IDToken Java Examples

The following examples show how to use org.keycloak.representations.IDToken. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: OIDCAdvancedRequestParamsTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void promptLoginDifferentUser() throws Exception {
    String sss = oauth.getLoginFormUrl();
    System.out.println(sss);

    // Login user
    loginPage.open();
    loginPage.login("test-user@localhost", "password");
    Assert.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType());

    EventRepresentation loginEvent = events.expectLogin().detail(Details.USERNAME, "test-user@localhost").assertEvent();
    IDToken idToken = sendTokenRequestAndGetIDToken(loginEvent);

    // Assert need to re-authenticate with prompt=login
    driver.navigate().to(oauth.getLoginFormUrl() + "&prompt=login");

    // Authenticate as different user
    loginPage.assertCurrent();
    loginPage.login("john-doh@localhost", "password");

    errorPage.assertCurrent();
    Assert.assertTrue(errorPage.getError().startsWith("You are already authenticated as different user"));
}
 
Example #2
Source File: KcOidcBrokerNonceParameterTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void testNonceNotSet() {
    updateExecutions(AbstractBrokerTest::disableUpdateProfileOnFirstLogin);

    oauth.realm(bc.consumerRealmName());
    oauth.clientId("consumer-client");
    oauth.nonce(null);

    OAuthClient.AuthorizationEndpointResponse authzResponse = oauth
            .doLoginSocial(bc.getIDPAlias(), bc.getUserLogin(), bc.getUserPassword());
    String code = authzResponse.getCode();
    OAuthClient.AccessTokenResponse response = oauth.doAccessTokenRequest(code, null);
    IDToken idToken = toIdToken(response.getIdToken());

    Assert.assertNull(idToken.getNonce());
}
 
Example #3
Source File: GroupMembershipMapper.java    From keycloak with Apache License 2.0 6 votes vote down vote up
/**
 * Adds the group membership information to the {@link IDToken#otherClaims}.
 * @param token
 * @param mappingModel
 * @param userSession
 */
protected void setClaim(IDToken token, ProtocolMapperModel mappingModel, UserSessionModel userSession) {

    List<String> membership = new LinkedList<>();
    boolean fullPath = useFullPath(mappingModel);
    for (GroupModel group : userSession.getUser().getGroups()) {
        if (fullPath) {
            membership.add(ModelToRepresentation.buildGroupPath(group));
        } else {
            membership.add(group.getName());
        }
    }
    String protocolClaim = mappingModel.getConfig().get(OIDCAttributeMapperHelper.TOKEN_CLAIM_NAME);

    token.getOtherClaims().put(protocolClaim, membership);
}
 
Example #4
Source File: KeycloakSpringAdapterUtils.java    From smartling-keycloak-extras with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a new {@link RefreshableKeycloakSecurityContext} from the given {@link KeycloakDeployment} and {@link AccessTokenResponse}.
 *
 * @param deployment the <code>KeycloakDeployment</code> for which to create a <code>RefreshableKeycloakSecurityContext</code> (required)
 * @param accessTokenResponse the <code>AccessTokenResponse</code> from which to create a RefreshableKeycloakSecurityContext (required)
 *
 * @return a <code>RefreshableKeycloakSecurityContext</code> created from the given <code>accessTokenResponse</code>
 * @throws VerificationException if the given <code>AccessTokenResponse</code> contains an invalid {@link IDToken}
 */
public static RefreshableKeycloakSecurityContext createKeycloakSecurityContext(KeycloakDeployment deployment, AccessTokenResponse accessTokenResponse) throws VerificationException {
    String tokenString = accessTokenResponse.getToken();
    String idTokenString = accessTokenResponse.getIdToken();
    AccessToken accessToken = RSATokenVerifier
            .verifyToken(tokenString, deployment.getRealmKey(), deployment.getRealmInfoUrl());
    IDToken idToken;

    try {
        JWSInput input = new JWSInput(idTokenString);
        idToken = input.readJsonContent(IDToken.class);
    } catch (JWSInputException e) {
        throw new VerificationException("Unable to verify ID token", e);
    }

    // FIXME: does it make sense to pass null for the token store?
    return new RefreshableKeycloakSecurityContext(deployment, null, tokenString, accessToken, idTokenString, idToken, accessTokenResponse.getRefreshToken());
}
 
Example #5
Source File: TokenManager.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public AccessTokenResponseBuilder generateIDToken() {
    if (accessToken == null) {
        throw new IllegalStateException("accessToken not set");
    }
    idToken = new IDToken();
    idToken.id(KeycloakModelUtils.generateId());
    idToken.type(TokenUtil.TOKEN_TYPE_ID);
    idToken.subject(accessToken.getSubject());
    idToken.audience(client.getClientId());
    idToken.issuedNow();
    idToken.issuedFor(accessToken.getIssuedFor());
    idToken.issuer(accessToken.getIssuer());
    idToken.setNonce(accessToken.getNonce());
    idToken.setAuthTime(accessToken.getAuthTime());
    idToken.setSessionState(accessToken.getSessionState());
    idToken.expiration(accessToken.getExpiration());
    idToken.setAcr(accessToken.getAcr());
    transformIDToken(session, idToken, userSession, clientSessionCtx);
    return this;
}
 
Example #6
Source File: LDAPPictureServlet.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    resp.setContentType("image/jpeg");
    ServletOutputStream outputStream = resp.getOutputStream();

    KeycloakSecurityContext securityContext = (KeycloakSecurityContext) req.getAttribute(KeycloakSecurityContext.class.getName());
    IDToken idToken = securityContext.getIdToken();

    String profilePicture = idToken.getPicture();

    if (profilePicture != null) {
        byte[] decodedPicture = Base64.decode(profilePicture);
        outputStream.write(decodedPicture);
    }

    outputStream.flush();
}
 
Example #7
Source File: HoKTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void accessTokenRequestWithClientCertificateInHybridFlowWithCodeIDToken() throws Exception {
    String nonce = "ckw938gnspa93dj";
    ClientManager.realm(adminClient.realm("test")).clientId("test-app").standardFlow(true).implicitFlow(true);
    oauth.clientId("test-app");
    oauth.responseType(OIDCResponseType.CODE + " " + OIDCResponseType.ID_TOKEN);
    oauth.nonce(nonce);

    oauth.doLogin("test-user@localhost", "password");

    EventRepresentation loginEvent = events.expectLogin().assertEvent();
    OAuthClient.AuthorizationEndpointResponse authzResponse = new OAuthClient.AuthorizationEndpointResponse(oauth, true);
    Assert.assertNotNull(authzResponse.getSessionState());
    List<IDToken> idTokens = testAuthzResponseAndRetrieveIDTokens(authzResponse, loginEvent);
    for (IDToken idToken : idTokens) {
        Assert.assertEquals(nonce, idToken.getNonce());
        Assert.assertEquals(authzResponse.getSessionState(), idToken.getSessionState());
    }
}
 
Example #8
Source File: HoKTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
protected List<IDToken> testAuthzResponseAndRetrieveIDTokens(OAuthClient.AuthorizationEndpointResponse authzResponse, EventRepresentation loginEvent) {
    Assert.assertEquals(OIDCResponseType.CODE + " " + OIDCResponseType.ID_TOKEN, loginEvent.getDetails().get(Details.RESPONSE_TYPE));

    // IDToken from the authorization response
    Assert.assertNull(authzResponse.getAccessToken());
    String idTokenStr = authzResponse.getIdToken();
    IDToken idToken = oauth.verifyIDToken(idTokenStr);

    // Validate "c_hash"
    Assert.assertNull(idToken.getAccessTokenHash());
    Assert.assertNotNull(idToken.getCodeHash());
    Assert.assertEquals(idToken.getCodeHash(), HashUtils.oidcHash(Algorithm.RS256, authzResponse.getCode()));

    // IDToken exchanged for the code
    IDToken idToken2 = sendTokenRequestAndGetIDToken(loginEvent);

    return Arrays.asList(idToken, idToken2);
}
 
Example #9
Source File: JsonParserTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void testUnwrap() throws Exception {
    // just experimenting with unwrapped and any properties
    IDToken test = new IDToken();
    test.getOtherClaims().put("phone_number", "978-666-0000");
    test.getOtherClaims().put("email_verified", "true");
    test.getOtherClaims().put("yo", "true");
    Map<String, String> nested = new HashMap<String, String>();
    nested.put("foo", "bar");
    test.getOtherClaims().put("nested", nested);
    String json = JsonSerialization.writeValueAsPrettyString(test);
    System.out.println(json);

    test = JsonSerialization.readValue(json, IDToken.class);
    System.out.println("email_verified property: " + test.getEmailVerified());
    System.out.println("property: " + test.getPhoneNumber());
    System.out.println("map: " + test.getOtherClaims().get("phone_number"));
    Assert.assertNotNull(test.getPhoneNumber());
    Assert.assertNotNull(test.getOtherClaims().get("yo"));
    Assert.assertNull(test.getOtherClaims().get("phone_number"));
    nested = (Map<String, String>)test.getOtherClaims().get("nested");
    Assert.assertNotNull(nested);
    Assert.assertNotNull(nested.get("foo"));
}
 
Example #10
Source File: AdapterTokenVerifier.java    From keycloak with Apache License 2.0 6 votes vote down vote up
/**
 * Verify access token and ID token. Typically called after successful tokenResponse is received from Keycloak
 *
 * @param accessTokenString
 * @param idTokenString
 * @param deployment
 * @return verified and parsed accessToken and idToken
 * @throws VerificationException
 */
public static VerifiedTokens verifyTokens(String accessTokenString, String idTokenString, KeycloakDeployment deployment) throws VerificationException {
    // Adapters currently do most of the checks including signature etc on the access token
    TokenVerifier<AccessToken> tokenVerifier = createVerifier(accessTokenString, deployment, true, AccessToken.class);
    AccessToken accessToken = tokenVerifier.verify().getToken();

    if (idTokenString != null) {
        // Don't verify signature again on IDToken
        IDToken idToken = TokenVerifier.create(idTokenString, IDToken.class).getToken();
        TokenVerifier<IDToken> idTokenVerifier = TokenVerifier.createWithoutSignature(idToken);

        // Always verify audience and azp on IDToken
        idTokenVerifier.audience(deployment.getResourceName());
        idTokenVerifier.issuedFor(deployment.getResourceName());

        idTokenVerifier.verify();
        return new VerifiedTokens(accessToken, idToken);
    } else {
        return new VerifiedTokens(accessToken, null);
    }
}
 
Example #11
Source File: OIDCProtocolMappersTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void testGroupAttributeUserOneGroupMultivalueNoAggregate() throws Exception {
    // get the user
    UserResource userResource = findUserByUsernameId(adminClient.realm("test"), "test-user@localhost");
    UserRepresentation user = userResource.toRepresentation();
    user.setAttributes(new HashMap<>());
    user.getAttributes().put("group-value", Arrays.asList("user-value1", "user-value2"));
    userResource.update(user);
    // create a group1 with two values
    GroupRepresentation group1 = new GroupRepresentation();
    group1.setName("group1");
    group1.setAttributes(new HashMap<>());
    group1.getAttributes().put("group-value", Arrays.asList("value1", "value2"));
    adminClient.realm("test").groups().add(group1);
    group1 = adminClient.realm("test").getGroupByPath("/group1");
    userResource.joinGroup(group1.getId());
    // create the attribute mapper
    ProtocolMappersResource protocolMappers = findClientResourceByClientId(adminClient.realm("test"), "test-app").getProtocolMappers();
    protocolMappers.createMapper(createClaimMapper("group-value", "group-value", "group-value", "String", true, true, true, false)).close();

    try {
        // test it
        OAuthClient.AccessTokenResponse response = browserLogin("password", "test-user@localhost", "password");

        IDToken idToken = oauth.verifyIDToken(response.getIdToken());
        assertNotNull(idToken.getOtherClaims());
        assertNotNull(idToken.getOtherClaims().get("group-value"));
        assertTrue(idToken.getOtherClaims().get("group-value") instanceof List);
        assertEquals(2, ((List) idToken.getOtherClaims().get("group-value")).size());
        assertTrue(((List) idToken.getOtherClaims().get("group-value")).contains("user-value1"));
        assertTrue(((List) idToken.getOtherClaims().get("group-value")).contains("user-value2"));
    } finally {
        // revert
        user.getAttributes().remove("group-value");
        userResource.update(user);
        userResource.leaveGroup(group1.getId());
        adminClient.realm("test").groups().group(group1.getId()).remove();
        deleteMappers(protocolMappers);
    }
}
 
Example #12
Source File: OIDCWellKnownProviderTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void testIssuerMatches() throws Exception {
    OAuthClient.AuthorizationEndpointResponse authzResp = oauth.doLogin("test-user@localhost", "password");
    OAuthClient.AccessTokenResponse response = oauth.doAccessTokenRequest(authzResp.getCode(), "password");
    assertEquals(200, response.getStatusCode());
    IDToken idToken = oauth.verifyIDToken(response.getIdToken());

    Client client = ClientBuilder.newClient();
    try {
        OIDCConfigurationRepresentation oidcConfig = getOIDCDiscoveryRepresentation(client);

        // assert issuer matches
        assertEquals(idToken.getIssuer(), oidcConfig.getIssuer());
    } finally {
        client.close();
    }
}
 
Example #13
Source File: OIDCScopeTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private void assertProfile(IDToken idToken, boolean claimsIn) {
    if (claimsIn) {
        Assert.assertEquals("john", idToken.getPreferredUsername());
        Assert.assertEquals("John", idToken.getGivenName());
        Assert.assertEquals("Doe", idToken.getFamilyName());
        Assert.assertEquals("John Doe", idToken.getName());
    } else {
        Assert.assertNull(idToken.getPreferredUsername());
        Assert.assertNull(idToken.getGivenName());
        Assert.assertNull(idToken.getFamilyName());
        Assert.assertNull(idToken.getName());
    }
}
 
Example #14
Source File: AbstractOIDCResponseTypeTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
public void nonceAndSessionStateMatches() {
    EventRepresentation loginEvent = loginUser("abcdef123456");

    OAuthClient.AuthorizationEndpointResponse authzResponse = new OAuthClient.AuthorizationEndpointResponse(oauth, isFragment());
    Assert.assertNotNull(authzResponse.getSessionState());

    List<IDToken> idTokens = testAuthzResponseAndRetrieveIDTokens(authzResponse, loginEvent);

    for (IDToken idToken : idTokens) {
        Assert.assertEquals("abcdef123456", idToken.getNonce());
        Assert.assertEquals(authzResponse.getSessionState(), idToken.getSessionState());
    }
}
 
Example #15
Source File: AbstractOIDCResponseTypeTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
public void initialSessionStateUsedInRedirect() {
    EventRepresentation loginEvent = loginUserWithRedirect("abcdef123456", OAuthClient.APP_ROOT + "/auth?session_state=foo");

    OAuthClient.AuthorizationEndpointResponse authzResponse = new OAuthClient.AuthorizationEndpointResponse(oauth, isFragment());
    Assert.assertNotNull(authzResponse.getSessionState());

    List<IDToken> idTokens = testAuthzResponseAndRetrieveIDTokens(authzResponse, loginEvent);

    for (IDToken idToken : idTokens) {
        Assert.assertEquals(authzResponse.getSessionState(), idToken.getSessionState());
    }
}
 
Example #16
Source File: UserSessionNoteMapper.java    From keycloak with Apache License 2.0 5 votes vote down vote up
protected void setClaim(IDToken token, ProtocolMapperModel mappingModel, UserSessionModel userSession) {

        String noteName = mappingModel.getConfig().get(ProtocolMapperUtils.USER_SESSION_NOTE);
        String noteValue = userSession.getNote(noteName);
        if (noteValue == null) return;
        OIDCAttributeMapperHelper.mapClaim(token, mappingModel, noteValue);
    }
 
Example #17
Source File: OIDCAttributeMapperHelper.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public static void mapClaim(IDToken token, ProtocolMapperModel mappingModel, Object attributeValue) {
    attributeValue = mapAttributeValue(mappingModel, attributeValue);
    if (attributeValue == null) return;

    String protocolClaim = mappingModel.getConfig().get(TOKEN_CLAIM_NAME);
    if (protocolClaim == null) {
        return;
    }
    List<String> split = splitClaimPath(protocolClaim);
    final int length = split.size();
    int i = 0;
    Map<String, Object> jsonObject = token.getOtherClaims();
    for (String component : split) {
        i++;
        if (i == length) {
            jsonObject.put(component, attributeValue);
        } else {
            Map<String, Object> nested = (Map<String, Object>)jsonObject.get(component);

            if (nested == null) {
                nested = new HashMap<String, Object>();
                jsonObject.put(component, nested);
            }

            jsonObject = nested;
        }
    }
}
 
Example #18
Source File: OIDCProtocolMappersTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
public void testRoleMapperWithRoleInheritedFromMoreGroups() throws Exception {
    // Create client-mapper
    String clientId = "test-app";
    ProtocolMapperRepresentation clientMapper = ProtocolMapperUtil.createUserClientRoleMappingMapper(clientId, null, "Client roles mapper", "roles-custom.test-app", true, true);

    ProtocolMappersResource protocolMappers = ApiUtil.findClientResourceByClientId(adminClient.realm("test"), clientId).getProtocolMappers();
    protocolMappers.createMapper(Arrays.asList(clientMapper));

    // Add user 'level2GroupUser' to the group 'level2Group2'
    GroupRepresentation level2Group2 = adminClient.realm("test").getGroupByPath("/topGroup/level2group2");
    UserResource level2GroupUser = ApiUtil.findUserByUsernameId(adminClient.realm("test"), "level2GroupUser");
    level2GroupUser.joinGroup(level2Group2.getId());

    oauth.clientId(clientId);
    OAuthClient.AccessTokenResponse response = browserLogin("password", "level2GroupUser", "password");
    IDToken idToken = oauth.verifyIDToken(response.getIdToken());

    // Verify attribute is filled AND it is filled only once
    Map<String, Object> roleMappings = (Map<String, Object>)idToken.getOtherClaims().get("roles-custom");
    Assert.assertThat(roleMappings.keySet(), containsInAnyOrder(clientId));
    String testAppScopeMappings = (String) roleMappings.get(clientId);
    assertRolesString(testAppScopeMappings,
            "customer-user"      // from assignment to level2group or level2group2. It is filled just once
    );

    // Revert
    level2GroupUser.leaveGroup(level2Group2.getId());
    deleteMappers(protocolMappers);
}
 
Example #19
Source File: OIDCBasicResponseTypeCodeTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
protected List<IDToken> testAuthzResponseAndRetrieveIDTokens(OAuthClient.AuthorizationEndpointResponse authzResponse, EventRepresentation loginEvent) {
    Assert.assertEquals(OIDCResponseType.CODE, loginEvent.getDetails().get(Details.RESPONSE_TYPE));

    Assert.assertNull(authzResponse.getAccessToken());
    Assert.assertNull(authzResponse.getIdToken());

    OAuthClient.AccessTokenResponse authzResponse2 = sendTokenRequestAndGetResponse(loginEvent);
    IDToken idToken2 = oauth.verifyIDToken(authzResponse2.getIdToken());

    // Validate "at_hash"
    assertValidAccessTokenHash(idToken2.getAccessTokenHash(), authzResponse2.getAccessToken());

    return Collections.singletonList(idToken2);
}
 
Example #20
Source File: OIDCScopeTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private void assertEmail(IDToken idToken, boolean claimsIn) {
    if (claimsIn) {
        Assert.assertEquals("[email protected]", idToken.getEmail());
        Assert.assertEquals(true, idToken.getEmailVerified());
    } else {
        Assert.assertNull(idToken.getEmail());
        Assert.assertNull(idToken.getEmailVerified());
    }
}
 
Example #21
Source File: OIDCScopeTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private void assertAddress(IDToken idToken, boolean claimsIn) {
    AddressClaimSet address = idToken.getAddress();
    if (claimsIn) {
        Assert.assertNotNull(address);
        Assert.assertEquals("Elm 5", address.getStreetAddress());
    } else {
        Assert.assertNull(address);
    }
}
 
Example #22
Source File: KeycloakSecurityContext.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
    DelegatingSerializationFilter.builder()
            .addAllowedClass(KeycloakSecurityContext.class)
            .setFilter(in);
    in.defaultReadObject();

    token = parseToken(tokenString, AccessToken.class);
    idToken = parseToken(idTokenString, IDToken.class);
}
 
Example #23
Source File: AbstractOIDCProtocolMapper.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public IDToken transformIDToken(IDToken token, ProtocolMapperModel mappingModel, KeycloakSession session,
                                UserSessionModel userSession, ClientSessionContext clientSessionCtx) {

    if (!OIDCAttributeMapperHelper.includeInIDToken(mappingModel)){
        return token;
    }

    setClaim(token, mappingModel, userSession, session, clientSessionCtx);
    return token;
}
 
Example #24
Source File: OIDCProtocolMappersTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
@AuthServerContainerExclude(AuthServer.REMOTE)
public void testUserRoleToAttributeMappers() throws Exception {
    // Add mapper for realm roles
    ProtocolMapperRepresentation realmMapper = ProtocolMapperUtil.createUserRealmRoleMappingMapper("pref.", "Realm roles mapper", "roles-custom.realm", true, true);
    ProtocolMapperRepresentation clientMapper = ProtocolMapperUtil.createUserClientRoleMappingMapper("test-app", null, "Client roles mapper", "roles-custom.test-app", true, true);

    ProtocolMappersResource protocolMappers = ApiUtil.findClientResourceByClientId(adminClient.realm("test"), "test-app").getProtocolMappers();
    protocolMappers.createMapper(Arrays.asList(realmMapper, clientMapper));

    // Login user
    OAuthClient.AccessTokenResponse response = browserLogin("password", "test-user@localhost", "password");
    IDToken idToken = oauth.verifyIDToken(response.getIdToken());

    // Verify attribute is filled
    Map<String, Object> roleMappings = (Map<String, Object>)idToken.getOtherClaims().get("roles-custom");
    Assert.assertThat(roleMappings.keySet(), containsInAnyOrder("realm", "test-app"));
    String realmRoleMappings = (String) roleMappings.get("realm");
    String testAppMappings = (String) roleMappings.get("test-app");
    assertRolesString(realmRoleMappings,
            "pref.user",                      // from direct assignment in user definition
            "pref.offline_access"             // from direct assignment in user definition
    );
    assertRolesString(testAppMappings,
            "customer-user"                   // from direct assignment in user definition
    );

    // Revert
    deleteMappers(protocolMappers);
}
 
Example #25
Source File: ClaimInformationPointProviderTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private HttpFacade createHttpFacade(Map<String, List<String>> headers, InputStream requestBody) {
    return new OIDCHttpFacade() {
        private Request request;

        @Override
        public KeycloakSecurityContext getSecurityContext() {
            AccessToken token = new AccessToken();

            token.subject("sub");
            token.setPreferredUsername("username");
            token.getOtherClaims().put("custom_claim", Arrays.asList("param-other-claims-value1", "param-other-claims-value2"));

            IDToken idToken = new IDToken();

            idToken.subject("sub");
            idToken.setPreferredUsername("username");
            idToken.getOtherClaims().put("custom_claim", Arrays.asList("param-other-claims-value1", "param-other-claims-value2"));

            return new KeycloakSecurityContext("tokenString", token, "idTokenString", idToken);
        }

        @Override
        public Request getRequest() {
            if (request == null) {
                request = createHttpRequest(headers, requestBody);
            }
            return request;
        }

        @Override
        public Response getResponse() {
            return createHttpResponse();
        }

        @Override
        public X509Certificate[] getCertificateChain() {
            return new X509Certificate[0];
        }
    };
}
 
Example #26
Source File: TokenManager.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public void transformIDToken(KeycloakSession session, IDToken token,
                                  UserSessionModel userSession, ClientSessionContext clientSessionCtx) {

    for (Map.Entry<ProtocolMapperModel, ProtocolMapper> entry : ProtocolMapperUtils.getSortedProtocolMappers(session, clientSessionCtx)) {
        ProtocolMapperModel mapping = entry.getKey();
        ProtocolMapper mapper = entry.getValue();

        if (mapper instanceof OIDCIDTokenMapper) {
            token = ((OIDCIDTokenMapper) mapper).transformIDToken(token, mapping, session, userSession, clientSessionCtx);
        }
    }
}
 
Example #27
Source File: OIDCProtocolMappersTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
public void testUserGroupRoleToAttributeMappersNotScopedOtherApp() throws Exception {
    String clientId = "test-app-authz";
    ProtocolMapperRepresentation realmMapper = ProtocolMapperUtil.createUserRealmRoleMappingMapper("pref.", "Realm roles mapper", "roles-custom.realm", true, true);
    ProtocolMapperRepresentation clientMapper = ProtocolMapperUtil.createUserClientRoleMappingMapper(clientId, null, "Client roles mapper", "roles-custom." + clientId, true, true);

    ProtocolMappersResource protocolMappers = ApiUtil.findClientResourceByClientId(adminClient.realm("test"), clientId).getProtocolMappers();
    protocolMappers.createMapper(Arrays.asList(realmMapper, clientMapper));

    // Login user
    ClientManager.realm(adminClient.realm("test")).clientId(clientId).directAccessGrant(true);
    oauth.clientId(clientId);

    String oldRedirectUri = oauth.getRedirectUri();
    oauth.redirectUri(UriUtils.getOrigin(oldRedirectUri) + "/test-app-authz");

    OAuthClient.AccessTokenResponse response = browserLogin("secret", "[email protected]", "password");
    IDToken idToken = oauth.verifyIDToken(response.getIdToken());

    // revert redirect_uri
    oauth.redirectUri(oldRedirectUri);

    // Verify attribute is filled
    Map<String, Object> roleMappings = (Map<String, Object>)idToken.getOtherClaims().get("roles-custom");
    Assert.assertThat(roleMappings.keySet(), containsInAnyOrder("realm"));
    String realmRoleMappings = (String) roleMappings.get("realm");
    String testAppAuthzMappings = (String) roleMappings.get(clientId);
    assertRolesString(realmRoleMappings,
      "pref.admin",                     // from direct assignment to /roleRichGroup/level2group
      "pref.user",                      // from parent group of /roleRichGroup/level2group, i.e. from /roleRichGroup
      "pref.customer-user-premium",     // from client role customer-admin-composite-role - realm role for test-app
      "pref.realm-composite-role",      // from parent group of /roleRichGroup/level2group, i.e. from /roleRichGroup
      "pref.sample-realm-role"          // from realm role realm-composite-role
    );
    assertNull(testAppAuthzMappings);  // There is no client role defined for test-app-authz

    // Revert
    deleteMappers(protocolMappers);
}
 
Example #28
Source File: OIDCAdvancedRequestParamsTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
public void nonSupportedParams() {
    driver.navigate().to(oauth.getLoginFormUrl() + "&display=popup&foo=foobar&claims_locales=fr");

    loginPage.assertCurrent();
    loginPage.login("test-user@localhost", "password");
    Assert.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType());

    EventRepresentation loginEvent = events.expectLogin().detail(Details.USERNAME, "test-user@localhost").assertEvent();
    IDToken idToken = sendTokenRequestAndGetIDToken(loginEvent);

    Assert.assertNotNull(idToken);
}
 
Example #29
Source File: OIDCAdvancedRequestParamsTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
public void testMaxAge1() {
    // Open login form and login successfully
    oauth.doLogin("test-user@localhost", "password");
    EventRepresentation loginEvent = events.expectLogin().assertEvent();

    IDToken idToken = sendTokenRequestAndGetIDToken(loginEvent);

    // Check that authTime is available and set to current time
    int authTime = idToken.getAuthTime();
    int currentTime = Time.currentTime();
    Assert.assertTrue(authTime <= currentTime && authTime + 3 >= currentTime);

    // Set time offset
    setTimeOffset(10);

    // Now open login form with maxAge=1
    oauth.maxAge("1");

    // Assert I need to login again through the login form
    oauth.doLogin("test-user@localhost", "password");
    loginEvent = events.expectLogin().assertEvent();

    idToken = sendTokenRequestAndGetIDToken(loginEvent);

    // Assert that authTime was updated
    int authTimeUpdated = idToken.getAuthTime();
    Assert.assertTrue(authTime + 10 <= authTimeUpdated);
}
 
Example #30
Source File: AddressMapper.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
protected void setClaim(IDToken token, ProtocolMapperModel mappingModel, UserSessionModel userSession) {
    UserModel user = userSession.getUser();
    AddressClaimSet addressSet = new AddressClaimSet();
    addressSet.setStreetAddress(getUserModelAttributeValue(user, mappingModel, STREET));
    addressSet.setLocality(getUserModelAttributeValue(user, mappingModel, AddressClaimSet.LOCALITY));
    addressSet.setRegion(getUserModelAttributeValue(user, mappingModel, AddressClaimSet.REGION));
    addressSet.setPostalCode(getUserModelAttributeValue(user, mappingModel, AddressClaimSet.POSTAL_CODE));
    addressSet.setCountry(getUserModelAttributeValue(user, mappingModel, AddressClaimSet.COUNTRY));
    addressSet.setFormattedAddress(getUserModelAttributeValue(user, mappingModel, AddressClaimSet.FORMATTED));
    token.getOtherClaims().put("address", addressSet);
}