org.eclipse.jetty.security.ServerAuthException Java Examples

The following examples show how to use org.eclipse.jetty.security.ServerAuthException. 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: TestInvokeHttpCommon.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse
        response)throws IOException, ServletException {
    baseRequest.setHandled(true);

    try {
        Authentication authentication = digestAuthenticator.validateRequest(request, response, true);

        if (authentication instanceof Authentication.User) {
            response.setContentType("text/plain");
            Authentication.User user = (Authentication.User) authentication;
            response.getWriter().println(user.getAuthMethod());
        } else if (authentication instanceof Authentication.ResponseSent) {
            Authentication.ResponseSent responseSent = (Authentication.ResponseSent) authentication;
        }
    } catch (ServerAuthException e) {
        e.printStackTrace();
    }
}
 
Example #2
Source File: JwtAuthenticatorTest.java    From cruise-control with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Test
public void testRedirect() throws IOException, ServerAuthException {
  JwtAuthenticator authenticator = new JwtAuthenticator(TOKEN_PROVIDER, JWT_TOKEN);

  HttpServletRequest request = mock(HttpServletRequest.class);
  expect(request.getMethod()).andReturn(HttpMethod.GET.asString());
  expect(request.getQueryString()).andReturn(null);
  expect(request.getHeader(HttpHeader.AUTHORIZATION.asString())).andReturn(null);
  expect(request.getCookies()).andReturn(new Cookie[] {});
  expect(request.getRequestURL()).andReturn(new StringBuffer(CRUISE_CONTROL_ENDPOINT));

  HttpServletResponse response = mock(HttpServletResponse.class);
  response.sendRedirect(TOKEN_PROVIDER.replace(JwtAuthenticator.REDIRECT_URL, CRUISE_CONTROL_ENDPOINT));
  expectLastCall().andVoid();

  replay(request, response);
  Authentication actualAuthentication = authenticator.validateRequest(request, response, true);
  verify(request, response);
  assertEquals(Authentication.SEND_CONTINUE, actualAuthentication);
}
 
Example #3
Source File: TestInvokeHttpCommon.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse
        response)throws IOException, ServletException {
    baseRequest.setHandled(true);

    try {
        Authentication authentication = digestAuthenticator.validateRequest(request, response, true);

        if (authentication instanceof Authentication.User) {
            response.setContentType("text/plain");
            Authentication.User user = (Authentication.User) authentication;
            response.getWriter().println(user.getAuthMethod());
        } else if (authentication instanceof Authentication.ResponseSent) {
            Authentication.ResponseSent responseSent = (Authentication.ResponseSent) authentication;
        }
    } catch (ServerAuthException e) {
        e.printStackTrace();
    }
}
 
Example #4
Source File: SpnegoAuthenticatorEx.java    From sql-layer with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public Authentication validateRequest(ServletRequest request, ServletResponse response, boolean mandatory) throws ServerAuthException {
    Authentication result = super.validateRequest(request, response, mandatory);
    if ((result == Authentication.UNAUTHENTICATED) &&
        mandatory &&
        !DeferredAuthentication.isDeferred((HttpServletResponse)response)) {
        LOG.debug("SpengoAuthenticatorEx: unauthenticated -> forbidden");
        try {
            ((HttpServletResponse)response).sendError(Response.SC_FORBIDDEN,
                                                      "negotiation failure");
        }
        catch (IOException ex) {
            throw new ServerAuthException(ex);
        }
        result = Authentication.SEND_FAILURE;
    }
    return result;
}
 
Example #5
Source File: ActivationAuthenticator.java    From datacollector with Apache License 2.0 6 votes vote down vote up
@Override
public Authentication validateRequest(
    ServletRequest request, ServletResponse response, boolean mandatory
) throws ServerAuthException {
  Authentication authentication = authenticator.validateRequest(request, response, mandatory);
  if (authentication instanceof Authentication.User) {
    Activation.Info activationInfo = activation.getInfo();
    if (activation.isEnabled() && !activationInfo.isValid()) {
      boolean hasTrial = activationInfo.getExpiration() > 0;
      authentication = new ExpiredActivationUser(
          (Authentication.User) authentication,
          hasTrial ? TRIAL_ALLOWED_ROLES : NO_TRIAL_ALLOWED_ROLES
      );
    }
  }
  return authentication;
}
 
