Search in sources :

Example 36 with JWSInput

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

the class SkeletonKeyTokenTest method testRSA.

@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()));
}
Also used : KeyPair(java.security.KeyPair) AccessToken(org.keycloak.representations.AccessToken) JWSInput(org.keycloak.jose.jws.JWSInput) JWSBuilder(org.keycloak.jose.jws.JWSBuilder) Test(org.junit.Test)

Example 37 with JWSInput

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

the class OIDCIdentityProvider method validateToken.

protected JsonWebToken validateToken(String encodedToken, boolean ignoreAudience) {
    if (encodedToken == null) {
        throw new IdentityBrokerException("No token from server.");
    }
    JsonWebToken token;
    try {
        JWSInput jws = new JWSInput(encodedToken);
        if (!verify(jws)) {
            throw new IdentityBrokerException("token signature validation failed");
        }
        token = jws.readJsonContent(JsonWebToken.class);
    } catch (JWSInputException e) {
        throw new IdentityBrokerException("Invalid token", e);
    }
    String iss = token.getIssuer();
    if (!token.isActive(getConfig().getAllowedClockSkew())) {
        throw new IdentityBrokerException("Token is no longer valid");
    }
    if (!ignoreAudience && !token.hasAudience(getConfig().getClientId())) {
        throw new IdentityBrokerException("Wrong audience from token.");
    }
    if (!ignoreAudience && (token.getIssuedFor() != null && !getConfig().getClientId().equals(token.getIssuedFor()))) {
        throw new IdentityBrokerException("Token issued for does not match client id");
    }
    String trustedIssuers = getConfig().getIssuer();
    if (trustedIssuers != null && trustedIssuers.length() > 0) {
        String[] issuers = trustedIssuers.split(",");
        for (String trustedIssuer : issuers) {
            if (iss != null && iss.equals(trustedIssuer.trim())) {
                return token;
            }
        }
        throw new IdentityBrokerException("Wrong issuer from token. Got: " + iss + " expected: " + getConfig().getIssuer());
    }
    return token;
}
Also used : IdentityBrokerException(org.keycloak.broker.provider.IdentityBrokerException) JWSInputException(org.keycloak.jose.jws.JWSInputException) JWSInput(org.keycloak.jose.jws.JWSInput) JsonWebToken(org.keycloak.representations.JsonWebToken)

Example 38 with JWSInput

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

the class AdminController method showTokens.

@RequestMapping(path = "/TokenServlet", method = RequestMethod.GET)
public String showTokens(WebRequest req, Model model, @RequestParam Map<String, String> attributes) throws IOException {
    String timeOffset = attributes.get("timeOffset");
    if (!StringUtils.isEmpty(timeOffset)) {
        int offset;
        try {
            offset = Integer.parseInt(timeOffset, 10);
        } catch (NumberFormatException e) {
            offset = 0;
        }
        Time.setOffset(offset);
    }
    RefreshableKeycloakSecurityContext ctx = (RefreshableKeycloakSecurityContext) req.getAttribute(KeycloakSecurityContext.class.getName(), WebRequest.SCOPE_REQUEST);
    String accessTokenPretty = JsonSerialization.writeValueAsPrettyString(ctx.getToken());
    RefreshToken refreshToken;
    try {
        refreshToken = new JWSInput(ctx.getRefreshToken()).readJsonContent(RefreshToken.class);
    } catch (JWSInputException e) {
        throw new IOException(e);
    }
    String refreshTokenPretty = JsonSerialization.writeValueAsPrettyString(refreshToken);
    model.addAttribute("accessToken", accessTokenPretty);
    model.addAttribute("refreshToken", refreshTokenPretty);
    model.addAttribute("accessTokenString", ctx.getTokenString());
    return "tokens";
}
Also used : RefreshToken(org.keycloak.representations.RefreshToken) RefreshableKeycloakSecurityContext(org.keycloak.adapters.RefreshableKeycloakSecurityContext) JWSInputException(org.keycloak.jose.jws.JWSInputException) JWSInput(org.keycloak.jose.jws.JWSInput) IOException(java.io.IOException) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 39 with JWSInput

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

the class MyResourcesTest method createResource.

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;
}
Also used : Response(javax.ws.rs.core.Response) AccessToken(org.keycloak.representations.AccessToken) JWSInput(org.keycloak.jose.jws.JWSInput) IOException(java.io.IOException) NoSuchElementException(org.openqa.selenium.NoSuchElementException) ResourceRepresentation(org.keycloak.representations.idm.authorization.ResourceRepresentation)

Example 40 with JWSInput

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

the class ClientPoliciesTest method testSecureResponseTypeExecutor.

