org.keycloak.representations.AccessToken Java Examples

The following examples show how to use org.keycloak.representations.AccessToken. 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: UmaGrantTypeTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void testObtainRptWithClientCredentials() throws Exception {
    AuthorizationResponse response = authorize("Resource A", new String[] {"ScopeA", "ScopeB"});
    String rpt = response.getToken();

    assertNotNull(rpt);
    assertFalse(response.isUpgraded());

    AccessToken accessToken = toAccessToken(rpt);
    AccessToken.Authorization authorization = accessToken.getAuthorization();

    assertNotNull(authorization);

    Collection<Permission> permissions = authorization.getPermissions();

    assertNotNull(permissions);
    assertPermissions(permissions, "Resource A", "ScopeA", "ScopeB");

    assertTrue(permissions.isEmpty());
}
 
Example #2
Source File: AudienceResolveProtocolMapper.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public AccessToken transformAccessToken(AccessToken token, ProtocolMapperModel mappingModel, KeycloakSession session,
                                        UserSessionModel userSession, ClientSessionContext clientSessionCtx) {
    String clientId = clientSessionCtx.getClientSession().getClient().getClientId();

    for (Map.Entry<String, AccessToken.Access> entry : RoleResolveUtil.getAllResolvedClientRoles(session, clientSessionCtx).entrySet()) {
        // Don't add client itself to the audience
        if (entry.getKey().equals(clientId)) {
            continue;
        }

        AccessToken.Access access = entry.getValue();
        if (access != null && access.getRoles() != null && !access.getRoles().isEmpty()) {
            token.addAudience(entry.getKey());
        }
    }

    return token;
}
 
Example #3
Source File: EntitlementAPITest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
private boolean hasPermission(String userName, String password, String resourceId, String... scopeIds) throws Exception {
    String accessToken = new OAuthClient().realm("authz-test").clientId(RESOURCE_SERVER_TEST).doGrantAccessTokenRequest("secret", userName, password).getAccessToken();
    AuthorizationResponse response = getAuthzClient(AUTHZ_CLIENT_CONFIG).authorization(accessToken).authorize(new AuthorizationRequest());
    AccessToken rpt = toAccessToken(response.getToken());
    Authorization authz = rpt.getAuthorization();
    Collection<Permission> permissions = authz.getPermissions();

    assertNotNull(permissions);
    assertFalse(permissions.isEmpty());

    for (Permission grantedPermission : permissions) {
        if (grantedPermission.getResourceId().equals(resourceId)) {
            return scopeIds == null || scopeIds.length == 0 || grantedPermission.getScopes().containsAll(Arrays.asList(scopeIds));
        }
    }

    return false;
}
 
Example #4
Source File: AdminSignatureAlgorithmTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void changeRealmTokenAlgorithm() throws Exception {
    TokenSignatureUtil.changeRealmTokenSignatureProvider("master", adminClient, Algorithm.ES256);

    try (Keycloak adminClient = AdminClientUtil.createAdminClient(suiteContext.isAdapterCompatTesting(), suiteContext.getAuthServerInfo().getContextRoot().toString())) {
        AccessTokenResponse accessToken = adminClient.tokenManager().getAccessToken();
        TokenVerifier<AccessToken> verifier = TokenVerifier.create(accessToken.getToken(), AccessToken.class);
        assertEquals(Algorithm.ES256, verifier.getHeader().getAlgorithm().name());

        assertNotNull(adminClient.realms().findAll());

        String whoAmiUrl = suiteContext.getAuthServerInfo().getContextRoot().toString() + "/auth/admin/master/console/whoami";

        JsonNode jsonNode = SimpleHttp.doGet(whoAmiUrl, client).auth(accessToken.getToken()).asJson();
        assertNotNull(jsonNode.get("realm"));
        assertNotNull(jsonNode.get("userId"));
    }
}
 
