org.springframework.security.web.authentication.session.SessionAuthenticationException Java Examples

The following examples show how to use org.springframework.security.web.authentication.session.SessionAuthenticationException. 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: AuthenticationTest.java    From mojito with Apache License 2.0 6 votes vote down vote up
@Test(expected = SessionAuthenticationException.class)
public void testUnsuccessfulAuthWithIncorrectUser() throws IOException {
    formLoginAuthenticationCsrfTokenInterceptor.setCredentialProvider(new CredentialProvider() {
        @Override
        public String getUsername() {
            return "badUser";
        }

        @Override
        public String getPassword() {
            return credentialProvider.getPassword();
        }
    });

    String result = authenticatedRestTemplate.getForObject("", String.class);
}
 
Example #2
Source File: AuthenticationTest.java    From mojito with Apache License 2.0 6 votes vote down vote up
@Test(expected = SessionAuthenticationException.class)
public void testUnsuccessfulAuthWithIncorrectPassword() throws IOException {
    formLoginAuthenticationCsrfTokenInterceptor.setCredentialProvider(new CredentialProvider() {
        @Override
        public String getUsername() {
            return credentialProvider.getUsername();
        }

        @Override
        public String getPassword() {
            return "bad password";
        }
    });

    String result = authenticatedRestTemplate.getForObject("", String.class);
}
 
Example #3
Source File: MolgenisLoginController.java    From molgenis with GNU Lesser General Public License v3.0 6 votes vote down vote up
@GetMapping(params = "error")
public String getLoginErrorPage(Model model, HttpServletRequest request) {
  String errorMessage;
  Object attribute = request.getSession().getAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);
  if (attribute != null) {
    if (attribute instanceof BadCredentialsException) {
      errorMessage = ERROR_MESSAGE_BAD_CREDENTIALS;
    } else if (attribute instanceof SessionAuthenticationException) {
      errorMessage = ERROR_MESSAGE_SESSION_AUTHENTICATION;
    } else {
      if (!determineErrorMessagesFromInternalAuthenticationExceptions(attribute).isEmpty()) {
        errorMessage = determineErrorMessagesFromInternalAuthenticationExceptions(attribute);
      } else {
        errorMessage = ERROR_MESSAGE_UNKNOWN;
      }
    }
  } else {
    errorMessage = ERROR_MESSAGE_UNKNOWN;
  }

  model.addAttribute(ERROR_MESSAGE_ATTRIBUTE, errorMessage);
  return VIEW_LOGIN;
}
 
Example #4
Source File: FirebaseAuthenticationProvider.java    From spring-security-firebase with MIT License 5 votes vote down vote up
@Override
protected UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication)
		throws AuthenticationException {
	final FirebaseAuthenticationToken authenticationToken = (FirebaseAuthenticationToken) authentication;

	ApiFuture<FirebaseToken> task = firebaseAuth.verifyIdTokenAsync(authenticationToken.getToken());
	try {
		FirebaseToken token = task.get();
		return new FirebaseUserDetails(token.getEmail(), token.getUid());
	} catch (InterruptedException | ExecutionException e) {
		throw new SessionAuthenticationException(e.getMessage());
	}
}
 
Example #5
Source File: FormLoginAuthenticationCsrfTokenInterceptor.java    From mojito with Apache License 2.0 5 votes vote down vote up
/**
 * @param request the request, containing method, URI, and headers
 * @param csrfToken the CSRF token to be injected into the request header
 */
protected void injectCsrfTokenIntoHeader(HttpRequest request, CsrfToken csrfToken) {
    if (csrfToken == null) {
        throw new SessionAuthenticationException("There is no CSRF token to inject");
    }

    logger.debug("Injecting CSRF token into request {} header: {}", request.getURI(), csrfToken.getToken());
    request.getHeaders().add(csrfToken.getHeaderName(), csrfToken.getToken());
}
 
Example #6
Source File: FormLoginAuthenticationCsrfTokenInterceptor.java    From mojito with Apache License 2.0 5 votes vote down vote up
/**
 * Starts the traditioanl form login authentication flow handshake.
 * Consequencially, the cookie store (which contains the session id) and the
 * CSRF token will be updated.
 *
 * @throws AuthenticationException
 */
