Java Code Examples for org.keycloak.KeycloakSecurityContext#getToken()

The following examples show how to use org.keycloak.KeycloakSecurityContext#getToken() . 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: KeycloakAuthenticationFilter.java    From apicurio-studio with Apache License 2.0 6 votes vote down vote up
/**
 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain)
 */
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest httpReq = (HttpServletRequest) request;
    KeycloakSecurityContext session = getSession(httpReq);
    if (session != null) {
        // Fabricate a User object from information in the access token and store it in the security context.
        AccessToken token = session.getToken();
        if (token != null) {
            User user = new User();
            user.setEmail(token.getEmail());
            user.setLogin(token.getPreferredUsername());
            user.setName(token.getName());
            ((SecurityContext) security).setUser(user);
            ((SecurityContext) security).setToken(session.getTokenString());
        }
    }
    chain.doFilter(request, response);
}
 
Example 2
Source File: KeycloakLoggedInUser.java    From pnc with Apache License 2.0 6 votes vote down vote up
public KeycloakLoggedInUser(HttpServletRequest httpServletRequest) {
    if (httpServletRequest == null) {
        throw new NullPointerException();
    }
    try {
        KeycloakSecurityContext keycloakSecurityContext = (KeycloakSecurityContext) httpServletRequest
                .getAttribute(KeycloakSecurityContext.class.getName());
        if (keycloakSecurityContext == null) {
            handleAuthenticationProblem("KeycloakSecurityContext not available in the HttpServletRequest.");
        } else {
            this.auth = keycloakSecurityContext.getToken();
            this.tokenString = keycloakSecurityContext.getTokenString();
        }
    } catch (NoClassDefFoundError ncdfe) {
        handleAuthenticationProblem(ncdfe.getMessage(), ncdfe);
    }
}
 
Example 3
Source File: CustomerService.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@GET
@Produces("application/json")
@NoCache
public List<String> getCustomers() {
    // Just to show how to user info from access token in REST endpoint
    KeycloakSecurityContext securityContext = (KeycloakSecurityContext) httpRequest.getAttribute(KeycloakSecurityContext.class.getName());
    AccessToken accessToken = securityContext.getToken();
    System.out.println(String.format("User '%s' with email '%s' made request to CustomerService REST endpoint", accessToken.getPreferredUsername(), accessToken.getEmail()));

    ArrayList<String> rtn = new ArrayList<String>();
    rtn.add("Bill Burke");
    rtn.add("Stian Thorgersen");
    rtn.add("Stan Silvert");
    rtn.add("Gabriel Cardoso");
    rtn.add("Viliam Rockai");
    rtn.add("Marek Posolda");
    rtn.add("Boleslaw Dawidowicz");
    return rtn;
}
 
Example 4
Source File: KeycloakLinkedAccountsProvider.java    From apicurio-studio with Apache License 2.0 5 votes vote down vote up
/**
 * @see io.apicurio.hub.api.security.ILinkedAccountsProvider#initiateLinkedAccount(io.apicurio.hub.core.beans.LinkedAccountType, java.lang.String, java.lang.String)
 */
@Override
public InitiatedLinkedAccount initiateLinkedAccount(LinkedAccountType accountType, String redirectUri,
        String nonce) {
    String authServerRootUrl = config.getKeycloakAuthUrl();
    String realm = config.getKeycloakRealm();
    String provider = accountType.alias();

    KeycloakSecurityContext session = (KeycloakSecurityContext) request.getAttribute(KeycloakSecurityContext.class.getName());
    AccessToken token = session.getToken();

    String clientId = token.getIssuedFor();
    MessageDigest md = null;
    try {
        md = MessageDigest.getInstance("SHA-256");
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    }
    String input = nonce + token.getSessionState() + clientId + provider;
    byte[] check = md.digest(input.getBytes(StandardCharsets.UTF_8));
    String hash = Base64Url.encode(check);
    String accountLinkUrl = KeycloakUriBuilder.fromUri(authServerRootUrl)
        .path("/realms/{realm}/broker/{provider}/link").queryParam("nonce", nonce)
        .queryParam("hash", hash).queryParam("client_id", clientId)
        .queryParam("redirect_uri", redirectUri).build(realm, provider).toString();

    logger.debug("Account Link URL: {}", accountLinkUrl);

    // Return the URL that the browser should use to initiate the account linking
    InitiatedLinkedAccount rval = new InitiatedLinkedAccount();
    rval.setAuthUrl(accountLinkUrl);
    rval.setNonce(nonce);
    return rval;
}
 