Example #6
Source File: AbstractSSOAuthenticator.java    From datacollector with Apache License 2.0 6 votes vote down vote up
protected Authentication returnUnauthorized(
    HttpServletRequest httpReq,
    HttpServletResponse httpRes,
    Map errorReason,
    String principalId,
    String logMessageTemplate
) throws ServerAuthException {
  if (getLog().isDebugEnabled()) {
    getLog().debug(logMessageTemplate, getRequestInfoForLogging(httpReq, principalId));
  }
  try {
    httpRes.setHeader(HttpHeader.WWW_AUTHENTICATE.asString(), "dpm");
    httpRes.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    httpRes.setContentType("application/json");
    OBJECT_MAPPER.writeValue(httpRes.getWriter(), errorReason);
    return Authentication.SEND_FAILURE;
  } catch (IOException ex) {
    throw new ServerAuthException(Utils.format("Could send a Unauthorized (401) response: {}", ex.toString(), ex));
  }
}
 
Example #7
Source File: SSOUserAuthenticator.java    From datacollector with Apache License 2.0 6 votes vote down vote up
Authentication redirectToLogin(HttpServletRequest httpReq, HttpServletResponse httpRes) throws ServerAuthException {
  boolean repeatedRedirect = httpReq.getParameter(SSOConstants.REPEATED_REDIRECT_PARAM) != null;
  String urlToLogin = getLoginUrl(httpReq, repeatedRedirect);
  try {
    LOG.debug("Redirecting to login '{}'", urlToLogin);
    if (doMetaRedirectToSso) {
      httpRes.setContentType("text/html");
      httpRes.setStatus(HttpServletResponse.SC_OK);
      httpRes.getWriter().println(String.format(HTML_META_REDIRECT, urlToLogin));
    } else {
      httpRes.sendRedirect(urlToLogin);
    }
    return Authentication.SEND_CONTINUE;
  } catch (IOException ex) {
    throw new ServerAuthException(Utils.format("Could not redirect to '{}': {}", urlToLogin, ex.toString(), ex));
  }
}
 
Example #8
Source File: SSOAuthenticator.java    From datacollector with Apache License 2.0 6 votes vote down vote up
Authentication validateRequestDelegation(ServletRequest request, ServletResponse response, boolean mandatory)
    throws ServerAuthException {
  Authenticator auth = userAuthenticator;
  HttpServletRequest httpReq = (HttpServletRequest) request;
  boolean isRestCall = httpReq.getHeader(SSOConstants.X_REST_CALL) != null;
  boolean isAppCall = httpReq.getHeader(SSOConstants.X_APP_AUTH_TOKEN) != null ||
      httpReq.getHeader(SSOConstants.X_APP_COMPONENT_ID) != null;
  if (isAppCall && isRestCall) {
    auth = appAuthenticator;
    if (getLog().isTraceEnabled()) {
      getLog().trace("App request '{}'", getRequestInfoForLogging(httpReq, "?"));
    }
  } else {
    if (getLog().isTraceEnabled()) {
      getLog().trace("User request '{}'", getRequestInfoForLogging(httpReq, "?"));
    }
  }
  return auth.validateRequest(request, response, mandatory);
}
 
