Java Code Examples for org.keycloak.adapters.spi.AuthOutcome#NOT_ATTEMPTED

The following examples show how to use org.keycloak.adapters.spi.AuthOutcome#NOT_ATTEMPTED . 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: BearerTokenRequestAuthenticator.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public AuthOutcome authenticate(HttpFacade exchange)  {
    List<String> authHeaders = exchange.getRequest().getHeaders("Authorization");
    if (authHeaders == null || authHeaders.isEmpty()) {
        challenge = challengeResponse(exchange, OIDCAuthenticationError.Reason.NO_BEARER_TOKEN, null, null);
        return AuthOutcome.NOT_ATTEMPTED;
    }

    tokenString = null;
    for (String authHeader : authHeaders) {
        String[] split = authHeader.trim().split("\\s+");
        if (split.length != 2) continue;
        if (split[0].equalsIgnoreCase("Bearer")) {
            tokenString = split[1];

            log.debugf("Found [%d] values in authorization header, selecting the first value for Bearer.", (Integer) authHeaders.size());
            break;
        }
    }

    if (tokenString == null) {
        challenge = challengeResponse(exchange, OIDCAuthenticationError.Reason.NO_BEARER_TOKEN, null, null);
        return AuthOutcome.NOT_ATTEMPTED;
    }

    return (authenticateToken(exchange, tokenString));
}
 
Example 2
Source File: OAuthRequestAuthenticator.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public AuthOutcome authenticate() {
    String code = getCode();
    if (code == null) {
        log.debug("there was no code");
        String error = getError();
        if (error != null) {
            // todo how do we send a response?
            log.warn("There was an error: " + error);
            challenge = challenge(400, OIDCAuthenticationError.Reason.OAUTH_ERROR, error);
            return AuthOutcome.FAILED;
        } else {
            log.debug("redirecting to auth server");
            challenge = loginRedirect();
            return AuthOutcome.NOT_ATTEMPTED;
        }
    } else {
        log.debug("there was a code, resolving");
        challenge = resolveCode(code);
        if (challenge != null) {
            return AuthOutcome.FAILED;
        }
        return AuthOutcome.AUTHENTICATED;
    }

}
 
Example 3
Source File: HammockKeycloakJaxrsFilter.java    From hammock with Apache License 2.0 5 votes vote down vote up
private void bearerAuthentication(JaxrsHttpFacade facade, ContainerRequestContext request, KeycloakDeployment resolvedDeployment) {
    BearerTokenRequestAuthenticator authenticator = new BearerTokenRequestAuthenticator(resolvedDeployment);
    AuthOutcome outcome = authenticator.authenticate(facade);

    if (outcome == AuthOutcome.NOT_ATTEMPTED) {
        authenticator = new QueryParamterTokenRequestAuthenticator(resolvedDeployment);
        outcome = authenticator.authenticate(facade);
    }

    if (outcome == AuthOutcome.NOT_ATTEMPTED && resolvedDeployment.isEnableBasicAuth()) {
        authenticator = new BasicAuthRequestAuthenticator(resolvedDeployment);
        outcome = authenticator.authenticate(facade);
    }

    if (outcome == AuthOutcome.FAILED || outcome == AuthOutcome.NOT_ATTEMPTED) {
        AuthChallenge challenge = authenticator.getChallenge();
        boolean challengeSent = challenge.challenge(facade);
        if (!challengeSent) {
            // Use some default status code
            facade.getResponse().setStatus(Response.Status.UNAUTHORIZED.getStatusCode());
        }

        // Send response now (if not already sent)
        if (!facade.isResponseFinished()) {
            facade.getResponse().end();
        }
        return;
    } else {
        if (verifySslFailed(facade, resolvedDeployment)) {
            return;
        }
    }

    propagateSecurityContext(facade, request, resolvedDeployment, authenticator);
    handleAuthActions(facade, resolvedDeployment);
}
 
