Java Code Examples for org.springframework.security.authentication.AuthenticationCredentialsNotFoundException

The following examples show how to use org.springframework.security.authentication.AuthenticationCredentialsNotFoundException. These examples are extracted from open source projects. 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 Project: api-layer   Source File: RestResponseHandler.java    License: Eclipse Public License 2.0 7 votes vote down vote up
private void handleHttpClientError(@NotNull Exception exception, ErrorType errorType, String genericLogErrorMessage, Object... logParameters) {
    HttpClientErrorException hceException = (HttpClientErrorException) exception;
    switch (hceException.getStatusCode()) {
        case UNAUTHORIZED:
            if (errorType != null) {
                if (errorType.equals(ErrorType.BAD_CREDENTIALS)) {
                    throw new BadCredentialsException(errorType.getDefaultMessage(), exception);
                } else if (errorType.equals(ErrorType.TOKEN_NOT_VALID)) {
                    throw new TokenNotValidException(errorType.getDefaultMessage(), exception);
                } else if (errorType.equals(ErrorType.TOKEN_NOT_PROVIDED)) {
                    throw new TokenNotProvidedException(errorType.getDefaultMessage());
                }
            }
            throw new BadCredentialsException(ErrorType.BAD_CREDENTIALS.getDefaultMessage(), exception);
        case BAD_REQUEST:
            throw new AuthenticationCredentialsNotFoundException(ErrorType.AUTH_CREDENTIALS_NOT_FOUND.getDefaultMessage(), exception);
        case METHOD_NOT_ALLOWED:
            throw new AuthMethodNotSupportedException(ErrorType.AUTH_METHOD_NOT_SUPPORTED.getDefaultMessage());
        default:
            addDebugMessage(exception, genericLogErrorMessage, logParameters);
            throw new AuthenticationServiceException(ErrorType.AUTH_GENERAL.getDefaultMessage(), exception);
    }
}
 
Example 2
Source Project: cloud-service   Source File: UserDetailServiceImpl.java    License: MIT License 6 votes vote down vote up
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    // 为了支持多类型登录,这里username后面拼装上登录类型,如username|type
    String[] params = username.split("\\|");
    username = params[0];// 真正的用户名

    LoginAppUser loginAppUser = userClient.findByUsername(username);
    if (loginAppUser == null) {
        throw new AuthenticationCredentialsNotFoundException("用户不存在");
    } else if (!loginAppUser.isEnabled()) {
        throw new DisabledException("用户已作废");
    }

    if (params.length > 1) {
        // 登录类型
        CredentialType credentialType = CredentialType.valueOf(params[1]);
        if (CredentialType.PHONE == credentialType) {// 短信登录
            handlerPhoneSmsLogin(loginAppUser, params);
        } else if (CredentialType.WECHAT_OPENID == credentialType) {// 微信登陆
            handlerWechatLogin(loginAppUser, params);
        }
    }

    return loginAppUser;
}
 
Example 3
Source Project: blog-sample   Source File: JwtAuthenticationFilter.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
    if (isProtectedUrl(request)) {
        UsernamePasswordAuthenticationToken authentication = getAuthentication(request);

        // 如果验证失败,设置异常;否则将UsernamePasswordAuthenticationToken注入到框架中
        if (authentication == null) {
            //手动设置异常
            request.getSession().setAttribute("SPRING_SECURITY_LAST_EXCEPTION", new AuthenticationCredentialsNotFoundException("权限认证失败"));
            // 转发到错误Url
            request.getRequestDispatcher("/login/error").forward(request, response);
        } else {
            SecurityContextHolder.getContext().setAuthentication(authentication);
            filterChain.doFilter(request, response);
        }
    }
}
 
Example 4
Source Project: api-layer   Source File: AuthExceptionHandler.java    License: Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Entry method that takes care about the exception passed to it
 *
 * @param request  Http request
 * @param response Http response
 * @param ex       Exception to be handled
 * @throws ServletException Fallback exception if exception cannot be handled
 */
