org.springframework.security.authentication.AuthenticationCredentialsNotFoundException Java Examples

The following examples show how to use org.springframework.security.authentication.AuthenticationCredentialsNotFoundException. 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: RestResponseHandler.java    From api-layer with 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 File: AuthorizationWebFilter.java    From spring-security-reactive with Apache License 2.0 6 votes vote down vote up
@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 #3
Source File: AjaxAuthenticationProvider.java    From OpenLRW with Educational Community License v2.0 6 votes vote down vote up
@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 #4
Source File: InsightsSAMLTokenAuthenticationImpl.java    From Insights with Apache License 2.0 6 votes vote down vote up
/**
 * 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 #5
Source File: JwtAuthenticationFilter.java    From paas with 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 #6
Source File: JwtTokenService.java    From secrets-proxy with 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 #7
Source File: LoginFilter.java    From api-layer with 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 #8
Source File: AuthExceptionHandler.java    From api-layer with 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 #9
Source File: WebSocketAuthenticatorService.java    From joal with 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 #10
Source File: JwtAuthenticationFilter.java    From blog-sample with 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 #11
Source File: AuthDataAccessor.java    From syncope with 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 #12
Source File: UserDetailServiceImpl.java    From cloud-service with 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 #13
Source File: BoardServiceTest.java    From springboot-vue.js-bbs with 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 #14
Source File: LoginFilterTest.java    From api-layer with 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 #15
Source File: BoardServiceTest.java    From springboot-vue.js-bbs with 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 #16
Source File: AuthenticationController.java    From spring-boot-start-current with Apache License 2.0 5 votes vote down vote up
/**
 * 刷新并认证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 #17
Source File: UserDetailServiceImpl.java    From open-capacity-platform with Apache License 2.0 5 votes vote down vote up
@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 #18
Source File: LoginFilterTest.java    From api-layer with 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 #19
Source File: LoginFilterTest.java    From api-layer with 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
Source File: WebSocketAuthenticatorServiceTest.java    From joal with 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 #21
Source File: WebSocketAuthenticatorServiceTest.java    From joal with 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 #22
Source File: TokenProviderUtility.java    From Insights with Apache License 2.0 5 votes vote down vote up
/**
 * Used to verify received token with cached token
 * 
 * @param token
 * @return
 * @throws AuthorizationServiceException
 * @throws AuthenticationCredentialsNotFoundException
 * @throws AccountExpiredException
 * @throws InsightsCustomException
 */
public boolean verifyToken(String token) throws AuthorizationServiceException,
		AuthenticationCredentialsNotFoundException, AccountExpiredException, InsightsCustomException {
	boolean isVerify = Boolean.FALSE;
	boolean isTokenExistsInCache = Boolean.FALSE;
	boolean validateTokenDate = Boolean.FALSE;
	//log.debug(" In verifyToken ");
	try {
		String authToken = ValidationUtils.cleanXSS(token);
		if (authToken == null || authToken.isEmpty()) {
			log.error("authToken is null or empty");
			throw new InsightsCustomException("authToken is null or empty");
		}

		// parse the JWS and verify its HMAC
		SignedJWT signedJWT = SignedJWT.parse(authToken);
		JWSVerifier verifier = new MACVerifier(signingKey);
		isVerify = signedJWT.verify(verifier);

		String id = signedJWT.getJWTClaimsSet().getJWTID();
		String tokenValueFromCache = null;
		if (TokenProviderUtility.tokenCache != null) {
			tokenValueFromCache = TokenProviderUtility.tokenCache.get(id);
		} else {
			log.error("cache is not initilize properly");
		}

		if (tokenValueFromCache == null) {
			log.debug("No token found in cache");
		} else if (tokenValueFromCache.equalsIgnoreCase(authToken)) {
			//log.debug("Token value matched in cache === ");
			isTokenExistsInCache = Boolean.TRUE;
		} else {
			log.error("Token value not matched in cache=== ");
		}

		//log.debug("alice  after " + signedJWT.getJWTClaimsSet().getSubject());
		//log.debug("cognizant.com  " + signedJWT.getJWTClaimsSet().getIssuer());
		//log.debug("Exceperation Time after  " + signedJWT.getJWTClaimsSet().getExpirationTime());
		log.debug("Check date of token with current date {} ",
				new Date().before(signedJWT.getJWTClaimsSet().getExpirationTime()));//after
		validateTokenDate = new Date().before(signedJWT.getJWTClaimsSet().getExpirationTime());//after

	} catch (Exception e) {
		log.error(e);
		log.error(" Exception while validating token {} ", e.getMessage());
		isVerify = Boolean.FALSE;
		throw new InsightsCustomException("Exception while varifing token ==== " + e.getMessage());
	}

	if (!isVerify) {
		log.debug("Token signuture not match ");
		isVerify = Boolean.FALSE;
		throw new AuthorizationServiceException("Token signuture not match");
	} else if (!isTokenExistsInCache) {
		log.error("Token Not matched ");
		isVerify = Boolean.FALSE;
		throw new AuthenticationCredentialsNotFoundException("Token not found in cache");
	} else if (!validateTokenDate) {
		isVerify = Boolean.FALSE;
		throw new AccountExpiredException("Token Expire");
	} else {
		log.debug("Token verified sucessfully ==== ");
		isVerify = Boolean.TRUE;
	}

	log.debug(" is Token Verify  ====  {} ", isVerify);

	return isVerify;
}
 
Example #23
Source File: AuthenticationCredentialsNotFoundExceptionMapper.java    From nifi-registry with Apache License 2.0 5 votes vote down vote up
@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 #24
Source File: TokenAuthProcessingFilter.java    From secrets-proxy with 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 #25
Source File: OneOffSpringCommonFrameworkExceptionHandlerListenerTest.java    From backstopper with Apache License 2.0 5 votes vote down vote up
@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 #26
Source File: DirectAccessGrantAuthenticationProvider.java    From smartling-keycloak-extras with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
}
 
Example #27
Source File: AuthenticationCredentialsNotFoundExceptionMapper.java    From nifi with Apache License 2.0 5 votes vote down vote up
@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 File: PasswordResetterImpl.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Transactional
@Override
public void changePasswordAuthenticatedUser(String password) {
  String username = SecurityUtils.getCurrentUsername();
  if (username == null) {
    throw new AuthenticationCredentialsNotFoundException("not authenticated");
  }
  User user = getUser(username);
  user.setPassword(password);
  user.setChangePassword(false);
  RunAsSystemAspect.runAsSystem(() -> userService.update(user));
}
 
Example #29
Source File: PasswordResetterImplTest.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
void testChangePasswordAuthenticatedUserNoAuthenticedUser() {
  SecurityContext securityContext = mock(SecurityContext.class);
  SecurityContextHolder.setContext(securityContext);
  assertThrows(
      AuthenticationCredentialsNotFoundException.class,
      () -> passwordResetServiceImpl.changePasswordAuthenticatedUser("MyPassword"));
}
 
Example #30
Source File: AbstractUserRestController.java    From JiwhizBlogWeb with Apache License 2.0 5 votes vote down vote up
protected UserAccount getCurrentAuthenticatedUser() {
    UserAccount currentUser = this.userAccountService.getCurrentUser();
    if (currentUser == null) {
        throw new AuthenticationCredentialsNotFoundException("User not logged in.");
    }
    return currentUser;
}