Example 4
Source File: JaxrsBearerTokenFilterImpl.java    From keycloak with Apache License 2.0 5 votes vote down vote up
protected void bearerAuthentication(JaxrsHttpFacade facade, ContainerRequestContext request, KeycloakDeployment resolvedDeployment) {
    BearerTokenRequestAuthenticator authenticator = new BearerTokenRequestAuthenticator(resolvedDeployment);
    AuthOutcome outcome = authenticator.authenticate(facade);
    
    if (outcome == AuthOutcome.NOT_ATTEMPTED && resolvedDeployment.isEnableBasicAuth()) {
        authenticator = new BasicAuthRequestAuthenticator(resolvedDeployment);
        outcome = authenticator.authenticate(facade);
    }
    
    if (outcome == AuthOutcome.FAILED || outcome == AuthOutcome.NOT_ATTEMPTED) {
        AuthChallenge challenge = authenticator.getChallenge();
        log.fine("Authentication outcome: " + outcome);
        boolean challengeSent = challenge.challenge(facade);
        if (!challengeSent) {
            // Use some default status code
            facade.getResponse().setStatus(Response.Status.UNAUTHORIZED.getStatusCode());
        }

        // Send response now (if not already sent)
        if (!facade.isResponseFinished()) {
            facade.getResponse().end();
        }
        return;
    } else {
        if (verifySslFailed(facade, resolvedDeployment)) {
            return;
        }
    }

    propagateSecurityContext(facade, request, resolvedDeployment, authenticator);
    handleAuthActions(facade, resolvedDeployment);
}
 
Example 5
Source File: BasicAuthRequestAuthenticator.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public AuthOutcome authenticate(HttpFacade exchange)  {
    List<String> authHeaders = exchange.getRequest().getHeaders("Authorization");
    if (authHeaders == null || authHeaders.isEmpty()) {
        challenge = challengeResponse(exchange, OIDCAuthenticationError.Reason.NO_AUTHORIZATION_HEADER, null, null);
        return AuthOutcome.NOT_ATTEMPTED;
    }

    tokenString = null;
    for (String authHeader : authHeaders) {
        String[] split = authHeader.trim().split("\\s+");
        if (split.length != 2) continue;
        if (!split[0].equalsIgnoreCase("Basic")) continue;
        tokenString = split[1];
    }

    if (tokenString == null) {
        challenge = challengeResponse(exchange, OIDCAuthenticationError.Reason.INVALID_TOKEN, null, null);
        return AuthOutcome.NOT_ATTEMPTED;
    }

    AccessTokenResponse atr=null;        
    try {
        String userpw=new String(Base64.decode(tokenString));
        int seperatorIndex = userpw.indexOf(":");
        String user = userpw.substring(0, seperatorIndex);
        String pw = userpw.substring(seperatorIndex + 1);
        atr = getToken(user, pw);
        tokenString = atr.getToken();
    } catch (Exception e) {
        log.debug("Failed to obtain token", e);
        challenge = challengeResponse(exchange, OIDCAuthenticationError.Reason.INVALID_TOKEN, "no_token", e.getMessage());
        return AuthOutcome.FAILED;
    }

    return authenticateToken(exchange, atr.getToken());
}
 
Example 6
Source File: QueryParameterTokenRequestAuthenticator.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public AuthOutcome authenticate(HttpFacade exchange) {
    if(!deployment.isOAuthQueryParameterEnabled()) {
        return AuthOutcome.NOT_ATTEMPTED;
    }
    tokenString = null;
    tokenString = getAccessTokenFromQueryParameter(exchange);
    if (tokenString == null || tokenString.trim().isEmpty()) {
        challenge = challengeResponse(exchange, OIDCAuthenticationError.Reason.NO_QUERY_PARAMETER_ACCESS_TOKEN, null, null);
        return AuthOutcome.NOT_ATTEMPTED;
    }
    return (authenticateToken(exchange, tokenString));
}
 
Example 7
Source File: WebBrowserSsoAuthenticationHandler.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
protected AuthOutcome logoutRequest(LogoutRequestType request, String relayState) {
    if (request.getSessionIndex() == null || request.getSessionIndex().isEmpty()) {
        sessionStore.logoutByPrincipal(request.getNameID().getValue());
    } else {
        sessionStore.logoutBySsoId(request.getSessionIndex());
    }

    String issuerURL = deployment.getEntityID();
    SAML2LogoutResponseBuilder builder = new SAML2LogoutResponseBuilder();
    builder.logoutRequestID(request.getID());
    builder.destination(deployment.getIDP().getSingleLogoutService().getResponseBindingUrl());
    builder.issuer(issuerURL);
    BaseSAML2BindingBuilder binding = new BaseSAML2BindingBuilder().relayState(relayState);
    if (deployment.getIDP().getSingleLogoutService().signResponse()) {
        if (deployment.getSignatureCanonicalizationMethod() != null)
            binding.canonicalizationMethod(deployment.getSignatureCanonicalizationMethod());
        binding.signatureAlgorithm(deployment.getSignatureAlgorithm())
                .signWith(null, deployment.getSigningKeyPair())
                .signDocument();
        // TODO: As part of KEYCLOAK-3810, add KeyID to the SAML document
        //   <related DocumentBuilder>.addExtension(new KeycloakKeySamlExtensionGenerator(<key ID>));
    }


    try {
        SamlUtil.sendSaml(false, facade, deployment.getIDP().getSingleLogoutService().getResponseBindingUrl(), binding, builder.buildDocument(),
                deployment.getIDP().getSingleLogoutService().getResponseBinding());
    } catch (Exception e) {
        log.error("Could not send logout response SAML request", e);
        return AuthOutcome.FAILED;
    }
    return AuthOutcome.NOT_ATTEMPTED;
}
 