protected synchronized void startAuthenticationFlow() throws AuthenticationException {
    logger.debug("Getting authenticated session");

    logger.debug("Start by loading up the login form to get a valid unauthenticated session and CSRF token");
    ResponseEntity<String> loginResponseEntity = restTemplateForAuthenticationFlow.getForEntity(authRestTemplate.getURIForResource(formLoginConfig.getLoginFormPath()), String.class);

    latestCsrfToken = getCsrfTokenFromLoginHtml(loginResponseEntity.getBody());
    latestSessionIdForLatestCsrfToken = getAuthenticationSessionIdFromCookieStore();
    logger.debug("Update CSRF token for interceptor ({}) from login form", latestCsrfToken.getToken());

    MultiValueMap<String, Object> loginPostParams = new LinkedMultiValueMap<>();
    loginPostParams.add("username", credentialProvider.getUsername());
    loginPostParams.add("password", credentialProvider.getPassword());

    logger.debug("Post to login url to startAuthenticationFlow with user={}, pwd={}", credentialProvider.getUsername(), credentialProvider.getPassword());
    ResponseEntity<String> postLoginResponseEntity = restTemplateForAuthenticationFlow.postForEntity(authRestTemplate.getURIForResource(formLoginConfig.getLoginFormPath()), loginPostParams, String.class);

    //TODO(P1) This current way of checking if authentication is successful is somewhat
    // hacky. Bascailly it says that authentication is successful if a 302 is returned
    // and the redirect (from location header) maps to the login redirect path from the config. 
    URI locationURI = URI.create(postLoginResponseEntity.getHeaders().get("Location").get(0));
    String expectedLocation = resttemplateConfig.getContextPath() + "/" + formLoginConfig.getLoginRedirectPath();
    
    if (postLoginResponseEntity.getStatusCode().equals(HttpStatus.FOUND)
            && expectedLocation.equals(locationURI.getPath())) {

        latestCsrfToken = getCsrfTokenFromEndpoint(authRestTemplate.getURIForResource(formLoginConfig.getCsrfTokenPath()));
        latestSessionIdForLatestCsrfToken = getAuthenticationSessionIdFromCookieStore();

        logger.debug("Update CSRF token interceptor in AuthRestTempplate ({})", latestCsrfToken.getToken());

    } else {
        throw new SessionAuthenticationException("Authentication failed.  Post login status code = " + postLoginResponseEntity.getStatusCode()
                + ", location = [" + locationURI.getPath() + "], expected location = [" + expectedLocation + "]");
    }
}
 
Example #7
Source File: FormLoginAuthenticationCsrfTokenInterceptor.java    From mojito with Apache License 2.0 5 votes vote down vote up
/**
 * Gets the CSRF token from login html because the CSRF token endpoint needs
 * to be authenticated first.
 *
 * @param loginHtml The login page HTML which contains the csrf token. It is
 * assumed that the CSRF token is embedded on the page inside an input field
 * with name matching
 * {@link com.box.l10n.mojito.rest.resttemplate.FormLoginAuthenticationCsrfTokenInterceptor#CSRF_PARAM_NAME}
 * @return
 * @throws AuthenticationException
 */
protected CsrfToken getCsrfTokenFromLoginHtml(String loginHtml) throws AuthenticationException {
    Pattern pattern = Pattern.compile("CSRF_TOKEN = '(.*?)';");
    Matcher matcher = pattern.matcher(loginHtml);

    if (matcher.find()) {
        String csrfTokenString = matcher.group(1);

        logger.debug("CSRF token from login html: {}", csrfTokenString);
        return new DefaultCsrfToken(CSRF_HEADER_NAME,
                CSRF_PARAM_NAME, csrfTokenString);
    } else {
        throw new SessionAuthenticationException("Could not find CSRF_TOKEN variable on login page");
    }
}
 
Example #8
Source File: AuthenticationAuthoritiesUpdaterImplTest.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
void testUpdateAuthenticationUnknownToken() {
  Exception exception =
      assertThrows(
          SessionAuthenticationException.class,
          () ->
              authenticationAuthoritiesUpdaterImpl.updateAuthentication(
                  mock(Authentication.class), updatedAuthorities));
  assertThat(exception.getMessage()).containsPattern("Unknown authentication type '.*?'");
}