Example #9
Source File: SSOAppAuthenticator.java    From datacollector with Apache License 2.0 5 votes vote down vote up
@Override
public Authentication validateRequest(ServletRequest request, ServletResponse response, boolean mandatory)
    throws ServerAuthException {
  HttpServletRequest httpReq = (HttpServletRequest) request;
  HttpServletResponse httpRes = (HttpServletResponse) response;
  Authentication ret;
  String componentId = getAppComponentId(httpReq);
  if (!mandatory) {
    if (LOG.isDebugEnabled()) {
      LOG.trace("URL '{}' does not require authentication", getRequestInfoForLogging(httpReq, componentId));
    }
    ret = Authentication.NOT_CHECKED;
  } else {
    if (((HttpServletRequest) request).getHeader(SSOConstants.X_REST_CALL) == null) {
      ret = returnUnauthorized(httpReq, httpRes, componentId, "Not a REST call: {}");
    } else {
      String authToken = getAppAuthToken(httpReq);
      if (authToken == null) {
        ret = returnUnauthorized(httpReq, httpRes, componentId, "Missing app authentication token: {}");
      } else if (componentId == null) {
        ret = returnUnauthorized(httpReq, httpRes, null, "Missing component ID: {}");
      } else {
        try {
          SSOPrincipal principal = getSsoService().validateAppToken(authToken, componentId);
          if (principal != null) {
            ret = new SSOAuthenticationUser(principal);
          } else {
            ret = returnUnauthorized(httpReq, httpRes, componentId, "Invalid app authentication token: {}");
          }
        } catch (ForbiddenException fex) {
          ret = returnUnauthorized(httpReq, httpRes, fex.getErrorInfo(), componentId, "Request: {}");
        }
      }
    }
  }
  return ret;
}
 
Example #10
Source File: ProxyAuthenticator.java    From datacollector with Apache License 2.0 5 votes vote down vote up
@Override
public boolean secureResponse(
    ServletRequest request,
    ServletResponse response,
    boolean mandatory,
    Authentication.User validatedUser
) throws ServerAuthException {
  return authenticator.secureResponse(request, response, mandatory, validatedUser);
}
 
Example #11
Source File: DrillSpnegoAuthenticator.java    From Bats with Apache License 2.0 5 votes vote down vote up
/**
 * Updated logic as compared to default implementation in
 * {@link SpnegoAuthenticator#validateRequest(ServletRequest, ServletResponse, boolean)} to handle below cases:
 * 1) Perform SPNEGO authentication only when spnegoLogin resource is requested. This helps to avoid authentication
 *    for each and every resource which the JETTY provided authenticator does.
 * 2) Helps to redirect to the target URL after authentication is done successfully.
 * 3) Clear-Up in memory session information once LogOut is triggered such that any future request also triggers SPNEGO
 *    authentication.
 * @param request
 * @param response
 * @param mandatoryAuth
 * @return
 * @throws ServerAuthException
 */
@Override
public Authentication validateRequest(ServletRequest request, ServletResponse response, boolean mandatoryAuth)
    throws ServerAuthException {

  final HttpServletRequest req = (HttpServletRequest) request;
  final HttpSession session = req.getSession(true);
  final Authentication authentication = (Authentication) session.getAttribute(SessionAuthentication.__J_AUTHENTICATED);
  final String uri = req.getRequestURI();

  // If the Request URI is for /spnegoLogin then perform login
  final boolean mandatory = mandatoryAuth || uri.equals(WebServerConstants.SPENGO_LOGIN_RESOURCE_PATH);

  // For logout remove the attribute from the session that holds UserIdentity
  if (authentication != null) {
    if (uri.equals(WebServerConstants.LOGOUT_RESOURCE_PATH)) {
      logger.debug("Logging out user {}", req.getRemoteAddr());
      session.removeAttribute(SessionAuthentication.__J_AUTHENTICATED);
      return null;
    }

    // Already logged in so just return the session attribute.
    return authentication;
  }

  // Try to authenticate an unauthenticated session.
  return authenticateSession(request, response, mandatory);
}
 
Example #12
Source File: SSOAuthenticator.java    From datacollector with Apache License 2.0 5 votes vote down vote up
@Override
public Authentication validateRequest(ServletRequest request, ServletResponse response, boolean mandatory)
    throws ServerAuthException {
  SSOPrincipalJson.resetRequestIpAddress();
  Authentication authentication = validateRequestDelegation(request, response, mandatory);
  if (authentication instanceof SSOAuthenticationUser) {
    // if the Authentication is an authenticated user, we set the IP address of the request in it.
    SSOPrincipalUtils.setRequestInfo(((SSOAuthenticationUser)authentication).getSSOUserPrincipal(), request);
  }
  return authentication;
}
 