Example #5
Source File: AuthzClientRequestFactory.java    From devconf2019-authz with Apache License 2.0 6 votes vote down vote up
@Override
protected void postProcessHttpRequest(HttpUriRequest request) {
    KeycloakSecurityContext context = this.getKeycloakSecurityContext();

    // TODO: Ideally should do it all automatically by some provided adapter/utility
    String currentRpt = rptStore.getRpt(context);
    if (currentRpt == null) {
        // Fallback to access token
        currentRpt = context.getTokenString();
    } else {
        AccessToken parsedRpt = rptStore.getParsedRpt(context);
        if (!parsedRpt.isActive(10)) {
            // Just delete RPT and use accessToken instead. TODO: Will be good to have some "built-in" way to refresh RPT for clients
            log.info("Deleting expired RPT. Will need to obtain new when needed");
            rptStore.deleteCurrentRpt(servletRequest);
            currentRpt = context.getTokenString();
        }
    }

    request.setHeader(AUTHORIZATION_HEADER, "Bearer " + currentRpt);
}
 
Example #6
Source File: CompositeImportRoleTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void testRealmOnlyWithUserCompositeAppComposite() throws Exception {
    oauth.realm("test");
    oauth.clientId("REALM_COMPOSITE_1_APPLICATION");
    oauth.doLogin("REALM_COMPOSITE_1_USER", "password");

    String code = oauth.getCurrentQuery().get(OAuth2Constants.CODE);
    AccessTokenResponse response = oauth.doAccessTokenRequest(code, "password");

    Assert.assertEquals(200, response.getStatusCode());

    Assert.assertEquals("bearer", response.getTokenType());

    AccessToken token = oauth.verifyToken(response.getAccessToken());

    Assert.assertEquals(getUserId("REALM_COMPOSITE_1_USER"), token.getSubject());

    Assert.assertEquals(2, token.getRealmAccess().getRoles().size());
    Assert.assertTrue(token.getRealmAccess().isUserInRole("REALM_COMPOSITE_1"));
    Assert.assertTrue(token.getRealmAccess().isUserInRole("REALM_ROLE_1"));
}
 
Example #7
Source File: RoleResolveUtil.java    From keycloak with Apache License 2.0 6 votes vote down vote up
private static void addToToken(AccessToken token, RoleModel role) {
    AccessToken.Access access = null;
    if (role.getContainer() instanceof RealmModel) {
        access = token.getRealmAccess();
        if (token.getRealmAccess() == null) {
            access = new AccessToken.Access();
            token.setRealmAccess(access);
        } else if (token.getRealmAccess().getRoles() != null && token.getRealmAccess().isUserInRole(role.getName()))
            return;

    } else {
        ClientModel app = (ClientModel) role.getContainer();
        access = token.getResourceAccess(app.getClientId());
        if (access == null) {
            access = token.addAccess(app.getClientId());
            if (app.isSurrogateAuthRequired()) access.verifyCaller(true);
        } else if (access.isUserInRole(role.getName())) return;

    }
    access.addRole(role.getName());
}
 
Example #8
Source File: CompositeRoleTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void testRealmAppCompositeUser() throws Exception {
    oauth.realm("test");
    oauth.clientId("APP_ROLE_APPLICATION");
    oauth.doLogin("REALM_APP_COMPOSITE_USER", "password");

    String code = oauth.getCurrentQuery().get(OAuth2Constants.CODE);
    AccessTokenResponse response = oauth.doAccessTokenRequest(code, "password");

    Assert.assertEquals(200, response.getStatusCode());

    Assert.assertEquals("bearer", response.getTokenType());

    AccessToken token = oauth.verifyToken(response.getAccessToken());

    Assert.assertEquals(getUserId("REALM_APP_COMPOSITE_USER"), token.getSubject());

    Assert.assertEquals(1, token.getResourceAccess("APP_ROLE_APPLICATION").getRoles().size());
    Assert.assertTrue(token.getResourceAccess("APP_ROLE_APPLICATION").isUserInRole("APP_ROLE_1"));

    AccessTokenResponse refreshResponse = oauth.doRefreshTokenRequest(response.getRefreshToken(), "password");
    Assert.assertEquals(200, refreshResponse.getStatusCode());
}
 
