Java Code Examples for org.eclipse.jetty.server.Authentication#UNAUTHENTICATED

The following examples show how to use org.eclipse.jetty.server.Authentication#UNAUTHENTICATED . 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: AvaticaSpnegoAuthenticator.java    From calcite-avatica with Apache License 2.0 6 votes vote down vote up
/**
 * Jetty has a bug in which if there is an Authorization header sent by a client which is
 * not of the Negotiate type, Jetty does not send the challenge to negotiate. This works
 * around that issue, forcing the challenge to be sent. Will require investigation on
 * upgrade to a newer version of Jetty.
 */
Authentication sendChallengeIfNecessary(Authentication computedAuth, ServletRequest request,
    ServletResponse response) throws IOException {
  if (computedAuth == Authentication.UNAUTHENTICATED) {
    HttpServletRequest req = (HttpServletRequest) request;
    HttpServletResponse res = (HttpServletResponse) response;

    String header = req.getHeader(HttpHeader.AUTHORIZATION.asString());
    // We have an authorization header, but it's not Negotiate
    if (header != null && !header.startsWith(HttpHeader.NEGOTIATE.asString())) {
      LOG.debug("Client sent Authorization header that was not for Negotiate,"
          + " sending challenge anyways.");
      if (DeferredAuthentication.isDeferred(res)) {
        return Authentication.UNAUTHENTICATED;
      }

      res.setHeader(HttpHeader.WWW_AUTHENTICATE.asString(), HttpHeader.NEGOTIATE.asString());
      res.sendError(HttpServletResponse.SC_UNAUTHORIZED);
      return Authentication.SEND_CONTINUE;
    }
  }
  return computedAuth;
}
 
Example 2
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 3
Source File: JettyTokenAuthenticator.java    From cloud-security-xsuaa-integration with Apache License 2.0 5 votes vote down vote up
@Override
public Authentication validateRequest(ServletRequest request, ServletResponse response, boolean mandatory) {
	TokenAuthenticationResult tokenAuthenticationResult = tokenAuthenticator.validateRequest(request, response);
	if (tokenAuthenticationResult.isAuthenticated()) {
		return createAuthentication(tokenAuthenticationResult);
	} else {
		sendUnauthenticatedResponse(response, tokenAuthenticationResult.getUnauthenticatedReason());
		return Authentication.UNAUTHENTICATED;
	}
}
 
Example 4
Source File: JettyTokenAuthenticator.java    From cloud-security-xsuaa-integration with Apache License 2.0 5 votes vote down vote up
@Override
public Authentication validateRequest(ServletRequest request, ServletResponse response, boolean mandatory) {
	TokenAuthenticationResult tokenAuthenticationResult = tokenAuthenticator.validateRequest(request, response);
	if (tokenAuthenticationResult.isAuthenticated()) {
		return createAuthentication(tokenAuthenticationResult);
	} else {
		sendUnauthenticatedResponse(response, tokenAuthenticationResult.getUnauthenticatedReason());
		return Authentication.UNAUTHENTICATED;
	}
}
 
Example 5
Source File: SpnegoTestUtil.java    From calcite-avatica with Apache License 2.0 5 votes vote down vote up
@Override public void handle(String target, Request baseRequest, HttpServletRequest request,
    HttpServletResponse response) throws IOException, ServletException {
  Authentication auth = baseRequest.getAuthentication();
  if (Authentication.UNAUTHENTICATED == auth) {
    throw new AssertionError("Unauthenticated users should not reach here!");
  }

  baseRequest.setHandled(true);
  UserAuthentication userAuth = (UserAuthentication) auth;
  UserIdentity userIdentity = userAuth.getUserIdentity();
  Principal userPrincipal = userIdentity.getUserPrincipal();

  response.getWriter().print("OK " + userPrincipal.getName());
  response.setStatus(200);
}
 
Example 6
Source File: FederationAuthenticator.java    From cxf-fediz with Apache License 2.0 4 votes vote down vote up
private Authentication handleSignInRequest(HttpServletRequest request, HttpServletResponse response,
                                           HttpSession session, FedizContext fedConfig) throws IOException {
    FedizResponse wfRes = null;
    if (LOG.isDebugEnabled()) {
        LOG.debug("SignIn request found");
    }

    String action = request.getParameter(FederationConstants.PARAM_ACTION);
    String responseToken = getResponseToken(request, fedConfig);
    if (responseToken == null) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("SignIn request must contain a response token from the IdP");
        }
        response.sendError(HttpServletResponse.SC_BAD_REQUEST);
        return Authentication.SEND_FAILURE;
    } else {

        FedizRequest wfReq = new FedizRequest();
        wfReq.setAction(action);
        wfReq.setResponseToken(responseToken);
        wfReq.setState(getState(request));
        wfReq.setRequest(request);
        wfReq.setRequestState((RequestState) session.getAttribute(J_CONTEXT));

        X509Certificate[] certs =
            (X509Certificate[])request.getAttribute("javax.servlet.request.X509Certificate");
        wfReq.setCerts(certs);

        FederationLoginService fedLoginService = (FederationLoginService)this._loginService;
        UserIdentity user = fedLoginService.login(null, wfReq, fedConfig);
        if (user != null) {
            session = renewSession(request, response);

            // Redirect to original request
            String nuri;
            synchronized (session) {
                // Check the context
                RequestState savedRequestState = (RequestState) session.getAttribute(J_CONTEXT);
                String receivedContext = getState(request);
                if (savedRequestState == null || !savedRequestState.getState().equals(receivedContext)) {
                    LOG.warn("The received wctx/RelayState parameter does not match the saved value");
                    response.sendError(HttpServletResponse.SC_FORBIDDEN);
                    return Authentication.UNAUTHENTICATED;
                }

                nuri = (String) session.getAttribute(J_URI);

                if (nuri == null || nuri.length() == 0) {
                    nuri = request.getContextPath();
                    if (nuri.length() == 0) {
                        nuri = URIUtil.SLASH;
                    }
                }
                Authentication cached = new SessionAuthentication(getAuthMethod(), user, wfRes);
                session.setAttribute(SessionAuthentication.__J_AUTHENTICATED, cached);
            }

            FederationUserIdentity fui = (FederationUserIdentity)user;
            session.setAttribute(SECURITY_TOKEN_ATTR, fui.getToken());

            response.setContentLength(0);
            response.sendRedirect(response.encodeRedirectURL(nuri));

            return new FederationAuthentication(getAuthMethod(), user);
        }

        // not authenticated
        if (LOG.isDebugEnabled()) {
            LOG.debug("WSFED authentication FAILED");
        }
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        return Authentication.UNAUTHENTICATED;
    }
}
 
Example 7
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 8
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;
}