@Override
public void handleException(HttpServletRequest request, HttpServletResponse response, RuntimeException ex) throws ServletException {
    if (ex instanceof InsufficientAuthenticationException) {
        handleAuthenticationRequired(request, response, ex);
    } else if (ex instanceof BadCredentialsException) {
        handleBadCredentials(request, response, ex);
    } else if (ex instanceof AuthenticationCredentialsNotFoundException) {
        handleAuthenticationCredentialsNotFound(request, response, ex);
    } else if (ex instanceof AuthMethodNotSupportedException) {
        handleAuthMethodNotSupported(request, response, ex);
    } else if (ex instanceof TokenNotValidException) {
        handleTokenNotValid(request, response, ex);
    } else if (ex instanceof TokenNotProvidedException) {
        handleTokenNotProvided(request, response, ex);
    } else if (ex instanceof TokenExpireException) {
        handleTokenExpire(request, response, ex);
    } else if (ex instanceof InvalidCertificateException) {
        handleInvalidCertificate(response, ex);
    } else if (ex instanceof AuthenticationException) {
        handleAuthenticationException(request, response, ex);
    } else {
        throw new ServletException(ex);
    }
}
 
Example 5
Source Project: api-layer   Source File: LoginFilter.java    License: Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Calls authentication manager to validate the username and password
 *
 * @param request  the http request
 * @param response the http response
 * @return the authenticated token
 * @throws AuthMethodNotSupportedException            when the authentication method is not supported
 * @throws AuthenticationCredentialsNotFoundException when username or password are not provided
 */
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws ServletException {
    if (!request.getMethod().equals(HttpMethod.POST.name())) {
        throw new AuthMethodNotSupportedException(request.getMethod());
    }

    Optional<LoginRequest> optionalLoginRequest = getCredentialFromAuthorizationHeader(request);
    LoginRequest loginRequest = optionalLoginRequest.orElseGet(() -> getCredentialsFromBody(request));
    if (StringUtils.isBlank(loginRequest.getUsername()) || StringUtils.isBlank(loginRequest.getPassword())) {
        throw new AuthenticationCredentialsNotFoundException("Username or password not provided.");
    }

    UsernamePasswordAuthenticationToken authentication
        = new UsernamePasswordAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword());
    Authentication auth = null;
    try {
        auth = this.getAuthenticationManager().authenticate(authentication);
    } catch (RuntimeException ex) {
        resourceAccessExceptionHandler.handleException(request, response, ex);
    }
    return auth;
}
 
Example 6
Source Project: paas   Source File: JwtAuthenticationFilter.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
    if (!disProtectedUrl(request)) {
        Object obj = getAuthentication(request);

        if(obj instanceof ResultVO) {
            //如果属于ResultVO,表示有错误
            request.setAttribute("ERR_MSG", obj);
            // 转发到错误Url
            request.getRequestDispatcher("/auth/error").forward(request, response);
        } else if(obj instanceof UsernamePasswordAuthenticationToken) {
            SecurityContextHolder.getContext().setAuthentication((UsernamePasswordAuthenticationToken)obj);
            filterChain.doFilter(request, response);
        } else {
            // 如果验证失败,设置异常;否则将UsernamePasswordAuthenticationToken注入到框架中
            request.getSession().setAttribute("SPRING_SECURITY_LAST_EXCEPTION", new AuthenticationCredentialsNotFoundException("权限认证失败"));
            // 转发到错误Url
            request.getRequestDispatcher("/auth/error").forward(request, response);
        }
    } else {
        filterChain.doFilter(request, response);
    }
}
 
