类org.eclipse.jetty.server.Authentication源码实例Demo

下面列出了怎么用org.eclipse.jetty.server.Authentication的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: localization_nifi   文件: TestInvokeHttpCommon.java
@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();
    }
}
 
源代码2 项目: cruise-control   文件: JwtAuthenticatorTest.java
@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);
}
 
/**
 * 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;
}
 
@Override public RemoteUserExtractor getRemoteUserExtractor() {
  return new RemoteUserExtractor() {
    @Override public String extract(HttpServletRequest request)
        throws RemoteUserExtractionException {
      methodCallCounter3++;
      if (request instanceof Request) {
        Authentication authentication = ((Request) request).getAuthentication();
        if (authentication instanceof UserAuthentication) {
          UserIdentity userIdentity = ((UserAuthentication) authentication).getUserIdentity();
          return userIdentity.getUserPrincipal().getName();
        }
      }
      throw new RemoteUserExtractionException("Request doesn't contain user credentials.");
    }
  };
}
 
源代码5 项目: sql-layer   文件: SpnegoAuthenticatorEx.java
@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;
}
 
源代码6 项目: datacollector   文件: SSOUserAuthenticator.java
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));
  }
}
 
源代码7 项目: datacollector   文件: SSOAuthenticator.java
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);
}
 
源代码8 项目: datacollector   文件: AbstractSSOAuthenticator.java
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));
  }
}
 
@Test
public void testReturnForbidden() throws Exception {
  SSOService ssoService = Mockito.mock(SSOService.class);
  AbstractSSOAuthenticator authenticator = new ForTestSSOAuthenticator(ssoService);

  HttpServletRequest req = Mockito.mock(HttpServletRequest.class);
  Mockito.when(req.getRequestURL()).thenReturn(new StringBuffer("url"));
  Mockito.when(req.getRemoteAddr()).thenReturn("remoteAddress");
  Mockito.when(req.getMethod()).thenReturn("method");
  Mockito.when(req.getQueryString()).thenReturn("QS");

  HttpServletResponse res = Mockito.mock(HttpServletResponse.class);
  StringWriter writer = new StringWriter();
  PrintWriter printWriter = new PrintWriter(writer);
  Mockito.when(res.getWriter()).thenReturn(printWriter);

  Assert.assertEquals(Authentication.SEND_FAILURE, authenticator.returnUnauthorized(req, res, "principal", "template"));

  ArgumentCaptor<Integer> error = ArgumentCaptor.forClass(Integer.class);
  Mockito.verify(res).setStatus(error.capture());
  Assert.assertEquals(
      SSOUserAuthenticator.UNAUTHORIZED_JSON,
      new ObjectMapper().readValue(writer.toString().trim(), Map.class)
  );
  Mockito.verify(res).setContentType(Mockito.eq("application/json"));
}
 
源代码10 项目: datacollector   文件: TestSSOUserAuthenticator.java
@Test
public void testRedirectToSelf() throws Exception {
  SSOService ssoService = Mockito.mock(SSOService.class);
  SSOUserAuthenticator authenticator = new SSOUserAuthenticator(ssoService, conf);

  HttpServletRequest req = Mockito.mock(HttpServletRequest.class);
  Mockito.when(req.getRequestURL()).thenReturn(new StringBuffer("http://foo/bar"));
  Mockito.when(req.getQueryString()).thenReturn("a=A&b=B&" + SSOConstants.USER_AUTH_TOKEN_PARAM + "=token");

  HttpServletResponse res = Mockito.mock(HttpServletResponse.class);

  Assert.assertEquals(Authentication.SEND_CONTINUE, authenticator.redirectToSelf(req, res));
  ArgumentCaptor<String> redirect = ArgumentCaptor.forClass(String.class);
  Mockito.verify(res).sendRedirect(redirect.capture());
  Assert.assertEquals("http://foo/bar?a=A&b=B", redirect.getValue());
}
 
源代码11 项目: datacollector   文件: TestSSOUserAuthenticator.java
@Test
public void testreturnUnauthorized() throws Exception {
  SSOService ssoService = Mockito.mock(SSOService.class);
  ssoService.setConfiguration(new Configuration());
  SSOUserAuthenticator authenticator = Mockito.spy(new SSOUserAuthenticator(ssoService, conf));
  Mockito
      .doReturn("http://foo")
      .when(authenticator)
      .getLoginUrl(Mockito.any(HttpServletRequest.class), Mockito.anyBoolean());

  HttpServletRequest req = Mockito.mock(HttpServletRequest.class);
  Mockito.when(req.getServerPort()).thenReturn(1000);
  HttpServletResponse res = Mockito.mock(HttpServletResponse.class);
  Mockito.when(res.getWriter()).thenReturn(new PrintWriter(new StringWriter()));
  Assert.assertEquals(Authentication.SEND_FAILURE, authenticator.returnUnauthorized(req, res, "principal", "template"));
  Mockito.verify(authenticator).redirectToLogin(Mockito.eq(req), Mockito.eq(res));
  ArgumentCaptor<Cookie> cookieCaptor = ArgumentCaptor.forClass(Cookie.class);
  Mockito.verify(authenticator, Mockito.times(1)).createAuthCookie(Mockito.eq(req), Mockito.eq(""), Mockito.eq(0L));
  Mockito.verify(res, Mockito.times(1)).addCookie(cookieCaptor.capture());
  Assert.assertEquals(authenticator.getAuthCookieName(req), cookieCaptor.getValue().getName());
  Assert.assertEquals("", cookieCaptor.getValue().getValue());
  Assert.assertEquals("/", cookieCaptor.getValue().getPath());
  Assert.assertEquals(0, cookieCaptor.getValue().getMaxAge());
}
 
源代码12 项目: datacollector   文件: TestSSOUserAuthenticator.java
@Test
public void testreturnUnauthorizedREST() throws Exception {
  SSOService ssoService = Mockito.mock(SSOService.class);
  SSOUserAuthenticator authenticator = Mockito.spy(new SSOUserAuthenticator(ssoService, conf));
  Mockito
      .doReturn("http://foo")
      .when(authenticator)
      .getLoginUrl(Mockito.any(HttpServletRequest.class), Mockito.anyBoolean());

  HttpServletRequest req = Mockito.mock(HttpServletRequest.class);
  Mockito.when(req.getHeader(Mockito.eq(SSOConstants.X_REST_CALL))).thenReturn("foo");
  HttpServletResponse res = Mockito.mock(HttpServletResponse.class);
  Mockito.when(res.getWriter()).thenReturn(new PrintWriter(new StringWriter()));
  Assert.assertEquals(Authentication.SEND_FAILURE, authenticator.returnUnauthorized(req, res, "principal", "template"));
  Mockito.verify(res).setContentType(Mockito.eq("application/json"));
}
 
源代码13 项目: datacollector   文件: TestSSOUserAuthenticator.java
@Test
public void testValidateRequestMandatoryInvalidAuthToken() throws Exception {
  SSOService ssoService = Mockito.mock(SSOService.class);
  SSOUserAuthenticator authenticator = Mockito.spy(new SSOUserAuthenticator(ssoService, conf));
  HttpServletRequest req = Mockito.mock(HttpServletRequest.class);
  HttpServletResponse res = Mockito.mock(HttpServletResponse.class);
  Mockito.doReturn("token").when(authenticator).getAuthTokenFromRequest(Mockito.eq(req));

  Mockito.doReturn(Authentication.SEND_FAILURE).when(authenticator).returnUnauthorized(Mockito.eq(req), Mockito.eq
      (res), Mockito.anyString(), Mockito.anyString());

  Assert.assertEquals(Authentication.SEND_FAILURE, authenticator.validateRequest(req, res, true));
  Mockito
      .verify(authenticator)
      .returnUnauthorized(Mockito.eq(req), Mockito.eq(res), Mockito.anyString(), Mockito.anyString());
  Mockito.verify(ssoService).validateUserToken(Mockito.eq("token"));
  Mockito.verifyNoMoreInteractions(ssoService);
}
 
源代码14 项目: datacollector   文件: TestSSOAppAuthenticator.java
@Test
public void testValidateRequestMandatoryNoRESTCall() throws Exception {
  SSOService ssoService = Mockito.mock(SSOService.class);
  SSOAppAuthenticator authenticator = Mockito.spy(new SSOAppAuthenticator(ssoService));
  HttpServletRequest req = Mockito.mock(HttpServletRequest.class);
  HttpServletResponse res = Mockito.mock(HttpServletResponse.class);
  Mockito.when(req.getHeader(Mockito.eq(SSOConstants.X_APP_COMPONENT_ID))).thenReturn("componentId");
  Mockito.when(req.getHeader(Mockito.eq(SSOConstants.X_REST_CALL))).thenReturn(null);
  Mockito
      .doReturn(Authentication.SEND_FAILURE)
      .when(authenticator)
      .returnUnauthorized(Mockito.eq(req), Mockito.eq(res), Mockito.eq("componentId"), Mockito.anyString());
  Assert.assertEquals(Authentication.SEND_FAILURE, authenticator.validateRequest(req, res, true));
  Mockito
      .verify(authenticator)
      .returnUnauthorized(Mockito.eq(req), Mockito.eq(res), Mockito.eq("componentId"), Mockito.anyString());
}
 
源代码15 项目: datacollector   文件: TestSSOAppAuthenticator.java
@Test
public void testValidateRequestMandatoryNoAuthToken() throws Exception {
  SSOService ssoService = Mockito.mock(SSOService.class);
  SSOAppAuthenticator authenticator = Mockito.spy(new SSOAppAuthenticator(ssoService));
  HttpServletRequest req = Mockito.mock(HttpServletRequest.class);
  HttpServletResponse res = Mockito.mock(HttpServletResponse.class);
  Mockito.when(req.getHeader(Mockito.eq(SSOConstants.X_APP_COMPONENT_ID))).thenReturn("componentId");
  Mockito.when(req.getHeader(Mockito.eq(SSOConstants.X_REST_CALL))).thenReturn("foo");
  Mockito
      .doReturn(Authentication.SEND_FAILURE)
      .when(authenticator)
      .returnUnauthorized(Mockito.eq(req), Mockito.eq(res), Mockito.eq("componentId"), Mockito.anyString());
  Assert.assertEquals(Authentication.SEND_FAILURE, authenticator.validateRequest(req, res, true));
  Mockito
      .verify(authenticator)
      .returnUnauthorized(Mockito.eq(req), Mockito.eq(res), Mockito.eq("componentId"), Mockito.anyString());
}
 
源代码16 项目: datacollector   文件: TestSSOAppAuthenticator.java
@Test
public void testValidateRequestMandatoryNoComponentIdToken() throws Exception {
  SSOService ssoService = Mockito.mock(SSOService.class);
  SSOAppAuthenticator authenticator = Mockito.spy(new SSOAppAuthenticator(ssoService));
  HttpServletRequest req = Mockito.mock(HttpServletRequest.class);
  HttpServletResponse res = Mockito.mock(HttpServletResponse.class);
  Mockito.when(req.getHeader(Mockito.eq(SSOConstants.X_APP_AUTH_TOKEN))).thenReturn("token");
  Mockito.when(req.getHeader(Mockito.eq(SSOConstants.X_REST_CALL))).thenReturn("foo");
  Mockito
      .doReturn(Authentication.SEND_FAILURE)
      .when(authenticator)
      .returnUnauthorized(Mockito.eq(req), Mockito.eq(res), Mockito.anyString(), Mockito.anyString());
  Assert.assertEquals(Authentication.SEND_FAILURE, authenticator.validateRequest(req, res, true));
  Mockito
      .verify(authenticator)
      .returnUnauthorized(Mockito.eq(req), Mockito.eq(res), Mockito.anyString(), Mockito.anyString());
}
 
源代码17 项目: datacollector   文件: TestSSOAppAuthenticator.java
@Test
public void testValidateRequestMandatoryInvalidToken() throws Exception {
  SSOService ssoService = Mockito.mock(SSOService.class);
  SSOAppAuthenticator authenticator = Mockito.spy(new SSOAppAuthenticator(ssoService));
  HttpServletRequest req = Mockito.mock(HttpServletRequest.class);
  HttpServletResponse res = Mockito.mock(HttpServletResponse.class);
  Mockito.when(req.getHeader(Mockito.eq(SSOConstants.X_APP_AUTH_TOKEN))).thenReturn("token");
  Mockito.when(req.getHeader(Mockito.eq(SSOConstants.X_APP_COMPONENT_ID))).thenReturn("componentId");
  Mockito.when(req.getHeader(Mockito.eq(SSOConstants.X_REST_CALL))).thenReturn("foo");
  Mockito.when(ssoService.validateAppToken(Mockito.eq("token"), Mockito.eq("componentId"))).thenReturn(null);
  Mockito
      .doReturn(Authentication.SEND_FAILURE)
      .when(authenticator)
      .returnUnauthorized(Mockito.eq(req), Mockito.eq(res), Mockito.anyString(), Mockito.anyString());
  Assert.assertEquals(Authentication.SEND_FAILURE, authenticator.validateRequest(req, res, true));
  Mockito
      .verify(authenticator)
      .returnUnauthorized(Mockito.eq(req), Mockito.eq(res), Mockito.anyString(), Mockito.anyString());
  Mockito.verify(ssoService, Mockito.times(1)).validateAppToken(Mockito.eq("token"), Mockito.eq("componentId"));
}
 
源代码18 项目: datacollector   文件: TestSSOAppAuthenticator.java
@Test
public void testValidateRequestMandatoryValidToken() throws Exception {
  SSOService ssoService = Mockito.mock(SSOService.class);
  SSOAppAuthenticator authenticator = Mockito.spy(new SSOAppAuthenticator(ssoService));
  HttpServletRequest req = Mockito.mock(HttpServletRequest.class);
  HttpServletResponse res = Mockito.mock(HttpServletResponse.class);
  Mockito.when(req.getHeader(Mockito.eq(SSOConstants.X_APP_AUTH_TOKEN))).thenReturn("token");
  Mockito.when(req.getHeader(Mockito.eq(SSOConstants.X_APP_COMPONENT_ID))).thenReturn("componentId");
  Mockito.when(req.getHeader(Mockito.eq(SSOConstants.X_REST_CALL))).thenReturn("foo");
  Mockito.when(ssoService.validateAppToken(Mockito.eq("token"), Mockito.eq("componentId"))).thenReturn(null);
  SSOPrincipal principal = Mockito.mock(SSOPrincipal.class);
  Mockito.when(principal.getTokenStr()).thenReturn("token");
  Mockito.when(principal.getExpires()).thenReturn(1L);
  Mockito.doReturn(principal).when(ssoService).validateAppToken(Mockito.eq("token"), Mockito.eq("componentId"));

  Authentication auth = authenticator.validateRequest(req, res, true);
  Assert.assertNotNull(auth);
  Assert.assertSame(principal, ((SSOAuthenticationUser)auth).getSSOUserPrincipal());
}
 
源代码19 项目: datacollector   文件: ActivationAuthenticator.java
@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;
}
 
@Test
public void testCleanDelegationMethods() throws Exception {
  Authenticator auth = Mockito.mock(Authenticator.class);
  Activation activation = Mockito.mock(Activation.class);
  ActivationAuthenticator activationAuth = new ActivationAuthenticator(auth, activation);

  Authenticator.AuthConfiguration conf = Mockito.mock(Authenticator.AuthConfiguration.class);
  activationAuth.setConfiguration(conf);
  Mockito.verify(auth, Mockito.times(1)).setConfiguration(Mockito.eq(conf));

  Mockito.when(auth.getAuthMethod()).thenReturn("foo");
  Assert.assertEquals("foo", activationAuth.getAuthMethod());

  ServletRequest req = Mockito.mock(ServletRequest.class);
  activationAuth.prepareRequest(req);
  Mockito.verify(auth, Mockito.times(1)).prepareRequest(Mockito.eq(req));

  ServletResponse res = Mockito.mock(ServletResponse.class);
  Authentication.User user = Mockito.mock(Authentication.User.class);
  Mockito.when(auth.secureResponse(Mockito.eq(req), Mockito.eq(res), Mockito.eq(true), Mockito.eq(user)))
         .thenReturn(true);
  Assert.assertTrue(auth.secureResponse(req, res, true, user));
}
 
源代码21 项目: cxf-fediz   文件: FederationAuthenticator.java
private Authentication handleSignOutCleanup(HttpServletResponse response, HttpSession session) throws IOException {
    if (LOG.isDebugEnabled()) {
        LOG.debug("SignOutCleanup request found");
        LOG.debug("SignOutCleanup action...");
    }
    session.invalidate();

    final ServletOutputStream responseOutputStream = response.getOutputStream();
    InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("logout.jpg");
    if (inputStream == null) {
        LOG.warn("Could not write logout.jpg");
        return Authentication.SEND_FAILURE;
    }
    int read = 0;
    byte[] buf = new byte[1024];
    while ((read = inputStream.read(buf)) != -1) {
        responseOutputStream.write(buf, 0, read);
    }
    inputStream.close();
    responseOutputStream.flush();
    return Authentication.SEND_SUCCESS;
}
 
源代码22 项目: nifi   文件: TestInvokeHttpCommon.java
@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();
    }
}
 
源代码23 项目: Bats   文件: DrillSpnegoAuthenticator.java
/**
 * 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);
}
 
源代码24 项目: Bats   文件: DrillSpnegoAuthenticator.java
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;
}
 
@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;
	}
}
 
private Authentication createAuthentication(TokenAuthenticationResult tokenAuthentication) {
	Principal principal = tokenAuthentication.getPrincipal();
	Set<Principal> principals = new HashSet<>();
	principals.add(principal);
	Subject subject = new Subject(true, principals, new HashSet<>(), new HashSet<>());
	String[] scopes = tokenAuthentication.getScopes().toArray(new String[0]);
	return new UserAuthentication(getAuthMethod(), new DefaultUserIdentity(subject, principal, scopes));
}
 
@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;
	}
}
 
private Authentication createAuthentication(TokenAuthenticationResult tokenAuthentication) {
	Principal principal = tokenAuthentication.getPrincipal();
	Set<Principal> principals = new HashSet<>();
	principals.add(principal);
	Subject subject = new Subject(true, principals, new HashSet<>(), new HashSet<>());
	String[] scopes = tokenAuthentication.getScopes().toArray(new String[0]);
	return new UserAuthentication(getAuthMethod(), new DefaultUserIdentity(subject, principal, scopes));
}
 
源代码29 项目: keycloak   文件: KeycloakSamlAuthenticator.java
@Override
public Authentication createAuthentication(UserIdentity userIdentity, Request request) {
    return new KeycloakAuthentication(getAuthMethod(), userIdentity) {
        @Override
        public void logout() {
            logoutCurrent(HttpChannel.getCurrentHttpChannel().getRequest());
        }
    };
}
 
源代码30 项目: keycloak   文件: KeycloakSamlAuthenticator.java
@Override
public Authentication createAuthentication(UserIdentity userIdentity, final Request request) {
    return new KeycloakAuthentication(getAuthMethod(), userIdentity) {
        @Override
        public void logout() {
            logoutCurrent(request);
        }
    };
}
 
 类所在包
 同包方法