org.keycloak.adapters.spi.AuthOutcome Java Examples
The following examples show how to use
org.keycloak.adapters.spi.AuthOutcome.
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: EcpAuthenticationHandler.java From keycloak with Apache License 2.0 | 6 votes |
@Override public AuthOutcome handle(OnSessionCreated onCreateSession) { String header = facade.getRequest().getHeader(PAOS_HEADER); if (header != null) { return doHandle(new SamlInvocationContext(), onCreateSession); } else { try { MessageFactory messageFactory = MessageFactory.newInstance(); SOAPMessage soapMessage = messageFactory.createMessage(null, facade.getRequest().getInputStream()); SOAPBody soapBody = soapMessage.getSOAPBody(); Node authnRequestNode = soapBody.getFirstChild(); Document document = DocumentUtil.createDocument(); document.appendChild(document.importNode(authnRequestNode, true)); String samlResponse = PostBindingUtil.base64Encode(DocumentUtil.asString(document)); return doHandle(new SamlInvocationContext(null, samlResponse, null), onCreateSession); } catch (Exception e) { throw new RuntimeException("Error creating fault message.", e); } } }
Example #2
Source File: BearerTokenRequestAuthenticator.java From keycloak with Apache License 2.0 | 6 votes |
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 #3
Source File: AbstractUndertowKeycloakAuthMech.java From keycloak with Apache License 2.0 | 6 votes |
/** * Call this inside your authenticate method. */ protected AuthenticationMechanismOutcome keycloakAuthenticate(HttpServerExchange exchange, SecurityContext securityContext, RequestAuthenticator authenticator) { AuthOutcome outcome = authenticator.authenticate(); if (outcome == AuthOutcome.AUTHENTICATED) { registerNotifications(securityContext); return AuthenticationMechanismOutcome.AUTHENTICATED; } AuthChallenge challenge = authenticator.getChallenge(); if (challenge != null) { exchange.putAttachment(KEYCLOAK_CHALLENGE_ATTACHMENT_KEY, challenge); } if (outcome == AuthOutcome.FAILED) { return AuthenticationMechanismOutcome.NOT_AUTHENTICATED; } return AuthenticationMechanismOutcome.NOT_ATTEMPTED; }
Example #4
Source File: AbstractKeycloakAuthenticatorValve.java From keycloak with Apache License 2.0 | 6 votes |
protected boolean authenticateInternal(Request request, HttpServletResponse response, Object loginConfig) throws IOException { CatalinaHttpFacade facade = new OIDCCatalinaHttpFacade(request, response); KeycloakDeployment deployment = deploymentContext.resolveDeployment(facade); if (deployment == null || !deployment.isConfigured()) { //needed for the EAP6/AS7 adapter relying on the tomcat core adapter facade.getResponse().sendError(401); return false; } AdapterTokenStore tokenStore = getTokenStore(request, facade, deployment); nodesRegistrationManagement.tryRegister(deployment); CatalinaRequestAuthenticator authenticator = createRequestAuthenticator(request, facade, deployment, tokenStore); AuthOutcome outcome = authenticator.authenticate(); if (outcome == AuthOutcome.AUTHENTICATED) { if (facade.isEnded()) { return false; } return true; } AuthChallenge challenge = authenticator.getChallenge(); if (challenge != null) { challenge.challenge(facade); } return false; }
Example #5
Source File: OAuthRequestAuthenticator.java From keycloak with Apache License 2.0 | 6 votes |
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 #6
Source File: WebBrowserSsoAuthenticationHandler.java From keycloak with Apache License 2.0 | 5 votes |
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 #7
Source File: WebBrowserSsoAuthenticationHandler.java From keycloak with Apache License 2.0 | 5 votes |
@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 |
@Override protected AuthOutcome handleRequest() { boolean globalLogout = "true".equals(facade.getRequest().getQueryParamValue("GLO")); if (globalLogout) { return globalLogout(); } return AuthOutcome.AUTHENTICATED; }
Example #9
Source File: SamlEndpoint.java From keycloak with Apache License 2.0 | 5 votes |
@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 |
public AuthOutcome doHandle(SamlInvocationContext context, OnSessionCreated onCreateSession) { String samlRequest = context.getSamlRequest(); String samlResponse = context.getSamlResponse(); String relayState = context.getRelayState(); if (samlRequest != null) { return handleSamlRequest(samlRequest, relayState); } else if (samlResponse != null) { return handleSamlResponse(samlResponse, relayState, onCreateSession); } else if (sessionStore.isLoggedIn()) { if (verifySSL()) return failedTerminal(); log.debug("AUTHENTICATED: was cached"); return handleRequest(); } return initiateLogin(); }
Example #11
Source File: AbstractSamlAuthenticationHandler.java From keycloak with Apache License 2.0 | 5 votes |
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 #12
Source File: QueryParameterTokenRequestAuthenticator.java From keycloak with Apache License 2.0 | 5 votes |
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 #13
Source File: BasicAuthRequestAuthenticator.java From keycloak with Apache License 2.0 | 5 votes |
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 #14
Source File: JaxrsBearerTokenFilterImpl.java From keycloak with Apache License 2.0 | 5 votes |
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 #15
Source File: SamlAuthenticator.java From keycloak with Apache License 2.0 | 5 votes |
public AuthOutcome authenticate() { log.debugf("SamlAuthenticator is using handler [%s]", this.handler); return this.handler.handle(new OnSessionCreated() { @Override public void onSessionCreated(SamlSession samlSession) { completeAuthentication(samlSession); } }); }
Example #16
Source File: HammockKeycloakJaxrsFilter.java From hammock with Apache License 2.0 | 5 votes |
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 #17
Source File: KeycloakAuthFilter.java From keycloak-dropwizard-integration with Apache License 2.0 | 5 votes |
public void validateRequest(final ContainerRequestContext requestContext) { if (requestContext.getSecurityContext().getUserPrincipal() != null) { // the user is already authenticated, further processing is not necessary return; } Request request = Request.getBaseRequest((ServletRequest) requestContext.getProperty(HttpServletRequest.class.getName())); JaxrsHttpFacade facade = new JaxrsHttpFacade(requestContext, requestContext.getSecurityContext()); request.setAttribute(AdapterDeploymentContext.class.getName(), deploymentContext); KeycloakDeployment deployment = deploymentContext.resolveDeployment(facade); if (deployment == null || !deployment.isConfigured()) { return; } AdapterTokenStore tokenStore = getTokenStore(request, facade, deployment); tokenStore.checkCurrentToken(); JettyRequestAuthenticator authenticator = createRequestAuthenticator(request, facade, deployment, tokenStore); AuthOutcome outcome = authenticator.authenticate(); if (outcome == AuthOutcome.AUTHENTICATED) { return; } AuthChallenge challenge = authenticator.getChallenge(); if (challenge != null) { challenge.challenge(facade); if (!adapterConfig.isBearerOnly()) { // create session and set cookie for client facade.getResponse().setCookie("JSESSIONID", request.getSession().getId(), "/", null, -1, false, false); } facade.getResponse().end(); } }
Example #18
Source File: AbstractSamlAuthenticationHandler.java From keycloak with Apache License 2.0 | 4 votes |
private AuthOutcome failed(AuthChallenge challenge) { this.challenge = challenge; return AuthOutcome.FAILED; }
Example #19
Source File: AbstractSamlAuthenticationHandler.java From keycloak with Apache License 2.0 | 4 votes |
protected AuthOutcome handleSamlRequest(String samlRequest, String relayState) { SAMLDocumentHolder holder = null; boolean postBinding = false; String requestUri = facade.getRequest().getURI(); if (facade.getRequest().getMethod().equalsIgnoreCase("GET")) { // strip out query params int index = requestUri.indexOf('?'); if (index > -1) { requestUri = requestUri.substring(0, index); } holder = SAMLRequestParser.parseRequestRedirectBinding(samlRequest); } else { postBinding = true; holder = SAMLRequestParser.parseRequestPostBinding(samlRequest); } if (holder == null) { log.error("Error parsing SAML document"); return failedTerminal(); } RequestAbstractType requestAbstractType = (RequestAbstractType) holder.getSamlObject(); if (requestAbstractType.getDestination() == null && containsUnencryptedSignature(holder, postBinding)) { log.error("Destination field required."); return failed(CHALLENGE_EXTRACTION_FAILURE); } if (! destinationValidator.validate(requestUri, requestAbstractType.getDestination())) { log.error("Expected destination '" + requestUri + "' got '" + requestAbstractType.getDestination() + "'"); return failedTerminal(); } if (requestAbstractType instanceof LogoutRequestType) { if (deployment.getIDP().getSingleLogoutService().validateRequestSignature()) { try { validateSamlSignature(holder, postBinding, GeneralConstants.SAML_REQUEST_KEY); } catch (VerificationException e) { log.error("Failed to verify saml request signature", e); return failedTerminal(); } } LogoutRequestType logout = (LogoutRequestType) requestAbstractType; return logoutRequest(logout, relayState); } else { log.error("unknown SAML request type"); return failedTerminal(); } }
Example #20
Source File: AbstractSamlAuthenticationHandler.java From keycloak with Apache License 2.0 | 4 votes |
protected AuthOutcome handleRequest() { return AuthOutcome.AUTHENTICATED; }
Example #21
Source File: AbstractSamlAuthenticationHandler.java From keycloak with Apache License 2.0 | 4 votes |
protected AuthOutcome initiateLogin() { challenge = createChallenge(); return AuthOutcome.NOT_ATTEMPTED; }
Example #22
Source File: BrowserHandler.java From keycloak with Apache License 2.0 | 4 votes |
@Override public AuthOutcome handle(OnSessionCreated onCreateSession) { return doHandle(new SamlInvocationContext(null, null, null), onCreateSession); }
Example #23
Source File: KeycloakHttpServerAuthenticationMechanism.java From keycloak with Apache License 2.0 | 4 votes |
@Override public void evaluateRequest(HttpServerRequest request) throws HttpAuthenticationException { LOGGER.debugf("Evaluating request for path [%s]", request.getRequestURI()); SamlDeploymentContext deploymentContext = getDeploymentContext(request); if (deploymentContext == null) { LOGGER.debugf("Ignoring request for path [%s] from mechanism [%s]. No deployment context found.", request.getRequestURI(), getMechanismName()); request.noAuthenticationInProgress(); return; } ElytronHttpFacade httpFacade = new ElytronHttpFacade(request, getSessionIdMapper(request), getSessionIdMapperUpdater(request), deploymentContext, callbackHandler); SamlDeployment deployment = httpFacade.getDeployment(); if (!deployment.isConfigured()) { request.noAuthenticationInProgress(); return; } if (deployment.getLogoutPage() != null && httpFacade.getRequest().getRelativePath().contains(deployment.getLogoutPage())) { LOGGER.debugf("Ignoring request for [%s] and logout page [%s].", request.getRequestURI(), deployment.getLogoutPage()); httpFacade.authenticationCompleteAnonymous(); return; } SamlAuthenticator authenticator; if (httpFacade.getRequest().getRelativePath().endsWith("/saml")) { authenticator = new ElytronSamlEndpoint(httpFacade, deployment); } else { authenticator = new ElytronSamlAuthenticator(httpFacade, deployment, callbackHandler); } AuthOutcome outcome = authenticator.authenticate(); if (outcome == AuthOutcome.AUTHENTICATED) { httpFacade.authenticationComplete(); return; } if (outcome == AuthOutcome.NOT_AUTHENTICATED) { httpFacade.noAuthenticationInProgress(null); return; } if (outcome == AuthOutcome.LOGGED_OUT) { if (deployment.getLogoutPage() != null) { redirectLogout(deployment, httpFacade); } httpFacade.authenticationInProgress(); return; } AuthChallenge challenge = authenticator.getChallenge(); if (challenge != null) { httpFacade.noAuthenticationInProgress(challenge); return; } if (outcome == AuthOutcome.FAILED) { httpFacade.authenticationFailed(); return; } httpFacade.authenticationInProgress(); }
Example #24
Source File: EcpAuthenticationHandler.java From keycloak with Apache License 2.0 | 4 votes |
@Override protected AuthOutcome logoutRequest(LogoutRequestType request, String relayState) { throw new RuntimeException("Not supported."); }
Example #25
Source File: WebBrowserSsoAuthenticationHandler.java From keycloak with Apache License 2.0 | 4 votes |
@Override public AuthOutcome handle(OnSessionCreated onCreateSession) { return doHandle(new SamlInvocationContext(facade.getRequest().getFirstParam(GeneralConstants.SAML_REQUEST_KEY), facade.getRequest().getFirstParam(GeneralConstants.SAML_RESPONSE_KEY), facade.getRequest().getFirstParam(GeneralConstants.RELAY_STATE)), onCreateSession); }
Example #26
Source File: IdentityServiceRemoteUserMapper.java From alfresco-repository with GNU Lesser General Public License v3.0 | 4 votes |
/** * Extracts the user name from the JWT in the given request. * * @param request The request containing the JWT * @return The user name or null if it can not be determined */ private String extractUserFromHeader(HttpServletRequest request) { String userName = null; IdentityServiceHttpFacade facade = new IdentityServiceHttpFacade(request); // try authenticating with bearer token first if (logger.isDebugEnabled()) { logger.debug("Trying bearer token..."); } AlfrescoBearerTokenRequestAuthenticator tokenAuthenticator = new AlfrescoBearerTokenRequestAuthenticator(this.keycloakDeployment); AuthOutcome tokenOutcome = tokenAuthenticator.authenticate(facade); if (logger.isDebugEnabled()) { logger.debug("Bearer token outcome: " + tokenOutcome); } if (tokenOutcome == AuthOutcome.FAILED && !isValidationFailureSilent) { throw new AuthenticationException("Token validation failed: " + tokenAuthenticator.getValidationFailureDescription()); } if (tokenOutcome == AuthOutcome.AUTHENTICATED) { userName = extractUserFromToken(tokenAuthenticator.getToken()); } else { if (logger.isDebugEnabled()) { logger.debug("User could not be authenticated by IdentityServiceRemoteUserMapper."); } } return userName; }
Example #27
Source File: AbstractSamlAuthenticator.java From keycloak with Apache License 2.0 | 4 votes |
@Override public Authentication validateRequest(ServletRequest req, ServletResponse res, boolean mandatory) throws ServerAuthException { if (log.isTraceEnabled()) { log.trace("*** authenticate"); } Request request = resolveRequest(req); JettyHttpFacade facade = new JettyHttpFacade(request, (HttpServletResponse) res); SamlDeployment deployment = deploymentContext.resolveDeployment(facade); if (deployment == null || !deployment.isConfigured()) { log.debug("*** deployment isn't configured return false"); return Authentication.UNAUTHENTICATED; } boolean isEndpoint = request.getRequestURI().substring(request.getContextPath().length()).endsWith("/saml"); if (!mandatory && !isEndpoint) return new DeferredAuthentication(this); JettySamlSessionStore tokenStore = getTokenStore(request, facade, deployment); SamlAuthenticator authenticator = null; if (isEndpoint) { authenticator = new SamlAuthenticator(facade, deployment, tokenStore) { @Override protected void completeAuthentication(SamlSession account) { } @Override protected SamlAuthenticationHandler createBrowserHandler(HttpFacade facade, SamlDeployment deployment, SamlSessionStore sessionStore) { return new SamlEndpoint(facade, deployment, sessionStore); } }; } else { authenticator = new SamlAuthenticator(facade, deployment, tokenStore) { @Override protected void completeAuthentication(SamlSession account) { } @Override protected SamlAuthenticationHandler createBrowserHandler(HttpFacade facade, SamlDeployment deployment, SamlSessionStore sessionStore) { return new BrowserHandler(facade, deployment, sessionStore); } }; } AuthOutcome outcome = authenticator.authenticate(); if (outcome == AuthOutcome.AUTHENTICATED) { if (facade.isEnded()) { return Authentication.SEND_SUCCESS; } SamlSession samlSession = tokenStore.getAccount(); Authentication authentication = register(request, samlSession); return authentication; } if (outcome == AuthOutcome.LOGGED_OUT) { logoutCurrent(request); if (deployment.getLogoutPage() != null) { forwardToLogoutPage(request, (HttpServletResponse)res, deployment); } return Authentication.SEND_CONTINUE; } AuthChallenge challenge = authenticator.getChallenge(); if (challenge != null) { challenge.challenge(facade); } return Authentication.SEND_CONTINUE; }
Example #28
Source File: AbstractSamlAuthMech.java From keycloak with Apache License 2.0 | 4 votes |
/** * Call this inside your authenticate method. */ public AuthenticationMechanismOutcome authenticate(HttpServerExchange exchange, SecurityContext securityContext) { UndertowHttpFacade facade = createFacade(exchange); SamlDeployment deployment = deploymentContext.resolveDeployment(facade); if (!deployment.isConfigured()) { return AuthenticationMechanismOutcome.NOT_ATTEMPTED; } SamlSessionStore sessionStore = getTokenStore(exchange, facade, deployment, securityContext); SamlAuthenticator authenticator = null; if (exchange.getRequestPath().endsWith("/saml")) { authenticator = new UndertowSamlEndpoint(facade, deploymentContext.resolveDeployment(facade), sessionStore); } else { authenticator = new UndertowSamlAuthenticator(securityContext, facade, deploymentContext.resolveDeployment(facade), sessionStore); } AuthOutcome outcome = authenticator.authenticate(); if (outcome == AuthOutcome.AUTHENTICATED) { registerNotifications(securityContext); return AuthenticationMechanismOutcome.AUTHENTICATED; } if (outcome == AuthOutcome.NOT_AUTHENTICATED) { // we are in passive mode and user is not authenticated, let app server to try another auth mechanism // See KEYCLOAK-2107, AbstractSamlAuthenticationHandler return AuthenticationMechanismOutcome.NOT_ATTEMPTED; } if (outcome == AuthOutcome.LOGGED_OUT) { securityContext.logout(); if (deployment.getLogoutPage() != null) { redirectLogout(deployment, exchange); } return AuthenticationMechanismOutcome.NOT_ATTEMPTED; } AuthChallenge challenge = authenticator.getChallenge(); if (challenge != null) { exchange.putAttachment(KEYCLOAK_CHALLENGE_ATTACHMENT_KEY, challenge); if (authenticator instanceof UndertowSamlEndpoint) { exchange.getSecurityContext().setAuthenticationRequired(); } } if (outcome == AuthOutcome.FAILED) { return AuthenticationMechanismOutcome.NOT_AUTHENTICATED; } return AuthenticationMechanismOutcome.NOT_ATTEMPTED; }
Example #29
Source File: SamlFilter.java From keycloak with Apache License 2.0 | 4 votes |
@Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) res; ServletHttpFacade facade = new ServletHttpFacade(request, response); SamlDeployment deployment = deploymentContext.resolveDeployment(facade); if (deployment == null || !deployment.isConfigured()) { response.sendError(403); log.fine("deployment not configured"); return; } FilterSamlSessionStore tokenStore = new FilterSamlSessionStore(request, facade, 100000, idMapper, deployment); boolean isEndpoint = request.getRequestURI().substring(request.getContextPath().length()).endsWith("/saml"); SamlAuthenticator authenticator; if (isEndpoint) { authenticator = new SamlAuthenticator(facade, deployment, tokenStore) { @Override protected void completeAuthentication(SamlSession account) { } @Override protected SamlAuthenticationHandler createBrowserHandler(HttpFacade facade, SamlDeployment deployment, SamlSessionStore sessionStore) { return new SamlEndpoint(facade, deployment, sessionStore); } }; } else { authenticator = new SamlAuthenticator(facade, deployment, tokenStore) { @Override protected void completeAuthentication(SamlSession account) { } @Override protected SamlAuthenticationHandler createBrowserHandler(HttpFacade facade, SamlDeployment deployment, SamlSessionStore sessionStore) { return new BrowserHandler(facade, deployment, sessionStore); } }; } AuthOutcome outcome = authenticator.authenticate(); if (outcome == AuthOutcome.AUTHENTICATED) { log.fine("AUTHENTICATED"); if (facade.isEnded()) { return; } HttpServletRequestWrapper wrapper = tokenStore.getWrap(); chain.doFilter(wrapper, res); return; } if (outcome == AuthOutcome.LOGGED_OUT) { tokenStore.logoutAccount(); String logoutPage = deployment.getLogoutPage(); if (logoutPage != null) { if (PROTOCOL_PATTERN.matcher(logoutPage).find()) { response.sendRedirect(logoutPage); log.log(Level.FINE, "Redirected to logout page {0}", logoutPage); } else { RequestDispatcher disp = req.getRequestDispatcher(logoutPage); disp.forward(req, res); } return; } chain.doFilter(req, res); return; } AuthChallenge challenge = authenticator.getChallenge(); if (challenge != null) { log.fine("challenge"); challenge.challenge(facade); return; } if (deployment.isIsPassive() && outcome == AuthOutcome.NOT_AUTHENTICATED) { log.fine("PASSIVE_NOT_AUTHENTICATED"); if (facade.isEnded()) { return; } chain.doFilter(req, res); return; } if (!facade.isEnded()) { response.sendError(403); } }
Example #30
Source File: KeycloakHttpServerAuthenticationMechanism.java From keycloak with Apache License 2.0 | 4 votes |
@Override public void evaluateRequest(HttpServerRequest request) throws HttpAuthenticationException { LOGGER.debugf("Evaluating request for path [%s]", request.getRequestURI()); AdapterDeploymentContext deploymentContext = getDeploymentContext(request); if (deploymentContext == null) { LOGGER.debugf("Ignoring request for path [%s] from mechanism [%s]. No deployment context found.", request.getRequestURI(), getMechanismName()); request.noAuthenticationInProgress(); return; } ElytronHttpFacade httpFacade = new ElytronHttpFacade(request, deploymentContext, callbackHandler); KeycloakDeployment deployment = httpFacade.getDeployment(); if (!deployment.isConfigured()) { request.noAuthenticationInProgress(); return; } RequestAuthenticator authenticator = createRequestAuthenticator(request, httpFacade, deployment); httpFacade.getTokenStore().checkCurrentToken(); if (preActions(httpFacade, deploymentContext)) { LOGGER.debugf("Pre-actions has aborted the evaluation of [%s]", request.getRequestURI()); httpFacade.authenticationInProgress(); return; } AuthOutcome outcome = authenticator.authenticate(); if (AuthOutcome.AUTHENTICATED.equals(outcome)) { if (new AuthenticatedActionsHandler(deployment, httpFacade).handledRequest()) { httpFacade.authenticationInProgress(); } else { httpFacade.authenticationComplete(); } return; } AuthChallenge challenge = authenticator.getChallenge(); if (challenge != null) { httpFacade.noAuthenticationInProgress(challenge); return; } if (AuthOutcome.FAILED.equals(outcome)) { httpFacade.getResponse().setStatus(403); httpFacade.authenticationFailed(); return; } httpFacade.noAuthenticationInProgress(); }