Search in sources :

Example 46 with JWSInput

use of org.keycloak.jose.jws.JWSInput in project keycloak by keycloak.

the class RefreshTokenTest method refreshToken.

private void refreshToken(String expectedRefreshAlg, String expectedAccessAlg, String expectedIdTokenAlg) throws Exception {
    oauth.doLogin("test-user@localhost", "password");
    EventRepresentation loginEvent = events.expectLogin().assertEvent();
    String sessionId = loginEvent.getSessionId();
    String codeId = loginEvent.getDetails().get(Details.CODE_ID);
    String code = oauth.getCurrentQuery().get(OAuth2Constants.CODE);
    OAuthClient.AccessTokenResponse tokenResponse = oauth.doAccessTokenRequest(code, "password");
    JWSHeader header = new JWSInput(tokenResponse.getAccessToken()).getHeader();
    assertEquals(expectedAccessAlg, header.getAlgorithm().name());
    assertEquals("JWT", header.getType());
    assertNull(header.getContentType());
    header = new JWSInput(tokenResponse.getIdToken()).getHeader();
    assertEquals(expectedIdTokenAlg, header.getAlgorithm().name());
    assertEquals("JWT", header.getType());
    assertNull(header.getContentType());
    header = new JWSInput(tokenResponse.getRefreshToken()).getHeader();
    assertEquals(expectedRefreshAlg, header.getAlgorithm().name());
    assertEquals("JWT", header.getType());
    assertNull(header.getContentType());
    AccessToken token = oauth.verifyToken(tokenResponse.getAccessToken());
    String refreshTokenString = tokenResponse.getRefreshToken();
    RefreshToken refreshToken = oauth.parseRefreshToken(refreshTokenString);
    EventRepresentation tokenEvent = events.expectCodeToToken(codeId, sessionId).assertEvent();
    assertNotNull(refreshTokenString);
    assertEquals("Bearer", tokenResponse.getTokenType());
    assertEquals(sessionId, refreshToken.getSessionState());
    setTimeOffset(2);
    OAuthClient.AccessTokenResponse response = oauth.doRefreshTokenRequest(refreshTokenString, "password");
    if (response.getError() != null || response.getErrorDescription() != null) {
        log.debugf("Refresh token error: %s, error description: %s", response.getError(), response.getErrorDescription());
    }
    AccessToken refreshedToken = oauth.verifyToken(response.getAccessToken());
    RefreshToken refreshedRefreshToken = oauth.parseRefreshToken(response.getRefreshToken());
    assertEquals(200, response.getStatusCode());
    assertEquals(sessionId, refreshedToken.getSessionState());
    assertEquals(sessionId, refreshedRefreshToken.getSessionState());
    Assert.assertNotEquals(token.getId(), refreshedToken.getId());
    Assert.assertNotEquals(refreshToken.getId(), refreshedRefreshToken.getId());
    assertEquals("Bearer", response.getTokenType());
    assertEquals(findUserByUsername(adminClient.realm("test"), "test-user@localhost").getId(), refreshedToken.getSubject());
    Assert.assertNotEquals("test-user@localhost", refreshedToken.getSubject());
    EventRepresentation refreshEvent = events.expectRefresh(tokenEvent.getDetails().get(Details.REFRESH_TOKEN_ID), sessionId).assertEvent();
    Assert.assertNotEquals(tokenEvent.getDetails().get(Details.TOKEN_ID), refreshEvent.getDetails().get(Details.TOKEN_ID));
    Assert.assertNotEquals(tokenEvent.getDetails().get(Details.REFRESH_TOKEN_ID), refreshEvent.getDetails().get(Details.UPDATED_REFRESH_TOKEN_ID));
    setTimeOffset(0);
}
Also used : RefreshToken(org.keycloak.representations.RefreshToken) OAuthClient(org.keycloak.testsuite.util.OAuthClient) AccessToken(org.keycloak.representations.AccessToken) EventRepresentation(org.keycloak.representations.idm.EventRepresentation) JWSInput(org.keycloak.jose.jws.JWSInput) JWSHeader(org.keycloak.jose.jws.JWSHeader)

Example 47 with JWSInput

use of org.keycloak.jose.jws.JWSInput in project keycloak by keycloak.

the class PermissionManagementTest method assertPersistence.