@Test
public void testSecureResponseTypeExecutor() throws Exception {
    // register profiles
    String json = (new ClientProfilesBuilder()).addProfile((new ClientProfileBuilder()).createProfile(PROFILE_NAME, "O Primeiro Perfil").addExecutor(SecureResponseTypeExecutorFactory.PROVIDER_ID, null).toRepresentation()).toString();
    updateProfiles(json);
    // register policies
    json = (new ClientPoliciesBuilder()).addPolicy((new ClientPolicyBuilder()).createPolicy(POLICY_NAME, "A Primeira Politica", Boolean.TRUE).addCondition(ClientRolesConditionFactory.PROVIDER_ID, createClientRolesConditionConfig(Arrays.asList(SAMPLE_CLIENT_ROLE))).addProfile(PROFILE_NAME).toRepresentation()).toString();
    updatePolicies(json);
    String clientId = generateSuffixedName(CLIENT_NAME);
    String clientSecret = "secret";
    String cid = createClientByAdmin(clientId, (ClientRepresentation clientRep) -> {
        clientRep.setSecret(clientSecret);
        clientRep.setStandardFlowEnabled(Boolean.TRUE);
        clientRep.setImplicitFlowEnabled(Boolean.TRUE);
        clientRep.setPublicClient(Boolean.FALSE);
    });
    adminClient.realm(REALM_NAME).clients().get(cid).roles().create(RoleBuilder.create().name(SAMPLE_CLIENT_ROLE).build());
    oauth.clientId(clientId);
    oauth.openLoginForm();
    assertEquals(OAuthErrorException.INVALID_REQUEST, oauth.getCurrentQuery().get(OAuth2Constants.ERROR));
    assertEquals("invalid response_type", oauth.getCurrentQuery().get(OAuth2Constants.ERROR_DESCRIPTION));
    oauth.responseType(OIDCResponseType.CODE + " " + OIDCResponseType.ID_TOKEN);
    oauth.nonce("vbwe566fsfffds");
    oauth.doLogin(TEST_USER_NAME, TEST_USER_PASSWORD);
    EventRepresentation loginEvent = events.expectLogin().client(clientId).assertEvent();
    String sessionId = loginEvent.getSessionId();
    String codeId = loginEvent.getDetails().get(Details.CODE_ID);
    String code = new OAuthClient.AuthorizationEndpointResponse(oauth).getCode();
    OAuthClient.AccessTokenResponse res = oauth.doAccessTokenRequest(code, clientSecret);
    assertEquals(200, res.getStatusCode());
    events.expectCodeToToken(codeId, sessionId).client(clientId).assertEvent();
    oauth.doLogout(res.getRefreshToken(), clientSecret);
    events.expectLogout(sessionId).client(clientId).clearDetails().assertEvent();
    // update profiles
    json = (new ClientProfilesBuilder()).addProfile((new ClientProfileBuilder()).createProfile(PROFILE_NAME, "O Primeiro Perfil").addExecutor(SecureResponseTypeExecutorFactory.PROVIDER_ID, createSecureResponseTypeExecutor(Boolean.FALSE, Boolean.TRUE)).toRepresentation()).toString();
    updateProfiles(json);
    // token response type allowed
    oauth.responseType(OIDCResponseType.CODE + " " + OIDCResponseType.ID_TOKEN + " " + OIDCResponseType.TOKEN);
    oauth.nonce("cie8cjcwiw");
    oauth.doLogin(TEST_USER_NAME, TEST_USER_PASSWORD);
    loginEvent = events.expectLogin().client(clientId).assertEvent();
    sessionId = loginEvent.getSessionId();
    codeId = loginEvent.getDetails().get(Details.CODE_ID);
    code = new OAuthClient.AuthorizationEndpointResponse(oauth).getCode();
    res = oauth.doAccessTokenRequest(code, clientSecret);
    assertEquals(200, res.getStatusCode());
    events.expectCodeToToken(codeId, sessionId).client(clientId).assertEvent();
    oauth.doLogout(res.getRefreshToken(), clientSecret);
    events.expectLogout(sessionId).client(clientId).clearDetails().assertEvent();
    // shall allow code using response_mode jwt
    oauth.responseType(OIDCResponseType.CODE);
    oauth.responseMode("jwt");
    OAuthClient.AuthorizationEndpointResponse authzResponse = oauth.doLogin(TEST_USER_NAME, TEST_USER_PASSWORD);
    String jwsResponse = authzResponse.getResponse();
    AuthorizationResponseToken responseObject = oauth.verifyAuthorizationResponseToken(jwsResponse);
    code = (String) responseObject.getOtherClaims().get(OAuth2Constants.CODE);
    res = oauth.doAccessTokenRequest(code, clientSecret);
    assertEquals(200, res.getStatusCode());
    // update profiles
    json = (new ClientProfilesBuilder()).addProfile((new ClientProfileBuilder()).createProfile(PROFILE_NAME, "O Primeiro Perfil").addExecutor(SecureResponseTypeExecutorFactory.PROVIDER_ID, createSecureResponseTypeExecutor(Boolean.FALSE, Boolean.FALSE)).toRepresentation()).toString();
    updateProfiles(json);
    oauth.openLogout();
    // token response type allowed
    oauth.responseType(OIDCResponseType.CODE + " " + OIDCResponseType.ID_TOKEN + " " + OIDCResponseType.TOKEN);
    oauth.responseMode("jwt");
    oauth.openLoginForm();
    final JWSInput errorJws = new JWSInput(new OAuthClient.AuthorizationEndpointResponse(oauth).getResponse());
    JsonNode errorClaims = JsonSerialization.readValue(errorJws.getContent(), JsonNode.class);
    assertEquals(OAuthErrorException.INVALID_REQUEST, errorClaims.get("error").asText());
}
Also used : AuthorizationResponseToken(org.keycloak.representations.AuthorizationResponseToken) OAuthClient(org.keycloak.testsuite.util.OAuthClient) ClientProfilesBuilder(org.keycloak.testsuite.util.ClientPoliciesUtil.ClientProfilesBuilder) ClientPoliciesBuilder(org.keycloak.testsuite.util.ClientPoliciesUtil.ClientPoliciesBuilder) EventRepresentation(org.keycloak.representations.idm.EventRepresentation) ClientPolicyBuilder(org.keycloak.testsuite.util.ClientPoliciesUtil.ClientPolicyBuilder) JsonNode(com.fasterxml.jackson.databind.JsonNode) JWSInput(org.keycloak.jose.jws.JWSInput) OIDCClientRepresentation(org.keycloak.representations.oidc.OIDCClientRepresentation) ClientRepresentation(org.keycloak.representations.idm.ClientRepresentation) ClientProfileBuilder(org.keycloak.testsuite.util.ClientPoliciesUtil.ClientProfileBuilder) Test(org.junit.Test)

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