Java源码示例:org.eclipse.jetty.security.authentication.SessionAuthentication

示例1
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response)
    throws IOException, ServletException {

  Preconditions.checkState(securityHandlers.size() > 0);

  HttpSession session = request.getSession(true);
  SessionAuthentication authentication =
      (SessionAuthentication) session.getAttribute(SessionAuthentication.__J_AUTHENTICATED);
  String uri = request.getRequestURI();
  final DrillHttpConstraintSecurityHandler securityHandler;

  // Before authentication, all requests go through the FormAuthenticator if configured except for /spnegoLogin
  // request. For SPNEGO authentication all requests will be forced going via /spnegoLogin before authentication is
  // done, this is to ensure that we don't have to authenticate same client session multiple times for each resource.
  //
  // If this authentication is null, user hasn't logged in yet
  if (authentication == null) {

    // 1) If only SPNEGOSecurity handler then use SPNEGOSecurity
    // 2) If both but uri equals spnegoLogin then use SPNEGOSecurity
    // 3) If both but uri doesn't equals spnegoLogin then use FORMSecurity
    // 4) If only FORMSecurity handler then use FORMSecurity
    if (isSpnegoEnabled() && (!isFormEnabled() || uri.equals(WebServerConstants.SPENGO_LOGIN_RESOURCE_PATH))) {
      securityHandler = securityHandlers.get(Constraint.__SPNEGO_AUTH);
      securityHandler.handle(target, baseRequest, request, response);
    } else if (isFormEnabled()) {
      securityHandler = securityHandlers.get(Constraint.__FORM_AUTH);
      securityHandler.handle(target, baseRequest, request, response);
    }
  }
  // If user has logged in, use the corresponding handler to handle the request
  else {
    final String authMethod = authentication.getAuthMethod();
    securityHandler = securityHandlers.get(authMethod);
    securityHandler.handle(target, baseRequest, request, response);
  }
}
 
示例2
/**
 * 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);
}
 
示例3
public UserIdentity login(String username, Object password, ServletRequest request) {
  final UserIdentity user = super.login(username, password, request);

  if (user != null) {
    final HttpSession session = ((HttpServletRequest) request).getSession(true);
    final Authentication cached = new SessionAuthentication(this.getAuthMethod(), user, password);
    session.setAttribute(SessionAuthentication.__J_AUTHENTICATED, cached);
  }

  return user;
}
 
示例4
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;
    }
}
 
示例5
private Authentication handleCachedAuthentication(HttpServletRequest request, HttpServletResponse response,
                                                  HttpSession session, FedizContext fedConfig) throws IOException {
    Authentication authentication =
        (Authentication) session.getAttribute(SessionAuthentication.__J_AUTHENTICATED);
    if (authentication != null) {
        // Has authentication been revoked?
        if (authentication instanceof Authentication.User
            && isTokenExpired(fedConfig, ((Authentication.User)authentication).getUserIdentity())) {
            session.removeAttribute(SessionAuthentication.__J_AUTHENTICATED);
        } else {
            //logout
            String action = request.getParameter(FederationConstants.PARAM_ACTION);
            boolean logout = FederationConstants.ACTION_SIGNOUT.equals(action);
            String logoutUrl = fedConfig.getLogoutURL();

            String uri = request.getRequestURI();
            if (uri == null) {
                uri = URIUtil.SLASH;
            }

            String contextName = request.getSession().getServletContext().getContextPath();
            if (contextName == null || contextName.isEmpty()) {
                contextName = "/";
            }

            if (logout || logoutUrl != null && !logoutUrl.isEmpty() && uri.equals(contextName + logoutUrl)) {
                session.invalidate();

                FedizProcessor wfProc =
                    FedizProcessorFactory.newFedizProcessor(fedConfig.getProtocol());
                signOutRedirectToIssuer(request, response, wfProc);

                return Authentication.SEND_CONTINUE;
            }

            String jUri = (String)session.getAttribute(J_URI);
            @SuppressWarnings("unchecked")
            MultiMap<String> jPost = (MultiMap<String>)session.getAttribute(J_POST);
            if (jUri != null && jPost != null) {
                StringBuffer buf = request.getRequestURL();
                if (request.getQueryString() != null) {
                    buf.append('?').append(request.getQueryString());
                }

                if (jUri.equals(buf.toString())) {
                    // This is a retry of an original POST request
                    // so restore method and parameters

                    session.removeAttribute(J_POST);
                    Request baseRequest = (Request)request;
                    // (req instanceof Request)?(Request)
                    // req:HttpConnection.getCurrentConnection().getRequest();
                    baseRequest.setMethod(HttpMethod.POST.asString());
                    baseRequest.setQueryParameters(jPost);
                }
            } else if (jUri != null) {
                session.removeAttribute(J_URI);
            }

            return authentication;
        }
    }
    return null;
}