private void assertPersistence(PermissionResponse response, ResourceRepresentation resource, String... scopeNames) throws Exception {
    String ticket = response.getTicket();
    assertNotNull(ticket);
    int expectedPermissions = scopeNames.length > 0 ? scopeNames.length : 1;
    List<PermissionTicketRepresentation> tickets = getAuthzClient().protection().permission().findByResource(resource.getId());
    assertEquals(expectedPermissions, tickets.size());
    PermissionTicketToken token = new JWSInput(ticket).readJsonContent(PermissionTicketToken.class);
    List<Permission> tokenPermissions = token.getPermissions();
    assertNotNull(tokenPermissions);
    assertEquals(expectedPermissions, scopeNames.length > 0 ? scopeNames.length : tokenPermissions.size());
    Iterator<Permission> permissionIterator = tokenPermissions.iterator();
    while (permissionIterator.hasNext()) {
        Permission resourcePermission = permissionIterator.next();
        long count = tickets.stream().filter(representation -> representation.getResource().equals(resourcePermission.getResourceId())).count();
        if (count == (scopeNames.length > 0 ? scopeNames.length : 1)) {
            permissionIterator.remove();
        }
    }
    assertTrue(tokenPermissions.isEmpty());
    ArrayList<PermissionTicketRepresentation> expectedTickets = new ArrayList<>(tickets);
    Iterator<PermissionTicketRepresentation> ticketIterator = expectedTickets.iterator();
    while (ticketIterator.hasNext()) {
        PermissionTicketRepresentation ticketRep = ticketIterator.next();
        assertFalse(ticketRep.isGranted());
        if (ticketRep.getScope() != null) {
            ScopeRepresentation scope = getClient(getRealm()).authorization().scopes().scope(ticketRep.getScope()).toRepresentation();
            if (Arrays.asList(scopeNames).contains(scope.getName())) {
                ticketIterator.remove();
            }
        } else if (ticketRep.getResource().equals(resource.getId())) {
            ticketIterator.remove();
        }
    }
    assertTrue(expectedTickets.isEmpty());
}
Also used : Arrays(java.util.Arrays) ResourceRepresentation(org.keycloak.representations.idm.authorization.ResourceRepresentation) AuthServerContainerExclude(org.keycloak.testsuite.arquillian.annotation.AuthServerContainerExclude) Permission(org.keycloak.representations.idm.authorization.Permission) Matchers.not(org.hamcrest.Matchers.not) AuthorizationResource(org.keycloak.admin.client.resource.AuthorizationResource) HttpResponseException(org.keycloak.authorization.client.util.HttpResponseException) AuthzClient(org.keycloak.authorization.client.AuthzClient) ArrayList(java.util.ArrayList) Assert.assertThat(org.junit.Assert.assertThat) HashSet(java.util.HashSet) Assert.fail(org.junit.Assert.fail) PermissionTicketToken(org.keycloak.representations.idm.authorization.PermissionTicketToken) ScopeRepresentation(org.keycloak.representations.idm.authorization.ScopeRepresentation) AuthServer(org.keycloak.testsuite.arquillian.annotation.AuthServerContainerExclude.AuthServer) ResourceScopesResource(org.keycloak.admin.client.resource.ResourceScopesResource) JWSInput(org.keycloak.jose.jws.JWSInput) Matchers.empty(org.hamcrest.Matchers.empty) UserRepresentation(org.keycloak.representations.idm.UserRepresentation) Iterator(java.util.Iterator) Assert.assertNotNull(org.junit.Assert.assertNotNull) Collection(java.util.Collection) AuthorizationRequest(org.keycloak.representations.idm.authorization.AuthorizationRequest) Assert.assertTrue(org.junit.Assert.assertTrue) Test(org.junit.Test) Collectors(java.util.stream.Collectors) PermissionRequest(org.keycloak.representations.idm.authorization.PermissionRequest) PermissionTicketRepresentation(org.keycloak.representations.idm.authorization.PermissionTicketRepresentation) List(java.util.List) Matchers.hasItem(org.hamcrest.Matchers.hasItem) Assert.assertFalse(org.junit.Assert.assertFalse) Matchers.is(org.hamcrest.Matchers.is) Collections(java.util.Collections) Assert.assertEquals(org.junit.Assert.assertEquals) PermissionResponse(org.keycloak.representations.idm.authorization.PermissionResponse) PermissionTicketToken(org.keycloak.representations.idm.authorization.PermissionTicketToken) ArrayList(java.util.ArrayList) JWSInput(org.keycloak.jose.jws.JWSInput) PermissionTicketRepresentation(org.keycloak.representations.idm.authorization.PermissionTicketRepresentation) Permission(org.keycloak.representations.idm.authorization.Permission) ScopeRepresentation(org.keycloak.representations.idm.authorization.ScopeRepresentation)

Example 48 with JWSInput

use of org.keycloak.jose.jws.JWSInput in project keycloak by keycloak.

the class ConflictingScopePermissionTest method getEntitlements.