Example 7
Source Project: joal   Source File: WebSocketAuthenticatorService.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("TypeMayBeWeakened")
public UsernamePasswordAuthenticationToken getAuthenticatedOrFail(final CharSequence username, final CharSequence authToken) throws AuthenticationException {
    if (StringUtils.isBlank(username)) {
        throw new AuthenticationCredentialsNotFoundException("Username was null or empty.");
    }
    if (StringUtils.isBlank(authToken)) {
        throw new AuthenticationCredentialsNotFoundException("Authentication token was null or empty.");
    }
    if (!appSecretToken.contentEquals(authToken)) {
        throw new BadCredentialsException("Authentication token does not match the expected token");
    }

    // Everything is fine, return an authenticated Authentication. (the constructor with grantedAuthorities auto set authenticated = true)
    // null credentials, we do not pass the password along to prevent security flaw
    return new UsernamePasswordAuthenticationToken(
            username,
            null,
            Collections.singleton((GrantedAuthority) () -> "USER")
    );
}
 
Example 8
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    Assert.notNull(authentication, "No authentication data provided");

    String key = (String) authentication.getPrincipal();
    String secret = (String) authentication.getCredentials();
    
    Org org;
    try {
      org = orgService.findByApiKeyAndApiSecret(key, secret);
    } 
    catch (OrgNotFoundException e) {
      throw new AuthenticationCredentialsNotFoundException(e.getMessage());
    }
    List<GrantedAuthority> authorities = Collections.singletonList(new SimpleGrantedAuthority("ROLE_ORG_ADMIN"));        
    UserContext userContext = UserContext.create(org.getMetadata().get(Vocabulary.TENANT), org.getSourcedId(), authorities);
    return new UsernamePasswordAuthenticationToken(userContext, null, userContext.getAuthorities());
}
 
Example 9
/**
 * This method is used to validate all subsequent request token
 *
 */
@Override
public Authentication authenticate(Authentication authentication) throws InsightsAuthenticationException {
	LOG.debug("Inside InsightsAuthenticationProviderImpl === ");
		if (!supports(authentication.getClass())) {
            throw new IllegalArgumentException("Only SAMLAuthenticationToken is supported, " + authentication.getClass() + " was attempted");
        }
		
        if (authentication.getPrincipal() == null) {
		LOG.debug("Authentication token is missing - authentication.getPrincipal() {} ",
				authentication.getPrincipal());
            throw new AuthenticationCredentialsNotFoundException("Authentication token is missing");
        }
	/*validate request token*/
	validateIncomingToken(authentication.getPrincipal());
       return authentication;
   }
 
Example 10
Source Project: secrets-proxy   Source File: JwtTokenService.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Retrieves the JWT authentication token from http request.
 *
 * @param req http request.
 * @return {@link JwtAuthToken} or <code>null</code> if the Bearer token is not present or empty.
 */
public @Nullable JwtAuthToken getAccessToken(@Nonnull HttpServletRequest req) {
  log.debug("Getting the access token for " + req.getRequestURI());

  String bearerToken = req.getHeader(tokenHeader);
  if (bearerToken != null) {
    // Make sure it's valid token type.
    if (!bearerToken.startsWith(tokenType)) {
      throw new AuthenticationCredentialsNotFoundException("Invalid Authorization Token.");
    }

    String jwtToken = bearerToken.replaceFirst(tokenType, "").trim();
    if (!isEmpty(jwtToken)) {
      return new JwtAuthToken("JwtToken", jwtToken, Collections.emptyList());
    }
  }

  log.debug("JWT Bearer token is null/empty for " + req.getRequestURI());
  return null;
}
 
Example 11
@Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
	return exchange.getPrincipal()
		.filter(p -> p instanceof Authentication)
		.flatMap( p-> Mono.just((Authentication) p))
		.filter(authentication -> {
			return authentication != null && authentication.isAuthenticated();
		})
		.flatMap(authentication -> {
			return source.getConfigAttributes(exchange).as( (Function<? super Flux<ConfigAttribute>, Mono<Boolean>>) a -> {
				return accessDecisionManager.decide(authentication, exchange, a);
			});
		})
		.filter(t -> t)
		.switchIfEmpty(Mono.defer(() -> {
			return entryPoint.commence(exchange, new AuthenticationCredentialsNotFoundException("Not Found"));
		}))
		.flatMap(sc -> {
			return chain.filter(exchange);
		});
}
 