Example #9
Source File: UmaGrantTypeTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void testObtainRptUsingAccessToken() throws Exception {
    AccessTokenResponse accessTokenResponse = getAuthzClient().obtainAccessToken("marta", "password");
    AuthorizationResponse response = authorize(null, null, null, null, accessTokenResponse.getToken(), null, null, new PermissionRequest("Resource A", "ScopeA", "ScopeB"));
    String rpt = response.getToken();

    assertNotNull(rpt);
    assertFalse(response.isUpgraded());

    AccessToken accessToken = toAccessToken(rpt);
    AccessToken.Authorization authorization = accessToken.getAuthorization();

    assertNotNull(authorization);

    Collection<Permission> permissions = authorization.getPermissions();

    assertNotNull(permissions);
    assertPermissions(permissions, "Resource A", "ScopeA", "ScopeB");
    assertTrue(permissions.isEmpty());
}
 
Example #10
Source File: AuthzClientCredentialsTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void testPermissionWhenResourceServerIsCurrentUser() throws Exception {
    ClientsResource clients = getAdminClient().realm("authz-test-session").clients();
    ClientRepresentation clientRepresentation = clients.findByClientId("resource-server-test").get(0);
    List<UserSessionRepresentation> userSessions = clients.get(clientRepresentation.getId()).getUserSessions(-1, -1);

    assertEquals(0, userSessions.size());

    AuthzClient authzClient = getAuthzClient("default-session-keycloak.json");
    org.keycloak.authorization.client.resource.AuthorizationResource authorization = authzClient.authorization(authzClient.obtainAccessToken().getToken());
    AuthorizationResponse response = authorization.authorize();
    AccessToken accessToken = toAccessToken(response.getToken());

    assertEquals(1, accessToken.getAuthorization().getPermissions().size());
    assertEquals("Default Resource", accessToken.getAuthorization().getPermissions().iterator().next().getResourceName());
}
 
Example #11
Source File: CompositeImportRoleTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void testRealmOnlyWithUserRoleAppComposite() throws Exception {
    oauth.realm("test");
    oauth.clientId("REALM_COMPOSITE_1_APPLICATION");
    oauth.doLogin("REALM_ROLE_1_USER", "password");

    String code = oauth.getCurrentQuery().get(OAuth2Constants.CODE);
    AccessTokenResponse response = oauth.doAccessTokenRequest(code, "password");

    Assert.assertEquals(200, response.getStatusCode());

    Assert.assertEquals("bearer", response.getTokenType());

    AccessToken token = oauth.verifyToken(response.getAccessToken());

    Assert.assertEquals(getUserId("REALM_ROLE_1_USER"), token.getSubject());

    Assert.assertEquals(1, token.getRealmAccess().getRoles().size());
    Assert.assertTrue(token.getRealmAccess().isUserInRole("REALM_ROLE_1"));
}
 
Example #12
Source File: AdapterUtils.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public static String getPrincipalName(KeycloakDeployment deployment, AccessToken token) {
    String attr = "sub";
    if (deployment.getPrincipalAttribute() != null) attr = deployment.getPrincipalAttribute();
    String name = null;

    if ("sub".equals(attr)) {
        name = token.getSubject();
    } else if ("email".equals(attr)) {
        name = token.getEmail();
    } else if ("preferred_username".equals(attr)) {
        name = token.getPreferredUsername();
    } else if ("name".equals(attr)) {
        name = token.getName();
    } else if ("given_name".equals(attr)) {
        name = token.getGivenName();
    } else if ("family_name".equals(attr)) {
        name = token.getFamilyName();
    } else if ("nickname".equals(attr)) {
        name = token.getNickName();
    }
    if (name == null) name = token.getSubject();
    return name;
}
 
Example #13
Source File: GSSCredentialsClient.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public static LDAPUser getUserFromLDAP(HttpServletRequest req) throws Exception {
    KeycloakPrincipal keycloakPrincipal = (KeycloakPrincipal) req.getUserPrincipal();
    AccessToken accessToken = keycloakPrincipal.getKeycloakSecurityContext().getToken();
    String username = accessToken.getPreferredUsername();

    // Retrieve kerberos credential from accessToken and deserialize it
    String serializedGssCredential = (String) accessToken.getOtherClaims().get(KerberosConstants.GSS_DELEGATION_CREDENTIAL);
    GSSCredential deserializedGssCredential = KerberosSerializationUtils.deserializeCredential(serializedGssCredential);

    // First try to invoke without gssCredential. It should fail. This is here just for illustration purposes
    try {
        invokeLdap(null, username);
        throw new RuntimeException("Not expected to authenticate to LDAP without credential");
    } catch (NamingException nse) {
        System.out.println("GSSCredentialsClient: Expected exception: " + nse.getMessage());
    }

    return invokeLdap(deserializedGssCredential, username);
}
 