Example 5
Source File: KeycloakAdapterPolicyEnforcer.java    From keycloak with Apache License 2.0 4 votes vote down vote up
private AccessToken requestAuthorizationToken(PathConfig pathConfig, PolicyEnforcerConfig.MethodConfig methodConfig, OIDCHttpFacade httpFacade, Map<String, List<String>> claims) {
    if (getEnforcerConfig().getUserManagedAccess() != null) {
        return null;
    }

    try {
        KeycloakSecurityContext securityContext = httpFacade.getSecurityContext();
        String accessTokenString = securityContext.getTokenString();
        KeycloakDeployment deployment = getPolicyEnforcer().getDeployment();
        AccessToken accessToken = securityContext.getToken();
        AuthorizationRequest authzRequest = new AuthorizationRequest();

        if (isBearerAuthorization(httpFacade) || accessToken.getAuthorization() != null) {
            authzRequest.addPermission(pathConfig.getId(), methodConfig.getScopes());
        }

        if (!claims.isEmpty()) {
            authzRequest.setClaimTokenFormat("urn:ietf:params:oauth:token-type:jwt");
            authzRequest.setClaimToken(Base64.encodeBytes(JsonSerialization.writeValueAsBytes(claims)));
        }

        if (accessToken.getAuthorization() != null) {
            authzRequest.setRpt(accessTokenString);
        }

        LOGGER.debug("Obtaining authorization for authenticated user.");
        AuthorizationResponse authzResponse;

        if (isBearerAuthorization(httpFacade)) {
            authzRequest.setSubjectToken(accessTokenString);
            authzResponse = getAuthzClient().authorization().authorize(authzRequest);
        } else {
            authzResponse = getAuthzClient().authorization(accessTokenString).authorize(authzRequest);
        }

        if (authzResponse != null) {
            return AdapterTokenVerifier.verifyToken(authzResponse.getToken(), deployment);
        }
    } catch (AuthorizationDeniedException ignore) {
        LOGGER.debug("Authorization denied", ignore);
    } catch (Exception e) {
        LOGGER.debug("Authorization failed", e);
    }

    return null;
}
 