Example 8
Source File: WebBrowserSsoAuthenticationHandler.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private AuthOutcome globalLogout() {
    SamlSession account = sessionStore.getAccount();
    if (account == null) {
        return AuthOutcome.NOT_ATTEMPTED;
    }
    SAML2LogoutRequestBuilder logoutBuilder = new SAML2LogoutRequestBuilder()
            .assertionExpiration(30)
            .issuer(deployment.getEntityID())
            .sessionIndex(account.getSessionIndex())
            .nameId(account.getPrincipal().getNameID())
            .destination(deployment.getIDP().getSingleLogoutService().getRequestBindingUrl());
    BaseSAML2BindingBuilder binding = new BaseSAML2BindingBuilder();
    if (deployment.getIDP().getSingleLogoutService().signRequest()) {
        if (deployment.getSignatureCanonicalizationMethod() != null)
            binding.canonicalizationMethod(deployment.getSignatureCanonicalizationMethod());
        binding.signatureAlgorithm(deployment.getSignatureAlgorithm());
        binding.signWith(null, deployment.getSigningKeyPair())
                .signDocument();
        // TODO: As part of KEYCLOAK-3810, add KeyID to the SAML document
        //   <related DocumentBuilder>.addExtension(new KeycloakKeySamlExtensionGenerator(<key ID>));
    }

    binding.relayState("logout");

    try {
        SamlUtil.sendSaml(true, facade, deployment.getIDP().getSingleLogoutService().getRequestBindingUrl(), binding, logoutBuilder.buildDocument(), deployment.getIDP().getSingleLogoutService().getRequestBinding());
        sessionStore.setCurrentAction(SamlSessionStore.CurrentAction.LOGGING_OUT);
    } catch (Exception e) {
        log.error("Could not send global logout SAML request", e);
        return AuthOutcome.FAILED;
    }
    return AuthOutcome.NOT_ATTEMPTED;
}
 
Example 9
Source File: SamlEndpoint.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public AuthOutcome handle(OnSessionCreated onCreateSession) {
    String samlRequest = facade.getRequest().getFirstParam(GeneralConstants.SAML_REQUEST_KEY);
    String samlResponse = facade.getRequest().getFirstParam(GeneralConstants.SAML_RESPONSE_KEY);
    String relayState = facade.getRequest().getFirstParam(GeneralConstants.RELAY_STATE);
    if (samlRequest != null) {
        return handleSamlRequest(samlRequest, relayState);
    } else if (samlResponse != null) {
        return handleSamlResponse(samlResponse, relayState, onCreateSession);
    }
    return AuthOutcome.NOT_ATTEMPTED;

}
 
Example 10
Source File: AbstractSamlAuthenticationHandler.java    From keycloak with Apache License 2.0 5 votes vote down vote up
protected AuthOutcome handleLogoutResponse(SAMLDocumentHolder holder, StatusResponseType responseType, String relayState) {
    boolean loggedIn = sessionStore.isLoggedIn();
    if (!loggedIn || !"logout".equals(relayState)) {
        return AuthOutcome.NOT_ATTEMPTED;
    }
    sessionStore.logoutAccount();
    return AuthOutcome.LOGGED_OUT;
}
 
Example 11
Source File: AbstractSamlAuthenticationHandler.java    From keycloak with Apache License 2.0 4 votes vote down vote up
protected AuthOutcome initiateLogin() {
    challenge = createChallenge();
    return AuthOutcome.NOT_ATTEMPTED;
}