Example #14
Source File: MyResourcesTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
private ResourceRepresentation createResource(AuthzClient authzClient, AuthorizationResource authorization, int i) {
    ResourceRepresentation resource = new ResourceRepresentation();

    resource.setOwnerManagedAccess(true);

    try {
        final byte[] content = new JWSInput(authzClient.obtainAccessToken("jdoe", PASSWORD).getToken()).getContent();
        final AccessToken accessToken = JsonSerialization.readValue(content, AccessToken.class);
        resource.setOwner(accessToken.getSubject());
    }
    catch (Exception e) {
        throw new RuntimeException(e);
    }

    resource.setName("Resource " + i);
    resource.setDisplayName("Display Name " + i);
    resource.setIconUri("Icon Uri " + i);
    resource.addScope("Scope A", "Scope B", "Scope C", "Scope D");
    resource.setUri("http://resourceServer.com/resources/" + i);

    try (Response response1 = authorization.resources().create(resource)) {
        resource.setId(response1.readEntity(ResourceRepresentation.class).getId());
    }
    return resource;
}
 
Example #15
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 #16
Source File: AccessTokenDuplicateEmailsTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
public void loginWithSecondDuplicateEmailUser() throws Exception {
    oauth.doLogin("duplicate-email-user2", "password");

    String code = oauth.getCurrentQuery().get(OAuth2Constants.CODE);
    OAuthClient.AccessTokenResponse response = oauth.doAccessTokenRequest(code, "password");

    assertEquals(200, response.getStatusCode());
    
    AccessToken token = oauth.verifyToken(response.getAccessToken());
    
    assertEquals(findUserByUsername(adminClient.realm("test-duplicate-emails"), "duplicate-email-user2").getId(), token.getSubject());
    assertEquals("duplicate-email-user@localhost", token.getEmail());
}
 
Example #17
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 #18
Source File: AllowedWebOriginsProtocolMapper.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public AccessToken transformAccessToken(AccessToken token, ProtocolMapperModel mappingModel, KeycloakSession session,
                                        UserSessionModel userSession, ClientSessionContext clientSessionCtx) {
    ClientModel client = clientSessionCtx.getClientSession().getClient();

    Set<String> allowedOrigins = client.getWebOrigins();
    if (allowedOrigins != null && !allowedOrigins.isEmpty()) {
        token.setAllowedOrigins(WebOriginsUtils.resolveValidWebOrigins(session, client));
    }

    return token;
}
 
Example #19
Source File: PolicyEnforcerClaimsTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private OIDCHttpFacade createHttpFacade(String path, String method, String token, Map<String, List<String>> headers, Map<String, List<String>> parameters, InputStream requestBody) {
    return new OIDCHttpFacade() {
        Request request;
        Response response;

        @Override
        public KeycloakSecurityContext getSecurityContext() {
            AccessToken accessToken;
            try {
                accessToken = new JWSInput(token).readJsonContent(AccessToken.class);
            } catch (JWSInputException cause) {
                throw new RuntimeException(cause);
            }
            return new KeycloakSecurityContext(token, accessToken, null, null);
        }

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

        @Override
        public Response getResponse() {
            if (response == null) {
                response = createHttpResponse(headers);
            }
            return response;
        }

        @Override
        public X509Certificate[] getCertificateChain() {
            return new X509Certificate[0];
        }
    };
}
 
Example #20
Source File: KeycloakOauthPolicy.java    From apiman-plugins with Apache License 2.0 5 votes vote down vote up
private void forwardHeaders(ApiRequest request, KeycloakOauthConfigBean config, String rawToken,
        AccessToken parsedToken) {
    for (ForwardAuthInfo entry : config.getForwardAuthInfo()) {
        String headerValue = isToken(entry.getField()) ? rawToken :
            ClaimLookup.getClaim(parsedToken, entry.getField());
        // Add the header if we've been able to look it up, else it'll just be empty.
        request.getHeaders().put(entry.getHeader(), headerValue);
    }
}
 