Example #13
Source File: SSOUserAuthenticator.java    From datacollector with Apache License 2.0 5 votes vote down vote up
@Override
protected Authentication returnUnauthorized(
    HttpServletRequest httpReq, HttpServletResponse httpRes, String principalId, String logMessageTemplate
) throws ServerAuthException {
  Authentication ret;
  httpRes.addCookie(createAuthCookie(httpReq, "", 0));
  if (httpReq.getHeader(SSOConstants.X_REST_CALL) != null) {
    ret = super.returnUnauthorized(httpReq, httpRes, null, logMessageTemplate);
  } else {
    redirectToLogin(httpReq, httpRes);
    ret = Authentication.SEND_FAILURE;
  }
  return ret;
}
 
Example #14
Source File: SSOUserAuthenticator.java    From datacollector with Apache License 2.0 5 votes vote down vote up
Authentication redirectToLogout(HttpServletResponse httpRes) throws ServerAuthException {
  String urlToLogout = getSsoService().getLogoutUrl();
  try {
    LOG.debug("Redirecting to logout '{}'", urlToLogout);
    httpRes.sendRedirect(urlToLogout);
    return Authentication.SEND_SUCCESS;
  } catch (IOException ex) {
    throw new ServerAuthException(Utils.format("Could not redirect to '{}': {}", urlToLogout, ex.toString(), ex));
  }
}
 
Example #15
Source File: SSOUserAuthenticator.java    From datacollector with Apache License 2.0 5 votes vote down vote up
Authentication redirectToSelf(HttpServletRequest httpReq, HttpServletResponse httpRes) throws ServerAuthException {
  String authToken = httpReq.getParameter(SSOConstants.USER_AUTH_TOKEN_PARAM);
  String urlWithoutToken = getRequestUrlWithoutToken(httpReq);
  httpRes.setHeader(SSOConstants.X_USER_AUTH_TOKEN, authToken);
  try {
    LOG.debug("Redirecting to self without token '{}'", urlWithoutToken);
    httpRes.sendRedirect(urlWithoutToken);
    return Authentication.SEND_CONTINUE;
  } catch (IOException ex) {
    throw new ServerAuthException(Utils.format("Could not redirect to '{}': {}", urlWithoutToken, ex.toString(), ex));
  }
}
 
Example #16
Source File: KeycloakDropwizardAuthenticator.java    From keycloak-dropwizard-integration with Apache License 2.0 5 votes vote down vote up
@Override
public Authentication validateRequest(ServletRequest req, ServletResponse res, boolean mandatory)
        throws ServerAuthException {
    HttpServletRequest request = ((HttpServletRequest) req);
    request.setAttribute(HttpServletRequest.class.getName(), request);
    if (!getAdapterConfig().isBearerOnly()
            && request.getQueryString() != null
            && request.getQueryString().contains("code=")) {
        // we receive a code as part of the query string that is returned by OAuth
        // but only assume control is this is not bearer only!
        mandatory = true;
    } else if (request.getHeaders("Authorization").hasMoreElements()) {
        // we receive Authorization, might be Bearer or Basic Auth (both supported by Keycloak)
        mandatory = true;
    }
    HttpSession session = ((HttpServletRequest) req).getSession(false);
    if (session != null && session.getAttribute(JettyAdapterSessionStore.CACHED_FORM_PARAMETERS) != null) {
        // this is a redirect after the code has been received for a FORM
        mandatory = true;
    } else if (session != null && session.getAttribute(KeycloakSecurityContext.class.getName()) != null) {
        // there is an existing authentication in the session, use it
        mandatory = true;
    }
    Authentication authentication = super.validateRequest(req, res, mandatory);
    if (authentication instanceof DeferredAuthentication) {
        // resolving of a deferred authentication later will otherwise lead to a NullPointerException
        authentication = null;
    }
    return authentication;
}
 
Example #17
Source File: CorsBasicAuthenticator.java    From EDDI with Apache License 2.0 5 votes vote down vote up
@Override
public Authentication validateRequest(ServletRequest req, ServletResponse res, boolean mandatory) throws ServerAuthException {
    HttpServletRequest request = (HttpServletRequest) req;
    String credentials = request.getHeader(HttpHeader.AUTHORIZATION.asString());
    if (!RuntimeUtilities.isNullOrEmpty(credentials)) {
        ThreadContext.put("currentuser:credentials", credentials);
    }

    return super.validateRequest(req, res, mandatory);
}
 