Example 12
Source Project: syncope   Source File: AuthDataAccessor.java    License: Apache License 2.0 6 votes vote down vote up
public JWTSSOProvider getJWTSSOProvider(final String issuer) {
    synchronized (this) {
        if (jwtSSOProviders == null) {
            jwtSSOProviders = new HashMap<>();

            implementationLookup.getJWTSSOProviderClasses().stream().
                    map(clazz -> (JWTSSOProvider) ApplicationContextProvider.getBeanFactory().
                    createBean(clazz, AbstractBeanDefinition.AUTOWIRE_BY_TYPE, true)).
                    forEach(jwtSSOProvider -> jwtSSOProviders.put(jwtSSOProvider.getIssuer(), jwtSSOProvider));
        }
    }

    if (issuer == null) {
        throw new AuthenticationCredentialsNotFoundException("A null issuer is not permitted");
    }
    JWTSSOProvider provider = jwtSSOProviders.get(issuer);
    if (provider == null) {
        throw new AuthenticationCredentialsNotFoundException(
                "Could not find any registered JWTSSOProvider for issuer " + issuer);
    }

    return provider;
}
 
Example 13
@Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

//      后续考虑集成spring socail,支持多种类型登录
        LoginAppUser loginAppUser = userClient.findByUsername(username);   			  //方式1  feign调用       对外feign resttemplate
        
//        LoginAppUser loginAppUser = userLoginGrpc.findByUsername(username);		  //方式2  gprc调用		对内grpc dubbo
        if (loginAppUser == null) {
            throw new AuthenticationCredentialsNotFoundException("用户不存在");
        } else if (!loginAppUser.isEnabled()) {
            throw new DisabledException("用户已作废");
        }

        return loginAppUser;
    }
 
Example 14
@Override
public Response toResponse(AuthenticationCredentialsNotFoundException exception) {
    // log the error
    logger.info(String.format("No valid credentials were found in the request: %s. Returning %s response.", exception, Response.Status.FORBIDDEN));

    if (logger.isDebugEnabled()) {
        logger.debug(StringUtils.EMPTY, exception);
    }

    return Response.status(Response.Status.FORBIDDEN).entity("Access is denied.").type("text/plain").build();
}
 
Example 15
Source Project: api-layer   Source File: LoginFilter.java    License: Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Get credentials from the request body
 *
 * @param request the http request
 * @return the credentials in {@link LoginRequest}
 * @throws AuthenticationCredentialsNotFoundException if the login object has wrong format
 */
private LoginRequest getCredentialsFromBody(HttpServletRequest request) {
    try {
        return mapper.readValue(request.getInputStream(), LoginRequest.class);
    } catch (IOException e) {
        logger.debug("Authentication problem: login object has wrong format");
        throw new AuthenticationCredentialsNotFoundException("Login object has wrong format.");
    }
}
 
Example 16
@Test
public void testAuthenticationFailure_whenExceptionIsAuthenticationCredentialsNotFoundException() throws IOException, ServletException {
    authExceptionHandler.handleException(
        httpServletRequest,
        httpServletResponse,
        new AuthenticationCredentialsNotFoundException("ERROR"));

    assertEquals(HttpStatus.BAD_REQUEST.value(), httpServletResponse.getStatus());
    assertEquals(MediaType.APPLICATION_JSON_UTF8_VALUE, httpServletResponse.getContentType());

    Message message = messageService.createMessage(ErrorType.AUTH_CREDENTIALS_NOT_FOUND.getErrorMessageKey(), httpServletRequest.getRequestURI());
    verify(objectMapper).writeValue(httpServletResponse.getWriter(), message.mapToView());
}
 
Example 17
Source Project: api-layer   Source File: LoginFilterTest.java    License: Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void shouldFailWithJsonEmptyCredentials() throws ServletException {
    httpServletRequest = new MockHttpServletRequest();
    httpServletRequest.setMethod(HttpMethod.POST.name());
    httpServletRequest.setContent(EMPTY_JSON.getBytes());
    httpServletResponse = new MockHttpServletResponse();

    exception.expect(AuthenticationCredentialsNotFoundException.class);
    exception.expectMessage("Username or password not provided.");

    loginFilter.attemptAuthentication(httpServletRequest, httpServletResponse);
}
 