Example #21
Source File: AbstractAuthzTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
protected AccessToken toAccessToken(String rpt) {
    AccessToken accessToken;

    try {
        accessToken = new JWSInput(rpt).readJsonContent(AccessToken.class);
    } catch (JWSInputException cause) {
        throw new RuntimeException("Failed to deserialize RPT", cause);
    }
    return accessToken;
}
 
Example #22
Source File: ClientScopeEvaluateResource.java    From keycloak with Apache License 2.0 5 votes vote down vote up
/**
 * Create JSON with payload of example access token
 *
 * @return
 */
@GET
@Path("generate-example-access-token")
@NoCache
@Produces(MediaType.APPLICATION_JSON)
public AccessToken generateExampleAccessToken(@QueryParam("scope") String scopeParam, @QueryParam("userId") String userId) {
    auth.clients().requireView(client);

    if (userId == null) {
        throw new NotFoundException("No userId provided");
    }

    UserModel user = session.users().getUserById(userId, realm);
    if (user == null) {
        throw new NotFoundException("No user found");
    }

    logger.debugf("generateExampleAccessToken invoked. User: %s, Scope param: %s", user.getUsername(), scopeParam);

    AccessToken token = generateToken(user, scopeParam);
    return token;
}
 
Example #23
Source File: AbstractUser.java    From keycloak-dropwizard-integration with Apache License 2.0 5 votes vote down vote up
private Set<String> selectResourceRoles(KeycloakResource keycloakResource) {
    Set<String> roles = new HashSet<>();

    AccessToken.Access resourceAccess =
            securityContext.getToken().getResourceAccess(keycloakResource.getResource());
    if (resourceAccess != null && resourceAccess.getRoles() != null) {
        roles.addAll(resourceAccess.getRoles());
    }
    return Collections.unmodifiableSet(roles);
}
 
Example #24
Source File: AbstractMigrationTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
protected void testCredentialsMigratedToNewFormat() {
    log.info("testing user's credentials migrated to new format with secretData and credentialData");

    // Try to login with password+otp after the migration
    try {
        oauth.realm(MIGRATION);
        oauth.clientId("migration-test-client");

        TimeBasedOTP otpGenerator = new TimeBasedOTP("HmacSHA1", 8, 40, 1);
        String otp = otpGenerator.generateTOTP("dSdmuHLQhkm54oIm0A0S");

        // Try invalid password first
        OAuthClient.AccessTokenResponse response = oauth.doGrantAccessTokenRequest("secret",
                "migration-test-user", "password", otp);
        Assert.assertNull(response.getAccessToken());
        Assert.assertNotNull(response.getError());

        // Try invalid OTP then
        response = oauth.doGrantAccessTokenRequest("secret",
                "migration-test-user", "password2", "invalid");
        Assert.assertNull(response.getAccessToken());
        Assert.assertNotNull(response.getError());

        // Try successful login now
        response = oauth.doGrantAccessTokenRequest("secret",
                "migration-test-user", "password2", otp);
        Assert.assertNull(response.getError());
        AccessToken accessToken = oauth.verifyToken(response.getAccessToken());
        assertEquals("migration-test-user", accessToken.getPreferredUsername());
    } catch (Exception e) {
        throw new AssertionError("Failed to login with user 'migration-test-user' after migration", e);
    }
}
 