Example #18
Source File: AvaticaSpnegoAuthenticator.java    From calcite-avatica with Apache License 2.0 5 votes vote down vote up
@Override public Authentication validateRequest(ServletRequest request,
    ServletResponse response, boolean mandatory) throws ServerAuthException {
  final Authentication computedAuth = super.validateRequest(request, response, mandatory);
  try {
    return sendChallengeIfNecessary(computedAuth, request, response);
  } catch (IOException e) {
    throw new ServerAuthException(e);
  }
}
 
Example #19
Source File: SSOUserAuthenticator.java    From datacollector with Apache License 2.0 4 votes vote down vote up
@Override
public Authentication validateRequest(ServletRequest request, ServletResponse response, boolean mandatory)
    throws ServerAuthException {
  HttpServletRequest httpReq = (HttpServletRequest) request;
  HttpServletResponse httpRes = (HttpServletResponse) response;
  String authToken = getAuthTokenFromRequest(httpReq);

  Authentication ret = null;

  if (LOG.isTraceEnabled()) {
    LOG.trace("Request: {}", getRequestInfoForLogging(httpReq, SSOUtils.tokenForLog(authToken)));
  }

  if (isCORSOptionsRequest(httpReq)) {
    httpRes.setStatus(HttpServletResponse.SC_OK);
    httpRes.setHeader("Access-Control-Allow-Origin", conf.get(CORSConstants.HTTP_ACCESS_CONTROL_ALLOW_ORIGIN,
        CORSConstants.HTTP_ACCESS_CONTROL_ALLOW_ORIGIN_DEFAULT));
    httpRes.setHeader("Access-Control-Allow-Headers", conf.get(CORSConstants.HTTP_ACCESS_CONTROL_ALLOW_HEADERS,
        CORSConstants.HTTP_ACCESS_CONTROL_ALLOW_HEADERS_DEFAULT));
    httpRes.setHeader("Access-Control-Allow-Methods", conf.get(CORSConstants.HTTP_ACCESS_CONTROL_ALLOW_METHODS,
        CORSConstants.HTTP_ACCESS_CONTROL_ALLOW_METHODS_DEFAULT));
    return Authentication.SEND_SUCCESS;
  }

  if (!mandatory) {
    ret = Authentication.NOT_CHECKED;
  } else {
    if (authToken != null) {
      try {
        SSOPrincipal principal = getSsoService().validateUserToken(authToken);
        if (principal != null) {
          SSOAuthenticationUser user = new SSOAuthenticationUser(principal);
          if (isLogoutRequest(httpReq)) {
            if (LOG.isTraceEnabled()) {
              LOG.trace("Principal '{}' Logout", principal.getPrincipalId());
            }
            getSsoService().invalidateUserToken(authToken);
            ret = redirectToLogout(httpRes);
          } else {
            setAuthCookieIfNecessary(httpReq, httpRes, authToken, user.getSSOUserPrincipal().getExpires());
            if (isAuthTokenInQueryString(httpReq)) {
              if (LOG.isTraceEnabled()) {
                LOG.trace(
                    "Redirection to self, principal '{}' request: {}",
                    principal.getPrincipalId(),
                    getRequestInfoForLogging(httpReq, SSOUtils.tokenForLog(authToken))
                );
              }
              ret = redirectToSelf(httpReq, httpRes);
            } else {
              if (LOG.isDebugEnabled()) {
                LOG.debug(
                    "Principal '{}' request: {}",
                    principal.getPrincipalId(),
                    getRequestInfoForLogging(httpReq, SSOUtils.tokenForLog(authToken))
                );
              }
              ret = user;
            }
          }
        }
      } catch (ForbiddenException fex) {
        ret = returnUnauthorized(httpReq, httpRes, fex.getErrorInfo(), null, "Request: {}");
      }
    }
  }
  if (ret == null) {
    ret = returnUnauthorized(httpReq, httpRes, SSOUtils.tokenForLog(authToken), "Could not authenticate: {}");
  }
  return ret;
}
 