Example 18
Source Project: api-layer   Source File: LoginFilterTest.java    License: Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void shouldFailWithoutAuth() throws ServletException {
    httpServletRequest = new MockHttpServletRequest();
    httpServletRequest.setMethod(HttpMethod.POST.name());
    httpServletResponse = new MockHttpServletResponse();

    exception.expect(AuthenticationCredentialsNotFoundException.class);
    exception.expectMessage("Login object has wrong format.");

    loginFilter.attemptAuthentication(httpServletRequest, httpServletResponse);
}
 
Example 19
Source Project: api-layer   Source File: LoginFilterTest.java    License: Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void shouldFailWithIncorrectCredentialsFormat() throws ServletException {
    httpServletRequest = new MockHttpServletRequest();
    httpServletRequest.setMethod(HttpMethod.POST.name());
    httpServletRequest.addHeader(HttpHeaders.AUTHORIZATION, INVALID_AUTH_HEADER);
    httpServletResponse = new MockHttpServletResponse();

    exception.expect(AuthenticationCredentialsNotFoundException.class);
    exception.expectMessage("Login object has wrong format.");

    loginFilter.attemptAuthentication(httpServletRequest, httpServletResponse);
}
 
Example 20
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    if (deployment == null) {
        deployment = resolver.resolve(null);
    }
    UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) authentication;
    if (token.getCredentials() == null) {
        throw new AuthenticationCredentialsNotFoundException("");
    }
    try {
        return directGrantAuth(token.getName(), token.getCredentials().toString());
    } catch (VerificationException|IOException e) {
        throw new KeycloakAuthenticationException(e.getMessage(), e);
    }
}
 
Example 21
Source Project: spring-boot-start-current   Source File: ContextUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 得到凭证
 */
private static Authentication getAuthentication () {
	final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
	if ( Objects.isNull( authentication ) ) {
		throw new AuthenticationCredentialsNotFoundException( "未授权" );
	}
	return authentication;
}
 
Example 22
/**
 * 刷新并认证token
 *
 * @return token
 */
@PutMapping
public ResponseEntity refreshAndGetAuthenticationToken ( @RequestHeader( "${jwt.header:Authorization}" ) final String token ) {
	String username = jwtTokenUtil.getUsernameFromToken( token );
	if ( StringUtils.isBlank( username ) ) {
		throw new AuthenticationCredentialsNotFoundException( "无效token" );
	}
	JwtUser user = ( JwtUser ) userDetailsService.loadUserByUsername( username );
	if ( jwtTokenUtil.canTokenBeRefreshed( token , user.getLastPasswordResetDate() ) ) {
		String refreshedToken = jwtTokenUtil.refreshToken( token );
		return new ResponseEntityPro().add( "token" , refreshedToken ).buildOk();
	} else {
		return ResponseEntityPro.badRequest( "原 token 无效" );
	}
}
 
Example 23
Source Project: springboot-vue.js-bbs   Source File: BoardServiceTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test(expected = AuthenticationCredentialsNotFoundException.class)
public void 요청한_회원의_게시물이_아니면_예외를_발생시킨다() {
    // GIVEN
    long id = boardRepository.findAll().get(0).getId();
    Board target = boardRepository.findOne(id);

    // WHEN THEN
    boardService.findOneForMod("guest", target.getId());
}
 
Example 24
Source Project: springboot-vue.js-bbs   Source File: BoardServiceTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test(expected = AuthenticationCredentialsNotFoundException.class)
public void 요청한_회원의_삭제요청이_아니면_예외를_발생시킨다() {
    // GIVEN
    long id = boardRepository.findAll().get(0).getId();
    Board target = boardRepository.findOne(id);

    // WHEN THEN
    boardService.delete("guest", target.getId());
}
 