private Collection<Permission> getEntitlements(String username, String password) {
    AuthzClient authzClient = getAuthzClient();
    AuthorizationResponse response = authzClient.authorization(username, password).authorize();
    AccessToken accessToken;
    try {
        accessToken = new JWSInput(response.getToken()).readJsonContent(AccessToken.class);
    } catch (JWSInputException cause) {
        throw new RuntimeException("Failed to deserialize RPT", cause);
    }
    AccessToken.Authorization authorization = accessToken.getAuthorization();
    assertNotNull("RPT does not contain any authorization data", authorization);
    return authorization.getPermissions();
}
Also used : AuthzClient(org.keycloak.authorization.client.AuthzClient) AccessToken(org.keycloak.representations.AccessToken) JWSInputException(org.keycloak.jose.jws.JWSInputException) JWSInput(org.keycloak.jose.jws.JWSInput) AuthorizationResponse(org.keycloak.representations.idm.authorization.AuthorizationResponse)

Example 49 with JWSInput

use of org.keycloak.jose.jws.JWSInput in project keycloak by keycloak.

the class ResourcesRestServiceTest method before.

@Override
public void before() {
    super.before();
    ClientResource resourceServer = getResourceServer();
    authzClient = createAuthzClient(resourceServer.toRepresentation());
    AuthorizationResource authorization = resourceServer.authorization();
    for (int i = 0; i < 30; i++) {
        ResourceRepresentation resource = new ResourceRepresentation();
        resource.setOwnerManagedAccess(true);
        try {
            resource.setOwner(JsonSerialization.readValue(new JWSInput(tokenUtil.getToken()).getContent(), AccessToken.class).getSubject());
        } catch (Exception cause) {
            throw new RuntimeException("Failed to parse access token", cause);
        }
        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());
            assertTrue(resource.getId() != null);
        }
        for (String scope : Arrays.asList("Scope A", "Scope B")) {
            PermissionTicketRepresentation ticket = new PermissionTicketRepresentation();
            ticket.setGranted(true);
            ticket.setOwner(resource.getOwner().getId());
            ticket.setRequesterName(userNames.get(i % userNames.size()));
            ticket.setResource(resource.getId());
            ticket.setScopeName(scope);
            authzClient.protection("test-user@localhost", "password").permission().create(ticket);
        }
    }
}
Also used : Response(javax.ws.rs.core.Response) PermissionTicketRepresentation(org.keycloak.representations.idm.authorization.PermissionTicketRepresentation) ClientResource(org.keycloak.admin.client.resource.ClientResource) JWSInput(org.keycloak.jose.jws.JWSInput) AuthorizationResource(org.keycloak.admin.client.resource.AuthorizationResource) IOException(java.io.IOException) ResourceRepresentation(org.keycloak.representations.idm.authorization.ResourceRepresentation)

Example 50 with JWSInput

use of org.keycloak.jose.jws.JWSInput in project keycloak by keycloak.

the class AssertAdminEvents method defaultAuthDetails.

private AuthDetailsRepresentation defaultAuthDetails() {
    String accessTokenString = context.getAdminClient().tokenManager().getAccessTokenString();
    try {
        JWSInput input = new JWSInput(accessTokenString);
        AccessToken token = input.readJsonContent(AccessToken.class);
        AuthDetailsRepresentation authDetails = new AuthDetailsRepresentation();
        String realmId = token.getIssuer().substring(token.getIssuer().lastIndexOf('/') + 1);
        authDetails.setRealmId(realmId);
        authDetails.setUserId(token.getSubject());
        return authDetails;
    } catch (JWSInputException jwe) {
        throw new RuntimeException(jwe);
    }
}
Also used : AccessToken(org.keycloak.representations.AccessToken) JWSInputException(org.keycloak.jose.jws.JWSInputException) JWSInput(org.keycloak.jose.jws.JWSInput) AuthDetailsRepresentation(org.keycloak.representations.idm.AuthDetailsRepresentation)

Aggregations

JWSInput (org.keycloak.jose.jws.JWSInput)62 AccessToken (org.keycloak.representations.AccessToken)29 OAuthClient (org.keycloak.testsuite.util.OAuthClient)20 JWSInputException (org.keycloak.jose.jws.JWSInputException)16 Test (org.junit.Test)15 JWSHeader (org.keycloak.jose.jws.JWSHeader)11 Response (javax.ws.rs.core.Response)10 RefreshToken (org.keycloak.representations.RefreshToken)10 EventRepresentation (org.keycloak.representations.idm.EventRepresentation)9 ClientRepresentation (org.keycloak.representations.idm.ClientRepresentation)8 IOException (java.io.IOException)7 VerificationException (org.keycloak.common.VerificationException)7 JsonWebToken (org.keycloak.representations.JsonWebToken)7 JsonNode (com.fasterxml.jackson.databind.JsonNode)5 PublicKey (java.security.PublicKey)5 AccessTokenResponse (org.keycloak.representations.AccessTokenResponse)5 Client (javax.ws.rs.client.Client)4 IDToken (org.keycloak.representations.IDToken)4 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)3 List (java.util.List)3