Example #25
Source File: KeycloakOauthPolicyLegacyTest.java    From apiman-plugins with Apache License 2.0 5 votes vote down vote up
@Before
public void initTest() {
    MockitoAnnotations.initMocks(this);

    token = new AccessToken();

    AccessToken realm = token.type("Bearer").subject("CN=Client").issuer("apiman-realm"); // KC seems to use issuer for realm?

    realm.addAccess("apiman-api").addRole("apiman-gateway-user-role").addRole("a-nother-role");
    realm.setRealmAccess(new Access().addRole("lets-use-a-realm-role"));

    keycloakOauthPolicy = new KeycloakOauthPolicy();
    config = new KeycloakOauthConfigBean();
    config.setRequireOauth(true);
    config.setStripTokens(false);
    config.setBlacklistUnsafeTokens(false);
    config.setRequireTransportSecurity(false);

    forwardRoles = new ForwardRoles();
    config.setForwardRoles(forwardRoles);

    apiRequest = new ApiRequest();

    // Set up components.
    // Failure factory
    given(mContext.getComponent(IPolicyFailureFactoryComponent.class)).
        willReturn(new DefaultPolicyFailureFactoryComponent());
    // Data store
    given(mContext.getComponent(ISharedStateComponent.class)).
        willReturn(new InMemorySharedStateComponent());
}
 
Example #26
Source File: DemoServletsAdapterTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
public void testTokenMinTTL() {
    // Login
    tokenMinTTLPage.navigateTo();
    assertTrue(testRealmLoginPage.form().isUsernamePresent());
    assertCurrentUrlStartsWithLoginUrlOf(testRealmPage);
    testRealmLoginPage.form().login("[email protected]", "password");
    assertCurrentUrlEquals(tokenMinTTLPage);

    // Get time of token
    AccessToken token = tokenMinTTLPage.getAccessToken();
    int tokenIssued1 = token.getIssuedAt();

    // Sets 5 minutes offset and assert access token will be still the same
    setAdapterAndServerTimeOffset(300, tokenMinTTLPage.toString());
    tokenMinTTLPage.navigateTo();
    token = tokenMinTTLPage.getAccessToken();
    int tokenIssued2 = token.getIssuedAt();
    Assert.assertEquals(tokenIssued1, tokenIssued2);
    assertFalse(token.isExpired());

    // Sets 9 minutes offset and assert access token will be refreshed (accessTokenTimeout is 10 minutes, token-min-ttl is 2 minutes. Hence 8 minutes or more should be sufficient)
    setAdapterAndServerTimeOffset(540, tokenMinTTLPage.toString());
    tokenMinTTLPage.navigateTo();
    token = tokenMinTTLPage.getAccessToken();
    int tokenIssued3 = token.getIssuedAt();
    Assert.assertTrue(tokenIssued3 > tokenIssued1);

    // Revert times
    setAdapterAndServerTimeOffset(0, tokenMinTTLPage.toString());
}
 
Example #27
Source File: RSAVerifierTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
public void testExpirationBad() {
    token.expiration(Time.currentTime() - 100);

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

    AccessToken v = null;
    try {
        v = verifySkeletonKeyToken(encoded);
        Assert.fail();
    } catch (VerificationException ignored) {
    }
}
 
Example #28
Source File: KeycloakOauthPolicy.java    From apiman-plugins with Apache License 2.0 5 votes vote down vote up
private void delegateKerberosTicket(ApiRequest request, KeycloakOauthConfigBean config,
        AccessToken parsedToken) {
    String serializedGssCredential = (String) parsedToken.getOtherClaims().get(
            KerberosConstants.GSS_DELEGATION_CREDENTIAL);

    if (config.getDelegateKerberosTicket()) {
        request.getHeaders().put(AUTHORIZATION_KEY, NEGOTIATE + serializedGssCredential);
    }
}
 
Example #29
Source File: OIDCPublicKeyRotationAdapterTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private void loginToTokenMinTtlApp() {
    tokenMinTTLPage.navigateTo();
    assertTrue(testRealmLoginPage.form().isUsernamePresent());
    assertCurrentUrlStartsWithLoginUrlOf(testRealmPage);
    testRealmLoginPage.form().login("[email protected]", "password");
    assertCurrentUrlEquals(tokenMinTTLPage);

    AccessToken token = tokenMinTTLPage.getAccessToken();
    Assert.assertEquals("[email protected]", token.getPreferredUsername());
}
 
Example #30
Source File: AbstractOIDCProtocolMapper.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public AccessToken transformAccessToken(AccessToken token, ProtocolMapperModel mappingModel, KeycloakSession session,
                                        UserSessionModel userSession, ClientSessionContext clientSessionCtx) {

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

    setClaim(token, mappingModel, userSession, session, clientSessionCtx);
    return token;
}