Search in sources :

Example 6 with AccessToken

use of org.keycloak.representations.AccessToken in project keycloak by keycloak.

the class BackchannelAuthenticationCallbackEndpoint method verifyAuthenticationRequest.

private BackchannelAuthCallbackContext verifyAuthenticationRequest(HttpHeaders headers) {
    String rawBearerToken = AppAuthManager.extractAuthorizationHeaderTokenOrReturnNull(headers);
    if (rawBearerToken == null) {
        throw new ErrorResponseException(OAuthErrorException.INVALID_TOKEN, "Invalid token", Response.Status.UNAUTHORIZED);
    }
    AccessToken bearerToken;
    try {
        bearerToken = TokenVerifier.createWithoutSignature(session.tokens().decode(rawBearerToken, AccessToken.class)).withDefaultChecks().realmUrl(Urls.realmIssuer(session.getContext().getUri().getBaseUri(), realm.getName())).checkActive(true).audience(Urls.realmIssuer(session.getContext().getUri().getBaseUri(), realm.getName())).verify().getToken();
    } catch (Exception e) {
        event.error(Errors.INVALID_TOKEN);
        // authentication channel id format is invalid or it has already been used
        throw new ErrorResponseException(OAuthErrorException.INVALID_TOKEN, "Invalid token", Response.Status.FORBIDDEN);
    }
    OAuth2DeviceTokenStoreProvider store = session.getProvider(OAuth2DeviceTokenStoreProvider.class);
    OAuth2DeviceCodeModel deviceCode = store.getByUserCode(realm, bearerToken.getId());
    if (deviceCode == null) {
        throw new ErrorResponseException(OAuthErrorException.INVALID_TOKEN, "Invalid token", Response.Status.FORBIDDEN);
    }
    if (!deviceCode.isPending()) {
        cancelRequest(bearerToken.getId());
        throw new ErrorResponseException(OAuthErrorException.INVALID_TOKEN, "Invalid token", Response.Status.FORBIDDEN);
    }
    ClientModel issuedFor = realm.getClientByClientId(bearerToken.getIssuedFor());
    if (issuedFor == null || !issuedFor.isEnabled()) {
        throw new ErrorResponseException(OAuthErrorException.INVALID_REQUEST, "Invalid token recipient", Response.Status.BAD_REQUEST);
    }
    if (!deviceCode.getClientId().equals(issuedFor.getClientId())) {
        throw new ErrorResponseException(OAuthErrorException.INVALID_REQUEST, "Token recipient mismatch", Response.Status.BAD_REQUEST);
    }
    session.getContext().setClient(issuedFor);
    event.client(issuedFor);
    return new BackchannelAuthCallbackContext(bearerToken, deviceCode);
}
Also used : OAuth2DeviceTokenStoreProvider(org.keycloak.models.OAuth2DeviceTokenStoreProvider) ClientModel(org.keycloak.models.ClientModel) OAuth2DeviceCodeModel(org.keycloak.models.OAuth2DeviceCodeModel) AccessToken(org.keycloak.representations.AccessToken) ErrorResponseException(org.keycloak.services.ErrorResponseException) OAuthErrorException(org.keycloak.OAuthErrorException) ErrorResponseException(org.keycloak.services.ErrorResponseException) IOException(java.io.IOException)

Example 7 with AccessToken

use of org.keycloak.representations.AccessToken in project keycloak by keycloak.

the class BackchannelAuthenticationCallbackEndpoint method processAuthenticationChannelResult.

