下面列出了怎么用org.springframework.security.authentication.AuthenticationCredentialsNotFoundException的API类实例代码及写法,或者点击链接到github查看源代码。
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);
}
}
@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;
}
@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);
}
}
}
/**
* 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);
}
}
/**
* 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;
}
@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);
}
}
@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")
);
}
@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());
}
/**
* 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;
}
/**
* 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;
}
@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);
});
}
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;
}
@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;
}
@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();
}
/**
* 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.");
}
}
@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());
}
@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);
}
@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);
}
@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);
}
@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);
}
}
/**
* 得到凭证
*/
private static Authentication getAuthentication () {
final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if ( Objects.isNull( authentication ) ) {
throw new AuthenticationCredentialsNotFoundException( "未授权" );
}
return authentication;
}
/**
* 刷新并认证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 无效" );
}
}
@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());
}
@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());
}
@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");
}
@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");
}
@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();
}
@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);
}
@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());
}
/**
* 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);
}