Java Code Examples for org.keycloak.representations.AccessToken#id()

The following examples show how to use org.keycloak.representations.AccessToken#id() . 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: IdentityServiceRemoteUserMapperTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Utility method to create tokens for testing.
 * 
 * @param expired Determines whether to create an expired JWT
 * @return The string representation of the JWT
 */
private String generateToken(boolean expired) throws Exception
{
    String issuerUrl = this.identityServiceConfig.getAuthServerUrl() + "/realms/" + this.identityServiceConfig.getRealm();
    
    AccessToken token = new AccessToken();
    token.type("Bearer");
    token.id("1234");
    token.subject("abc123");
    token.issuer(issuerUrl);
    token.setPreferredUsername(TEST_USER_USERNAME);
    token.setEmail(TEST_USER_EMAIL);
    token.setGivenName("Joe");
    token.setFamilyName("Bloggs");
    
    if (expired)
    {
        token.expiration(Time.currentTime() - 60);
    }

    String jwt = new JWSBuilder()
            .jsonContent(token)
            .rsa256(keyPair.getPrivate());
    
    return jwt;
}
 
Example 2
Source File: SkeletonKeyTokenTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void testRSA() throws Exception {
    AccessToken token = createSimpleToken();
    token.id("111");
    token.addAccess("foo").addRole("admin");
    token.addAccess("bar").addRole("user");

    KeyPair keyPair = KeyPairGenerator.getInstance("RSA").generateKeyPair();

    String encoded = new JWSBuilder()
            .jsonContent(token)
            .rsa256(keyPair.getPrivate());

    JWSInput input = new JWSInput(encoded);

    token = input.readJsonContent(AccessToken.class);
    Assert.assertEquals("111", token.getId());
    Assert.assertTrue(RSAProvider.verify(input, keyPair.getPublic()));
}
 
Example 3
Source File: SkeletonKeyTokenTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void testTokenWithoutResourceAccess() throws Exception {
    AccessToken token = new AccessToken();
    token.id("111");
    token.issuer("http://localhost:8080/auth/acme");

    String json = JsonSerialization.writeValueAsString(token);

    // Assert JSON doesn't contain "realm_access" or "resource_access" fields as it doesn't have any roles specified
    Assert.assertFalse(json.contains("realm_access"));
    Assert.assertFalse(json.contains("resource_access"));

    token = JsonSerialization.readValue(json, AccessToken.class);

    Assert.assertNull(token.getRealmAccess());
    Assert.assertTrue(token.getResourceAccess() != null && token.getResourceAccess().isEmpty());
    Assert.assertNull(token.getResourceAccess("foo"));
}
 
Example 4
Source File: TokenManager.java    From keycloak with Apache License 2.0 5 votes vote down vote up
protected AccessToken initToken(RealmModel realm, ClientModel client, UserModel user, UserSessionModel session,
                                ClientSessionContext clientSessionCtx, UriInfo uriInfo) {
    AccessToken token = new AccessToken();
    token.id(KeycloakModelUtils.generateId());
    token.type(TokenUtil.TOKEN_TYPE_BEARER);
    token.subject(user.getId());
    token.issuedNow();
    token.issuedFor(client.getClientId());

    AuthenticatedClientSessionModel clientSession = clientSessionCtx.getClientSession();
    token.issuer(clientSession.getNote(OIDCLoginProtocol.ISSUER));
    token.setNonce(clientSessionCtx.getAttribute(OIDCLoginProtocol.NONCE_PARAM, String.class));
    token.setScope(clientSessionCtx.getScopeString());

    // Best effort for "acr" value. Use 0 if clientSession was authenticated through cookie ( SSO )
    // TODO: Add better acr support. See KEYCLOAK-3314
    String acr = (AuthenticationManager.isSSOAuthentication(clientSession)) ? "0" : "1";
    token.setAcr(acr);

    String authTime = session.getNote(AuthenticationManager.AUTH_TIME);
    if (authTime != null) {
        token.setAuthTime(Integer.parseInt(authTime));
    }


    token.setSessionState(session.getId());
    ClientScopeModel offlineAccessScope = KeycloakModelUtils.getClientScopeByName(realm, OAuth2Constants.OFFLINE_ACCESS);
    boolean offlineTokenRequested = offlineAccessScope == null ? false
        : clientSessionCtx.getClientScopeIds().contains(offlineAccessScope.getId());
    token.expiration(getTokenExpiration(realm, client, session, clientSession, offlineTokenRequested));

    return token;
}
 
Example 5
Source File: SkeletonKeyTokenTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private AccessToken createSimpleToken() {
    AccessToken token = new AccessToken();
    token.id("111");
    token.issuer("http://localhost:8080/auth/acme");
    token.addAccess("foo").addRole("admin");
    token.addAccess("bar").addRole("user");
    return token;
}
 
Example 6
Source File: RPTIntrospectionProvider.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Override
public Response introspect(String token) {
    LOGGER.debug("Introspecting requesting party token");
    try {
        AccessToken accessToken = verifyAccessToken(token);

        ObjectNode tokenMetadata;

        if (accessToken != null) {
            AccessToken metadata = new AccessToken();

            metadata.id(accessToken.getId());
            metadata.setAcr(accessToken.getAcr());
            metadata.type(accessToken.getType());
            metadata.expiration(accessToken.getExpiration());
            metadata.issuedAt(accessToken.getIssuedAt());
            metadata.audience(accessToken.getAudience());
            metadata.notBefore(accessToken.getNotBefore());
            metadata.setRealmAccess(null);
            metadata.setResourceAccess(null);

            tokenMetadata = JsonSerialization.createObjectNode(metadata);
            Authorization authorization = accessToken.getAuthorization();

            if (authorization != null) {
                Collection permissions;

                if (authorization.getPermissions() != null) {
                    permissions = authorization.getPermissions().stream().map(UmaPermissionRepresentation::new).collect(Collectors.toSet());
                } else {
                    permissions = Collections.emptyList();
                }

                tokenMetadata.putPOJO("permissions", permissions);
            }
        } else {
            tokenMetadata = JsonSerialization.createObjectNode();
        }

        tokenMetadata.put("active", accessToken != null);

        return Response.ok(JsonSerialization.writeValueAsBytes(tokenMetadata)).type(MediaType.APPLICATION_JSON_TYPE).build();
    } catch (Exception e) {
        throw new RuntimeException("Error creating token introspection response.", e);
    }
}