Example 6
Source File: AbstractPolicyEnforcer.java    From keycloak with Apache License 2.0 4 votes vote down vote up
public AuthorizationContext authorize(OIDCHttpFacade httpFacade) {
    EnforcementMode enforcementMode = getEnforcerConfig().getEnforcementMode();
    KeycloakSecurityContext securityContext = httpFacade.getSecurityContext();

    if (EnforcementMode.DISABLED.equals(enforcementMode)) {
        if (securityContext == null) {
            httpFacade.getResponse().sendError(401, "Invalid bearer");
        }
        return createEmptyAuthorizationContext(true);
    }

    Request request = httpFacade.getRequest();
    PathConfig pathConfig = getPathConfig(request);

    if (securityContext == null) {
        if (!isDefaultAccessDeniedUri(request)) {
            if (pathConfig != null) {
                if (EnforcementMode.DISABLED.equals(pathConfig.getEnforcementMode())) {
                    return createEmptyAuthorizationContext(true);
                } else {
                    challenge(pathConfig, getRequiredScopes(pathConfig, request), httpFacade);
                }
            } else {
                handleAccessDenied(httpFacade);
            }
        }
        return createEmptyAuthorizationContext(false);
    }

    AccessToken accessToken = securityContext.getToken();

    if (accessToken != null) {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debugf("Checking permissions for path [%s] with config [%s].", request.getURI(), pathConfig);
        }

        if (pathConfig == null) {
            if (EnforcementMode.PERMISSIVE.equals(enforcementMode)) {
                return createAuthorizationContext(accessToken, null);
            }

            if (LOGGER.isDebugEnabled()) {
                LOGGER.debugf("Could not find a configuration for path [%s]", getPath(request));
            }

            if (isDefaultAccessDeniedUri(request)) {
                return createAuthorizationContext(accessToken, null);
            }

            handleAccessDenied(httpFacade);

            return createEmptyAuthorizationContext(false);
        }

        if (EnforcementMode.DISABLED.equals(pathConfig.getEnforcementMode())) {
            return createAuthorizationContext(accessToken, pathConfig);
        }

        MethodConfig methodConfig = getRequiredScopes(pathConfig, request);
        Map<String, List<String>> claims = resolveClaims(pathConfig, httpFacade);

        if (isAuthorized(pathConfig, methodConfig, accessToken, httpFacade, claims)) {
            try {
                return createAuthorizationContext(accessToken, pathConfig);
            } catch (Exception e) {
                throw new RuntimeException("Error processing path [" + pathConfig.getPath() + "].", e);
            }
        }

        if (methodConfig != null && ScopeEnforcementMode.DISABLED.equals(methodConfig.getScopesEnforcementMode())) {
            return createEmptyAuthorizationContext(true);
        }

        if (LOGGER.isDebugEnabled()) {
            LOGGER.debugf("Sending challenge to the client. Path [%s]", pathConfig);
        }

        if (!challenge(pathConfig, methodConfig, httpFacade)) {
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debugf("Challenge not sent, sending default forbidden response. Path [%s]", pathConfig);
            }
            handleAccessDenied(httpFacade);
        }
    }

    return createEmptyAuthorizationContext(false);
}
 
Example 7
Source File: AuthenticatedActionsHandler.java    From keycloak with Apache License 2.0 4 votes vote down vote up
protected boolean corsRequest()  {
    if (!deployment.isCors()) return false;
    KeycloakSecurityContext securityContext = facade.getSecurityContext();
    String origin = facade.getRequest().getHeader(CorsHeaders.ORIGIN);
    String exposeHeaders = deployment.getCorsExposedHeaders();

    if (deployment.getPolicyEnforcer() != null) {
        if (exposeHeaders != null) {
            exposeHeaders += ",";
        } else {
            exposeHeaders = "";
        }

        exposeHeaders += "WWW-Authenticate";
    }

    String requestOrigin = UriUtils.getOrigin(facade.getRequest().getURI());
    log.debugv("Origin: {0} uri: {1}", origin, facade.getRequest().getURI());
    if (securityContext != null && origin != null && !origin.equals(requestOrigin)) {
        AccessToken token = securityContext.getToken();
        Set<String> allowedOrigins = token.getAllowedOrigins();

        log.debugf("Allowed origins in token: %s", allowedOrigins);

        if (allowedOrigins == null || (!allowedOrigins.contains("*") && !allowedOrigins.contains(origin))) {
            if (allowedOrigins == null) {
                log.debugv("allowedOrigins was null in token");
            } else {
                log.debugv("allowedOrigins did not contain origin");
            }
            facade.getResponse().sendError(403);
            facade.getResponse().end();
            return true;
        }
        log.debugv("returning origin: {0}", origin);
        facade.getResponse().setStatus(200);
        facade.getResponse().setHeader(CorsHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, origin);
        facade.getResponse().setHeader(CorsHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true");
        if (exposeHeaders != null) {
            facade.getResponse().setHeader(CorsHeaders.ACCESS_CONTROL_EXPOSE_HEADERS, exposeHeaders);
        }
    } else {
        log.debugv("cors validation not needed as we are not a secure session or origin header was null: {0}", facade.getRequest().getURI());
    }
    return false;
}