@Path("/")
@POST
@NoCache
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response processAuthenticationChannelResult(AuthenticationChannelResponse response) {
    event.event(EventType.LOGIN);
    BackchannelAuthCallbackContext ctx = verifyAuthenticationRequest(httpRequest.getHttpHeaders());
    AccessToken bearerToken = ctx.bearerToken;
    OAuth2DeviceCodeModel deviceModel = ctx.deviceModel;
    Status status = response.getStatus();
    if (status == null) {
        event.error(Errors.INVALID_REQUEST);
        throw new ErrorResponseException(OAuthErrorException.INVALID_REQUEST, "Invalid authentication status", Response.Status.BAD_REQUEST);
    }
    switch(status) {
        case SUCCEED:
            approveRequest(bearerToken, response.getAdditionalParams());
            break;
        case CANCELLED:
        case UNAUTHORIZED:
            denyRequest(bearerToken, status);
            break;
    }
    // Call the notification endpoint
    ClientModel client = session.getContext().getClient();
    CibaConfig cibaConfig = realm.getCibaPolicy();
    if (cibaConfig.getBackchannelTokenDeliveryMode(client).equals(CibaConfig.CIBA_PING_MODE)) {
        sendClientNotificationRequest(client, cibaConfig, deviceModel);
    }
    return Response.ok(MediaType.APPLICATION_JSON_TYPE).build();
}
Also used : Status(org.keycloak.protocol.oidc.grants.ciba.channel.AuthenticationChannelResponse.Status) ClientModel(org.keycloak.models.ClientModel) OAuth2DeviceCodeModel(org.keycloak.models.OAuth2DeviceCodeModel) AccessToken(org.keycloak.representations.AccessToken) CibaConfig(org.keycloak.models.CibaConfig) ErrorResponseException(org.keycloak.services.ErrorResponseException) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes) Produces(javax.ws.rs.Produces) NoCache(org.jboss.resteasy.annotations.cache.NoCache)

Example 8 with AccessToken

use of org.keycloak.representations.AccessToken in project keycloak by keycloak.

the class HttpAuthenticationChannelProvider method createBearerToken.

private String createBearerToken(CIBAAuthenticationRequest request, ClientModel client) {
    AccessToken bearerToken = new AccessToken();
    bearerToken.type(TokenUtil.TOKEN_TYPE_BEARER);
    bearerToken.issuer(request.getIssuer());
    bearerToken.id(request.getAuthResultId());
    bearerToken.issuedFor(client.getClientId());
    bearerToken.audience(request.getIssuer());
    bearerToken.exp(request.getExp());
    bearerToken.subject(request.getSubject());
    return session.tokens().encode(bearerToken);
}
Also used : AccessToken(org.keycloak.representations.AccessToken)

Example 9 with AccessToken

use of org.keycloak.representations.AccessToken in project keycloak by keycloak.

the class AbstractUserRoleMappingMapper method checkAccessToken.

// Special case when roles are put to the access token via "realmAcces, resourceAccess" properties
private static boolean checkAccessToken(IDToken idToken, List<String> path, Object attributeValue) {
    if (!(idToken instanceof AccessToken)) {
        return false;
    }
    if (!(attributeValue instanceof Collection)) {
        return false;
    }
    Collection<String> roles = (Collection<String>) attributeValue;
    AccessToken token = (AccessToken) idToken;
    AccessToken.Access access = null;
    if (path.size() == 2 && "realm_access".equals(path.get(0)) && "roles".equals(path.get(1))) {
        access = token.getRealmAccess();
        if (access == null) {
            access = new AccessToken.Access();
            token.setRealmAccess(access);
        }
    } else if (path.size() == 3 && "resource_access".equals(path.get(0)) && "roles".equals(path.get(2))) {
        String clientId = path.get(1);
        access = token.addAccess(clientId);
    } else {
        return false;
    }
    for (String role : roles) {
        access.addRole(role);
    }
    return true;
}
Also used : AccessToken(org.keycloak.representations.AccessToken) Collection(java.util.Collection)

Example 10 with AccessToken

use of org.keycloak.representations.AccessToken in project keycloak by keycloak.

