@Override protected UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException { try { UserEntity user = userService.findByName(username, true); if (RepositoryIdentityProvider.PROVIDER_TYPE.equals(user.getSource())) { return mapUserEntityToUserDetails(user); } else { throw new UserNotFoundException(username); } } catch (UserNotFoundException notFound) { throw new UsernameNotFoundException(String.format("User '%s' not found", username), notFound); } catch (Exception repositoryProblem) { LOGGER.error("Failed to retrieveUser : {}", username, repositoryProblem); throw new InternalAuthenticationServiceException(repositoryProblem.getMessage(), repositoryProblem); } }
@SuppressWarnings("unchecked") private URL readTokenEndpoint(URL targetURL) { try { String infoURL = targetURL.toString() + "/v2/info"; Map<String, Object> infoMap = restTemplate.getForEntity(infoURL, Map.class).getBody(); if (infoMap == null) { throw new InternalAuthenticationServiceException("Invalid response returned from /v2/info"); } Object endpoint = infoMap.get("token_endpoint"); if (endpoint == null) endpoint = infoMap.get("authorizationEndpoint"); if (endpoint == null) { throw new InternalAuthenticationServiceException("Response from /v2/info does not contain a valid token endpoint"); } return new URL(endpoint.toString()); } catch (Exception e) { throw new InternalAuthenticationServiceException("Could not read token endpoint", e); } }
@SuppressWarnings("unchecked") private Pair<String, String> readTokenKey(URL uaaUrl) { try { String tokenKeyURL = uaaUrl.toString() + "/token_key"; Map<String, Object> tokenKeyMap = null; tokenKeyMap = restTemplate.getForEntity(tokenKeyURL, Map.class).getBody(); if (tokenKeyMap == null) { throw new InternalAuthenticationServiceException("Invalid response returned from /token_key"); } Object value = tokenKeyMap.get("value"); Object alg = tokenKeyMap.get("alg"); if (value == null || alg == null) { throw new InternalAuthenticationServiceException("Response from /token_key does not contain a key value or an algorithm"); } return new Pair<>(value.toString(), alg.toString()); } catch (Exception e) { throw new InternalAuthenticationServiceException("Could not read token verification key", e); } }
@Nonnull private static String getRemoteAddress(@Nonnull final Authentication authentication) { final Object details = authentication.getDetails(); if (details != null) { if (details instanceof WebAuthenticationDetails) { final WebAuthenticationDetails webAuthenticationDetails = (WebAuthenticationDetails) details; return webAuthenticationDetails.getRemoteAddress(); } else if (details instanceof ExternalAuthenticationDetails) { final ExternalAuthenticationDetails externalAuthenticationDetails = (ExternalAuthenticationDetails) details; return externalAuthenticationDetails.getRemoteAddress(); } } throw new InternalAuthenticationServiceException("Authentication details is missing"); }
@Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { // get username and password String username = (authentication.getPrincipal() == null) ? "" : authentication.getName(); String password = (authentication.getCredentials() == null) ? "" : authentication.getCredentials().toString(); // check credentials if (userService.checkCredentials(username, password)) { // init return value AbstractAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, null, new ArrayList<>()); // set user object authenticationToken.setDetails(userService.getUserByUsername(username)); // return user details return authenticationToken; } // indicate invalid credentials throw new InternalAuthenticationServiceException("Unable to authenticate"); }
@Override public void saveSecretForUser(String secret) { if (secret == null) { throw new InternalAuthenticationServiceException("No secretKey found"); } else { User user = getUser(); UserSecret userSecret = userSecretFactory.create(); userSecret.setUserId(user.getId()); userSecret.setSecret(secret); runAsSystem(() -> dataService.add(USER_SECRET, userSecret)); } }
@Override public boolean isConfiguredForUser() { boolean isConfigured = false; try { UserSecret secret = getSecret(); if (StringUtils.hasText(secret.getSecret())) { isConfigured = true; } } catch (InternalAuthenticationServiceException err) { LOG.warn(err.getMessage()); } return isConfigured; }
private UserSecret getSecret() { User user = getUser(); UserSecret secret = runAsSystem(() -> dataService.query(USER_SECRET, UserSecret.class) .eq(UserSecretMetaData.USER_ID, user.getId()) .findOne()); if (secret != null) { return secret; } else { throw new InternalAuthenticationServiceException( format("Secret not found, user: [{0}] is not configured for two factor authentication", user.getUsername())); } }
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException { if (!request.getMethod().equals("POST")) { throw new AuthenticationServiceException( "Authentication method not supported: " + request.getMethod()); } try { LoginRequest loginRequest = objectMapper.readValue(request.getInputStream(), LoginRequest.class); String username = Optional .ofNullable(loginRequest.getUsername()) .map(String::trim) .orElse(""); String password = Optional .ofNullable(loginRequest.getPassword()) .orElse(""); request.setAttribute(REMEMBER_ME_ATTRIBUTE, loginRequest.getRememberMe()); UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password); return this.getAuthenticationManager().authenticate(authRequest); } catch (AuthenticationException ae) { throw ae; } catch (Exception e) { throw new InternalAuthenticationServiceException(e.getMessage(), e); } }
/** * * @return user */ public User getUser() { if(context.getUserPrincipal() == null) { throw new InternalAuthenticationServiceException("User not found"); } return new User(context.getUserPrincipal().getName()); }
public static void assertNotBlocked(UserDetails userDetails, Authentication authentication) { try { if (isAllowedRemote(userDetails, authentication)) { return; } } catch (RuntimeException ex) { throw new InternalAuthenticationServiceException("Internal error", ex); } throw new RemoteAddressBlockedException("Remote address is not allowed"); }
@Override public User loadUserByUsername(Authentication authentication) { try { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); DirContextOperations authenticate; try { Thread.currentThread().setContextClassLoader(getClass().getClassLoader()); // authenticate user authenticate = authenticator.authenticate(new UsernamePasswordAuthenticationToken( authentication.getPrincipal(), authentication.getCredentials())); // fetch user groups try { List<String> groups = authoritiesPopulator .getGrantedAuthorities(authenticate, authenticate.getNameInNamespace()).stream() .map(a -> a.getAuthority()) .collect(Collectors.toList()); authenticate.setAttributeValue(MEMBEROF_ATTRIBUTE, groups); } catch (Exception e) { LOGGER.warn("No group found for user {}", authenticate.getNameInNamespace(), e); } } finally { Thread.currentThread().setContextClassLoader(classLoader); } return createUser(authenticate); } catch (UsernameNotFoundException notFound) { throw notFound; } catch (NamingException ldapAccessFailure) { throw new InternalAuthenticationServiceException( ldapAccessFailure.getMessage(), ldapAccessFailure); } }
@Override public User loadUserByUsername(String username) { try { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); DirContextOperations authenticate; try { Thread.currentThread().setContextClassLoader(getClass().getClassLoader()); // find user authenticate = userSearch.searchForUser(username); // fetch user groups try { List<String> groups = authoritiesPopulator .getGrantedAuthorities(authenticate, authenticate.getNameInNamespace()).stream() .map(a -> a.getAuthority()) .collect(Collectors.toList()); authenticate.setAttributeValue(MEMBEROF_ATTRIBUTE, groups); } catch (Exception e) { LOGGER.warn("No group found for user {}", authenticate.getNameInNamespace(), e); } } finally { Thread.currentThread().setContextClassLoader(classLoader); } return createUser(authenticate); } catch (UsernameNotFoundException notFound) { throw notFound; } catch (NamingException ldapAccessFailure) { throw new InternalAuthenticationServiceException( ldapAccessFailure.getMessage(), ldapAccessFailure); } }
private Authentication tryToAuthenticate(Authentication requestAuthentication) { Authentication responseAuthentication = authenticationManager.authenticate(requestAuthentication); if (responseAuthentication == null || !responseAuthentication.isAuthenticated()) { throw new InternalAuthenticationServiceException("Unable to authenticate Backend Admin for provided credentials"); } logger.debug("Backend Admin successfully authenticated"); return responseAuthentication; }
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpRequest = asHttp(request); HttpServletResponse httpResponse = asHttp(response); Optional<String> username = Optional.fromNullable(httpRequest.getParameter("username")); Optional<String> password = Optional.fromNullable(httpRequest.getParameter("password")); Optional<String> token = Optional.fromNullable(httpRequest.getHeader("Authorization")); String resourcePath = new UrlPathHelper().getPathWithinApplication(httpRequest); try { if (postToAuthenticate(httpRequest, resourcePath)) { logger.debug("Trying to authenticate user {} by Username method", username); processUsernamePasswordAuthentication(httpResponse, username, password); return; } if (token.isPresent()) { logger.debug("Trying to authenticate user by Token method. Token: {}", token); processTokenAuthentication(token); } logger.debug("AuthenticationFilter is passing request down the filter chain"); addSessionContextToLogging(); chain.doFilter(request, response); } catch (InternalAuthenticationServiceException internalAuthenticationServiceException) { SecurityContextHolder.clearContext(); logger.error("Internal authentication service exception", internalAuthenticationServiceException); httpResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } catch (AuthenticationException authenticationException) { SecurityContextHolder.clearContext(); httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, authenticationException.getMessage()); } finally { MDC.remove(TOKEN_SESSION_KEY); MDC.remove(USER_SESSION_KEY); } }
private Authentication tryToAuthenticate(Authentication requestAuthentication) { Authentication responseAuthentication = authenticationManager.authenticate(requestAuthentication); if (responseAuthentication == null || !responseAuthentication.isAuthenticated()) { throw new InternalAuthenticationServiceException("Unable to authenticate Domain User for provided credentials"); } logger.debug("User successfully authenticated"); return responseAuthentication; }
@Override protected UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException { UserDetails loadedUser; try { loadedUser = loadUser(username, authentication.getCredentials().toString()); } catch (Exception repositoryProblem) { throw new InternalAuthenticationServiceException(repositoryProblem.getMessage(), repositoryProblem); } return loadedUser; }
@Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { final String name = authentication.getName(); final Object details = authentication.getDetails(); if (!(details instanceof DashboardAuthenticationDetails)) { throw new InternalAuthenticationServiceException("The authentication details [" + details + "] are not an instance of " + DashboardAuthenticationDetails.class.getSimpleName()); } try { final DashboardUser byName = userRepository.findByName(name); if (byName == null) { final DashboardAuthenticationDetails oauthDetails = (DashboardAuthenticationDetails) details; final DashboardUser user = new DashboardUser(); user.setName(name); user.setFullName(oauthDetails.getUserFullName()); userRepository.save(user); } } catch (Exception e) { throw new InternalAuthenticationServiceException("Error while creating a user based on [" + name + "]", e); } return authentication; }
/** * Returns the current service instance id. */ private String getServiceInstance() { final File config = new File(serviceInstanceIdFile); try { return new String(FileCopyUtils.copyToByteArray(config)); } catch (IOException e) { throw new InternalAuthenticationServiceException("Error while retrieving the service instance", e); } }
@Test(expected = InternalAuthenticationServiceException.class) public void authenticateErrorSave(){ final DashboardUserRepository mock = mock(DashboardUserRepository.class); when(mock.save(Matchers.<DashboardUser>any())) .thenThrow(new RuntimeException("Planned exception")); createProvider(mock).authenticate(createAuthentication(johnUser())); }
@Override protected void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException { super.additionalAuthenticationChecks(userDetails, authentication); if (authentication.getDetails() instanceof TotpWebAuthenticationDetails) { String secret = ((JpaUserDetails) userDetails).getSecret(); if (StringUtils.hasText(secret)) { Integer totpKey = ((TotpWebAuthenticationDetails) authentication .getDetails()).getTotpKey(); if (totpKey != null) { try { if (!TotpAuthenticatorUtil.verifyCode(secret, totpKey, 2)) { throw new BadCredentialsException( "Google Authenticator Code is not valid"); } } catch (InvalidKeyException | NoSuchAlgorithmException e) { throw new InternalAuthenticationServiceException( "Google Authenticator Code verify failed", e); } } else { throw new MissingTotpKeyAuthenticatorException( "Google Authenticator Code is mandatory"); } } } }
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpRequest = asHttp(request); HttpServletResponse httpResponse = asHttp(response); Optional<String> username = Optional.fromNullable(httpRequest.getHeader("X-Auth-Username")); Optional<String> password = Optional.fromNullable(httpRequest.getHeader("X-Auth-Password")); Optional<String> token = Optional.fromNullable(httpRequest.getHeader("X-Auth-Token")); String resourcePath = new UrlPathHelper().getPathWithinApplication(httpRequest); try { if (postToAuthenticate(httpRequest, resourcePath)) { logger.debug("Trying to authenticate user {} by X-Auth-Username method", username); processUsernamePasswordAuthentication(httpResponse, username, password); return; } if (token.isPresent()) { logger.debug("Trying to authenticate user by X-Auth-Token method. Token: {}", token); processTokenAuthentication(token); } logger.debug("AuthenticationFilter is passing request down the filter chain"); addSessionContextToLogging(); chain.doFilter(request, response); } catch (InternalAuthenticationServiceException internalAuthenticationServiceException) { SecurityContextHolder.clearContext(); logger.error("Internal authentication service exception", internalAuthenticationServiceException); httpResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } catch (AuthenticationException authenticationException) { SecurityContextHolder.clearContext(); httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, authenticationException.getMessage()); } finally { MDC.remove(TOKEN_SESSION_KEY); MDC.remove(USER_SESSION_KEY); } }
private String determineErrorMessagesFromInternalAuthenticationExceptions(Object attribute) { String errorMessage = ""; if (attribute instanceof InternalAuthenticationServiceException) { Throwable throwable = ((InternalAuthenticationServiceException) attribute).getCause(); if (throwable.getCause() instanceof UsernameNotFoundException) { errorMessage = ERROR_MESSAGE_BAD_CREDENTIALS; } } return errorMessage; }
private void tryAuthenticate(Authentication requestAuth) { Authentication authentication = authenticationManager.authenticate(requestAuth); if (authentication == null || !authentication.isAuthenticated()) { throw new InternalAuthenticationServiceException("Unable to authenticate user with provided credentials"); } logger.debug("Successfully authenticated"); SecurityContextHolder.getContext().setAuthentication(authentication); }
@Test(expected = InternalAuthenticationServiceException.class) public void isManagingFailToLoadSuidFile() { final DashboardAuthenticationDetailsSource source = createSource(createRestTemplate(), "/does-not-exist.txt"); source.buildDetails(new MockHttpServletRequest()); }
@Test(expected = InternalAuthenticationServiceException.class) public void authenticationNotOauth() { provider.authenticate(new TestingAuthenticationToken("user", "pwd")); }