Example 25
Source Project: joal   Source File: WebSocketAuthenticatorServiceTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void shouldThrowExceptionOnNullOrEmptyUsername() {
    final WebSocketAuthenticatorService authService = new WebSocketAuthenticatorService(TestConstant.UI_SECRET_TOKEN);
    assertThatThrownBy(() -> authService.getAuthenticatedOrFail("         ", TestConstant.UI_SECRET_TOKEN))
            .isInstanceOf(AuthenticationCredentialsNotFoundException.class)
            .hasMessageContaining("Username");

    assertThatThrownBy(() -> authService.getAuthenticatedOrFail("", TestConstant.UI_SECRET_TOKEN))
            .isInstanceOf(AuthenticationCredentialsNotFoundException.class)
            .hasMessageContaining("Username");

    assertThatThrownBy(() -> authService.getAuthenticatedOrFail(null, TestConstant.UI_SECRET_TOKEN))
            .isInstanceOf(AuthenticationCredentialsNotFoundException.class)
            .hasMessageContaining("Username");
}
 
Example 26
Source Project: joal   Source File: WebSocketAuthenticatorServiceTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void shouldThrowExceptionOnNullOrEmptyToken() {
    final WebSocketAuthenticatorService authService = new WebSocketAuthenticatorService(TestConstant.UI_SECRET_TOKEN);
    assertThatThrownBy(() -> authService.getAuthenticatedOrFail("john", "         "))
            .isInstanceOf(AuthenticationCredentialsNotFoundException.class)
            .hasMessageContaining("Authentication token");

    assertThatThrownBy(() -> authService.getAuthenticatedOrFail("john", ""))
            .isInstanceOf(AuthenticationCredentialsNotFoundException.class)
            .hasMessageContaining("Authentication token");

    assertThatThrownBy(() -> authService.getAuthenticatedOrFail("john", null))
            .isInstanceOf(AuthenticationCredentialsNotFoundException.class)
            .hasMessageContaining("Authentication token");
}
 
Example 27
@Override
public Response toResponse(AuthenticationCredentialsNotFoundException exception) {
    // log the error
    logger.info(String.format("No valid credentials were found in the request: %s. Returning %s response.", exception, Response.Status.FORBIDDEN));

    if (logger.isDebugEnabled()) {
        logger.debug(StringUtils.EMPTY, exception);
    }

    return Response.status(Response.Status.FORBIDDEN).entity("Access is denied.").type("text/plain").build();
}
 
Example 28
Source Project: secrets-proxy   Source File: TokenAuthProcessingFilter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Authentication attemptAuthentication(HttpServletRequest req, HttpServletResponse res)
    throws AuthenticationException {
  log.debug("Attempting token authentication.");
  JwtAuthToken jwtAuthToken = jwtTokenService.getAccessToken(req);
  if (jwtAuthToken == null) {
    throw new AuthenticationCredentialsNotFoundException("Authorization header is missing.");
  }
  return getAuthenticationManager().authenticate(jwtAuthToken);
}
 
Example 29
@DataProvider
public static List<List<Throwable>> unauthorized401ExceptionsDataProvider() {
    return Stream.<Throwable>of(
        new BadCredentialsException("foo"),
        new InsufficientAuthenticationException("foo"),
        new AuthenticationCredentialsNotFoundException("foo"),
        new LockedException("foo"),
        new DisabledException("foo"),
        new CredentialsExpiredException("foo"),
        new AccountExpiredException("foo"),
        new UsernameNotFoundException("foo"),
        new RemoteAuthenticationException("foo")
    ).map(Collections::singletonList)
     .collect(Collectors.toList());
}
 
Example 30
/**
 * Returns the username for the given principal.
 *
 * @param principal the principal to authenticate
 * @return the username from the given <code>principal</code>
 * @throws AuthenticationCredentialsNotFoundException if the username cannot be resolved
 */
protected String resolveUsername(Object principal) {

    if (principal instanceof String)
        return (String) principal;

    if (principal instanceof UserDetails)
        return ((UserDetails)principal).getUsername();

    throw new AuthenticationCredentialsNotFoundException("Can't find username on: " + principal);
}