the class LinkAndExchangeServlet method doGet.

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse resp) throws ServletException, IOException {
    resp.setHeader("Cache-Control", "no-cache");
    if (request.getRequestURI().endsWith("/link") && request.getParameter("response") == null) {
        String provider = request.getParameter("provider");
        String realm = request.getParameter("realm");
        KeycloakSecurityContext session = (KeycloakSecurityContext) request.getAttribute(KeycloakSecurityContext.class.getName());
        AccessToken token = session.getToken();
        String tokenString = session.getTokenString();
        String clientId = token.getIssuedFor();
        String linkUrl = null;
        try {
            AccessTokenResponse response = doTokenExchange(realm, tokenString, provider, clientId, "password");
            String error = response.getError();
            if (error != null) {
                System.out.println("*** error : " + error);
                System.out.println("*** link-url: " + response.getOtherClaims().get("account-link-url"));
                linkUrl = (String) response.getOtherClaims().get("account-link-url");
            } else {
                Assert.assertNotNull(response.getToken());
                resp.setStatus(200);
                resp.setContentType("text/html");
                PrintWriter pw = resp.getWriter();
                pw.printf("<html><head><title>%s</title></head><body>", "Client Linking");
                pw.println("Account Linked");
                pw.print("</body></html>");
                pw.flush();
                return;
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        String redirectUri = KeycloakUriBuilder.fromUri(request.getRequestURL().toString()).replaceQuery(null).queryParam("response", "true").queryParam("realm", realm).queryParam("provider", provider).build().toString();
        String accountLinkUrl = KeycloakUriBuilder.fromUri(linkUrl).queryParam("redirect_uri", redirectUri).build().toString();
        resp.setStatus(302);
        resp.setHeader("Location", accountLinkUrl);
    } else if (request.getRequestURI().endsWith("/link") && request.getParameter("response") != null) {
        resp.setStatus(200);
        resp.setContentType("text/html");
        PrintWriter pw = resp.getWriter();
        pw.printf("<html><head><title>%s</title></head><body>", "Client Linking");
        String error = request.getParameter("link_error");
        if (error != null) {
            pw.println("Link error: " + error);
        } else {
            pw.println("Account Linked");
        }
        pw.println("trying exchange");
        try {
            String provider = request.getParameter("provider");
            String realm = request.getParameter("realm");
            KeycloakSecurityContext session = (KeycloakSecurityContext) request.getAttribute(KeycloakSecurityContext.class.getName());
            AccessToken token = session.getToken();
            String clientId = token.getIssuedFor();
            String tokenString = session.getTokenString();
            AccessTokenResponse response = doTokenExchange(realm, tokenString, provider, clientId, "password");
            error = (String) response.getOtherClaims().get("error");
            if (error == null) {
                if (response.getToken() != null)
                    pw.println("Exchange token received");
            } else {
                pw.print("Error with exchange: " + error);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        pw.print("</body></html>");
        pw.flush();
    } else {
        resp.setStatus(200);
        resp.setContentType("text/html");
        PrintWriter pw = resp.getWriter();
        pw.printf("<html><head><title>%s</title></head><body>", "Client Linking");
        pw.println("Unknown request: " + request.getRequestURL().toString());
        pw.print("</body></html>");
        pw.flush();
    }
}
Also used : KeycloakSecurityContext(org.keycloak.KeycloakSecurityContext) AccessToken(org.keycloak.representations.AccessToken) AccessTokenResponse(org.keycloak.representations.AccessTokenResponse) ServletException(javax.servlet.ServletException) IOException(java.io.IOException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) PrintWriter(java.io.PrintWriter)

Aggregations

AccessToken (org.keycloak.representations.AccessToken)230 Test (org.junit.Test)129 OAuthClient (org.keycloak.testsuite.util.OAuthClient)104 AbstractKeycloakTest (org.keycloak.testsuite.AbstractKeycloakTest)54 RefreshToken (org.keycloak.representations.RefreshToken)45 AuthorizationResponse (org.keycloak.representations.idm.authorization.AuthorizationResponse)37 JWSInput (org.keycloak.jose.jws.JWSInput)29 Permission (org.keycloak.representations.idm.authorization.Permission)28 EventRepresentation (org.keycloak.representations.idm.EventRepresentation)27 Response (javax.ws.rs.core.Response)26 ClientResource (org.keycloak.admin.client.resource.ClientResource)22 VerificationException (org.keycloak.common.VerificationException)19 ClientRepresentation (org.keycloak.representations.idm.ClientRepresentation)19 AccessTokenResponse (org.keycloak.representations.AccessTokenResponse)18 IDToken (org.keycloak.representations.IDToken)18 AuthorizationRequest (org.keycloak.representations.idm.authorization.AuthorizationRequest)17 IOException (java.io.IOException)15 AuthzClient (org.keycloak.authorization.client.AuthzClient)15 ResourceRepresentation (org.keycloak.representations.idm.authorization.ResourceRepresentation)14 ArrayList (java.util.ArrayList)13