Example #20
Source File: AbstractSSOAuthenticator.java    From datacollector with Apache License 2.0 4 votes vote down vote up
@Override
public boolean secureResponse(
    ServletRequest request, ServletResponse response, boolean mandatory, Authentication.User validatedUser
) throws ServerAuthException {
  return true;
}
 
Example #21
Source File: AbstractSSOAuthenticator.java    From datacollector with Apache License 2.0 4 votes vote down vote up
protected Authentication returnUnauthorized(
    HttpServletRequest httpReq, HttpServletResponse httpRes, String principalId, String logMessageTemplate
) throws ServerAuthException {
  return returnUnauthorized(httpReq, httpRes, UNAUTHORIZED_JSON, principalId, logMessageTemplate);
}
 
Example #22
Source File: TestAbstractSSOAuthenticator.java    From datacollector with Apache License 2.0 4 votes vote down vote up
@Override
public Authentication validateRequest(
    ServletRequest request, ServletResponse response, boolean mandatory
) throws ServerAuthException {
  return null;
}
 
Example #23
Source File: ActivationAuthenticator.java    From datacollector with Apache License 2.0 4 votes vote down vote up
@Override
public boolean secureResponse(
    ServletRequest request, ServletResponse response, boolean mandatory, Authentication.User validatedUser
) throws ServerAuthException {
  return authenticator.secureResponse(request, response, mandatory, validatedUser);
}
 
Example #24
Source File: FederationAuthenticator.java    From cxf-fediz with Apache License 2.0 4 votes vote down vote up
public boolean secureResponse(ServletRequest req, ServletResponse res, boolean mandatory,
                              User validatedUser) throws ServerAuthException {
    return true;
}
 
Example #25
Source File: AbstractKeycloakJettyAuthenticator.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Override
public boolean secureResponse(ServletRequest req, ServletResponse res, boolean mandatory, Authentication.User validatedUser) throws ServerAuthException {
    return true;
}
 
Example #26
Source File: AbstractKeycloakJettyAuthenticator.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Override
public Authentication validateRequest(ServletRequest req, ServletResponse res, boolean mandatory) throws ServerAuthException {
    if (log.isTraceEnabled()) {
        log.trace("*** authenticate");
    }
    Request request = resolveRequest(req);
    OIDCJettyHttpFacade facade = new OIDCJettyHttpFacade(request, (HttpServletResponse) res);
    KeycloakDeployment deployment = deploymentContext.resolveDeployment(facade);
    if (deployment == null || !deployment.isConfigured()) {
        log.debug("*** deployment isn't configured return false");
        return Authentication.UNAUTHENTICATED;
    }
    PreAuthActionsHandler handler = new PreAuthActionsHandler(createSessionManagement(request), deploymentContext, facade);
    if (handler.handleRequest()) {
        return Authentication.SEND_SUCCESS;
    }
    if (!mandatory)
        return new DeferredAuthentication(this);
    AdapterTokenStore tokenStore = getTokenStore(request, facade, deployment);
    nodesRegistrationManagement.tryRegister(deployment);

    tokenStore.checkCurrentToken();
    JettyRequestAuthenticator authenticator = createRequestAuthenticator(request, facade, deployment, tokenStore);
    AuthOutcome outcome = authenticator.authenticate();
    if (outcome == AuthOutcome.AUTHENTICATED) {
        if (facade.isEnded()) {
            return Authentication.SEND_SUCCESS;
        }

        Authentication authentication = register(request, authenticator.principal);
        AuthenticatedActionsHandler authenticatedActionsHandler = new AuthenticatedActionsHandler(deployment, facade);
        if (authenticatedActionsHandler.handledRequest()) {
            return Authentication.SEND_SUCCESS;
        }
        return authentication;

    }
    AuthChallenge challenge = authenticator.getChallenge();
    if (challenge != null) {
        challenge.challenge(facade);
    }
    return Authentication.SEND_CONTINUE;
}
 
Example #27
Source File: AbstractSamlAuthenticator.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Override
public boolean secureResponse(ServletRequest req, ServletResponse res, boolean mandatory, Authentication.User validatedUser) throws ServerAuthException {
    return true;
}
 
Example #28
Source File: AbstractSamlAuthenticator.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@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;
}