List of usage examples for org.springframework.security.authentication UsernamePasswordAuthenticationToken getCredentials
public Object getCredentials()
From source file:org.jutge.joc.porra.security.MongoDBAuthenticationProvider.java
@Override public UserDetails retrieveUser(final String name, final UsernamePasswordAuthenticationToken authentication) throws AuthenticationException { this.logger.info("MongoDBAuthenticationProvider.retrieveUser"); boolean valid = true; // Make sure an actual password was entered final String password = (String) authentication.getCredentials(); if (!StringUtils.hasText(password)) { this.logger.warn("Username {}: no password provided", name); valid = false;// w w w . ja v a 2s. c o m } // Look for user and check their account is activated final Account account = this.accountService.getByName(name); if (account == null) { this.logger.warn("Username {}: user not found", name); valid = false; } else { if (!AccountStatus.STATUS_APPROVED.name().equals(account.getStatus())) { this.logger.warn("Username {}: not approved", name); valid = false; } // Check password final String hashedPassword = BCrypt.hashpw(password, account.getSalt()); if (!hashedPassword.equals(account.getHashedPass())) { this.logger.warn("Username {}: bad password entered", name); valid = false; } } if (!valid) { final Locale locale = LocaleContextHolder.getLocale(); final String message = this.messageSource.getMessage("exception.wrongAccountNameAndPass", null, locale); final MessageBox messageBox = new MessageBox("wrongAccountNameAndPass", message, new ArrayList<String>()); final List<MessageBox> errorMessages = new ArrayList<MessageBox>(); errorMessages.add(messageBox); final LoginException loginException = new LoginException(errorMessages, name); throw new BadCredentialsException("Invalid Username/Password", loginException); } // Create Springframework-typed User instance final List<String> roles = account.getRoles(); final List<GrantedAuthority> auths = !roles.isEmpty() ? AuthorityUtils.commaSeparatedStringToAuthorityList(account.getRolesCSV()) : AuthorityUtils.NO_AUTHORITIES; // enabled, account not expired, credentials not expired, account not locked return new User(name, password, true, true, true, true, auths); }
From source file:waffle.spring.WindowsAuthenticationProvider.java
@Override public Authentication authenticate(final Authentication authentication) { final UsernamePasswordAuthenticationToken auth = (UsernamePasswordAuthenticationToken) authentication; final IWindowsIdentity windowsIdentity = this.authProvider.logonUser(auth.getName(), auth.getCredentials().toString()); WindowsAuthenticationProvider.LOGGER.debug("logged in user: {} ({})", windowsIdentity.getFqn(), windowsIdentity.getSidString()); if (!this.allowGuestLogin && windowsIdentity.isGuest()) { WindowsAuthenticationProvider.LOGGER.warn("guest login disabled: {}", windowsIdentity.getFqn()); throw new GuestLoginDisabledAuthenticationException(windowsIdentity.getFqn()); }// w w w . ja v a 2s.co m final WindowsPrincipal windowsPrincipal = new WindowsPrincipal(windowsIdentity, this.principalFormat, this.roleFormat); WindowsAuthenticationProvider.LOGGER.debug("roles: {}", windowsPrincipal.getRolesString()); final WindowsAuthenticationToken token = new WindowsAuthenticationToken(windowsPrincipal, this.grantedAuthorityFactory, this.defaultGrantedAuthority); WindowsAuthenticationProvider.LOGGER.info("successfully logged in user: {}", windowsIdentity.getFqn()); return token; }
From source file:es.sas.lopd.infraestructura.seguridad.impl.DaoAuthenticationProvider.java
protected final UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException { UserDetails loadedUser;/*from ww w . j a v a 2s. com*/ try { loadedUser = this.getUserDetailsService().loadUserByUsername( username + ConstantesDatos.CADENA_SEPARACION_LOGIN + authentication.getCredentials()); } catch (UsernameNotFoundException notFound) { throw notFound; } catch (Exception repositoryProblem) { throw new AuthenticationServiceException(repositoryProblem.getMessage(), repositoryProblem); } if (loadedUser == null) { throw new AuthenticationServiceException( "UserDetailsService returned null, which is an interface contract violation"); } return loadedUser; }
From source file:iplatform.admin.ui.server.auth.ad.ActiveDirectoryLdapAuthenticationProvider.java
@Override protected DirContextOperations doAuthentication(UsernamePasswordAuthenticationToken auth) { String username = auth.getName(); String password = (String) auth.getCredentials(); DirContext ctx = bindAsUser(username, password); try {/*w ww . j a va2s . c o m*/ return searchForUser(ctx, username); } catch (NamingException e) { logger.error("Failed to locate directory entry for authenticated user: " + username, e); throw badCredentials(e); } finally { LdapUtils.closeContext(ctx); } }
From source file:com.telefonica.euro_iaas.sdc.rest.auth.OpenStackAuthenticationProvider.java
@Override protected final UserDetails retrieveUser(final String username, final UsernamePasswordAuthenticationToken authentication) { String system = systemPropertiesProvider.getProperty(SystemPropertiesProvider.CLOUD_SYSTEM); PaasManagerUser user = null;/*from w w w.j a v a 2s . c o m*/ String tenantId = authentication.getCredentials().toString(); if (SYSTEM_FIWARE.equals(system)) { user = authenticationFiware(username, tenantId); } else if (SYSTEM_FASTTRACK.equals(system)) { user = authenticationFastTrack(username, tenantId); } return user; }
From source file:com.telefonica.euro_iaas.sdc.puppetwrapper.auth.OpenStackAuthenticationProvider.java
@Override protected final UserDetails retrieveUser(final String username, final UsernamePasswordAuthenticationToken authentication) { PaasManagerUser user = null;/* w w w.j a v a 2s . c o m*/ String tenantId = null; if (null != authentication.getCredentials()) { tenantId = authentication.getCredentials().toString(); if (SYSTEM_FIWARE.equals(cloudSystem)) { try { user = authenticationFiware(username, tenantId); } catch (AuthenticationConnectionException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else if (SYSTEM_FASTTRACK.equals(cloudSystem)) { user = authenticationFastTrack(username, tenantId); } } else { String str = "Missing tenantId header"; log.info(str); throw new BadCredentialsException(str); } return user; }
From source file:ph.fingra.statisticsweb.security.FingraphAnthenticationProvider.java
@Override protected void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException { Object salt = null;//from w ww .j a v a 2 s . c o m if (this.saltSource != null) { salt = this.saltSource.getSalt(userDetails); } if (authentication.getCredentials() == null) { logger.debug("Authentication failed: no credentials provided"); throw new BadCredentialsException( messages.getMessage("Invalid user id or password. Please try again.", "Bad credentials"), userDetails); } String presentedPassword = authentication.getCredentials().toString(); logger.debug("userDetails {}, presentedPassword {}", userDetails, presentedPassword); if (!passwordEncoder.isPasswordValid(userDetails.getPassword(), presentedPassword, salt)) { logger.debug("Authentication failed: password does not match stored value"); //throw new BadCredentialsException( // messages.getMessage("Invalid user id or password. Please try again.", "Bad credentials"), // userDetails); throw new PasswordMissmatchUserException("Invalid user id or password. Please try again.", userDetails); } FingraphUser member = (FingraphUser) userDetails; if (MemberStatus.valueOf(member.getStatus()) != MemberStatus.ACTIVE) { logger.debug("Authentication failed: un-active user"); throw new UnverifiedUserException("AbstractUserDetailsAuthenticationProvider.disabled", userDetails); } if (MemberJoinstatus.valueOf(member.getJoinstatus()) != MemberJoinstatus.APPROVAL) { logger.debug("Authentication failed: un-approval user"); throw new UnapprovalUserException("AbstractUserDetailsAuthenticationProvider.disabled", userDetails); } }
From source file:com.haulmont.restapi.auth.CubaUserAuthenticationProvider.java
@Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder .currentRequestAttributes(); HttpServletRequest request = attributes.getRequest(); String ipAddress = request.getRemoteAddr(); if (authentication instanceof UsernamePasswordAuthenticationToken) { RestApiConfig config = configuration.getConfig(RestApiConfig.class); if (!config.getStandardAuthenticationEnabled()) { log.debug(/*w w w . j a v a 2 s. co m*/ "Standard authentication is disabled. Property cuba.rest.standardAuthenticationEnabled is false"); throw new InvalidGrantException("Authentication disabled"); } UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) authentication; String login = (String) token.getPrincipal(); UserSession session; try { String passwordHash = passwordEncryption.getPlainHash((String) token.getCredentials()); LoginPasswordCredentials credentials = new LoginPasswordCredentials(login, passwordHash); credentials.setIpAddress(ipAddress); credentials.setClientType(ClientType.REST_API); credentials.setClientInfo(makeClientInfo(request.getHeader(HttpHeaders.USER_AGENT))); //if the locale value is explicitly passed in the Accept-Language header then set its value to the //credentials. Otherwise, the locale of the user should be used Locale locale = restAuthUtils.extractLocaleFromRequestHeader(request); if (locale != null) { credentials.setLocale(locale); credentials.setOverrideLocale(true); } else { credentials.setOverrideLocale(false); } session = authenticationService.login(credentials).getSession(); } catch (AccountLockedException le) { log.info("Blocked user login attempt: login={}, ip={}", login, ipAddress); throw new LockedException("User temporarily blocked"); } catch (RestApiAccessDeniedException ex) { log.info("User is not allowed to use the REST API {}", login); throw new BadCredentialsException("User is not allowed to use the REST API"); } catch (LoginException e) { log.info("REST API authentication failed: {} {}", login, ipAddress); throw new BadCredentialsException("Bad credentials"); } AppContext.setSecurityContext(new SecurityContext(session)); UsernamePasswordAuthenticationToken result = new UsernamePasswordAuthenticationToken( authentication.getPrincipal(), authentication.getCredentials(), getRoleUserAuthorities(authentication)); @SuppressWarnings("unchecked") Map<String, String> details = (Map<String, String>) authentication.getDetails(); details.put(SESSION_ID_DETAILS_ATTRIBUTE, session.getId().toString()); result.setDetails(details); return result; } return null; }
From source file:com.telefonica.euro_iaas.paasmanager.rest.auth.OpenStackAuthenticationProviderTest.java
@Test(expected = AuthenticationServiceException.class) public void shouldReturnErrorWithFailInOpenStack() { // Given//from ww w.j a v a2s . c om OpenStackAuthenticationProvider openStackAuthenticationProvider = new OpenStackAuthenticationProvider(); openStackAuthenticationProvider.setSystemPropertiesProvider(systemPropertiesProvider); openStackAuthenticationToken = mock(OpenStackAuthenticationToken.class); openStackAuthenticationProvider.setoSAuthToken(openStackAuthenticationToken); OpenStackAccess openStackAccess = new OpenStackAccess(); openStackAccess.setToken("token1"); openStackAccess.setTenantId("tenantId1"); when(openStackAuthenticationToken.getAdminCredentials(any(Client.class))).thenReturn(openStackAccess); Client client = mock(Client.class); when(openStackAuthenticationToken.getKeystoneURL()).thenReturn(keystoneURL); openStackAuthenticationProvider.setClient(client); WebTarget webResource = mock(WebTarget.class); when(client.target("http://keystone.test")).thenReturn(webResource); Invocation.Builder builder = mock(Invocation.Builder.class); when(webResource.request()).thenReturn(builder); when(builder.accept(MediaType.APPLICATION_JSON)).thenReturn(builder); when(builder.header("X-Auth-Token", "token1")).thenReturn(builder); when(builder.header("X-Subject-Token", "user token")).thenReturn(builder); Response response = mock(Response.class); when(builder.get()).thenReturn(response); when(response.getStatus()).thenReturn(500); // mock response openStackAuthenticationProvider.getTokenCache().removeAll(); UsernamePasswordAuthenticationToken authentication = mock(UsernamePasswordAuthenticationToken.class); when(authentication.getCredentials()).thenReturn("user tenantId"); // When openStackAuthenticationProvider.retrieveUser("user token", authentication); // Then verify(response).getStatus(); }
From source file:com.telefonica.euro_iaas.paasmanager.rest.auth.OpenStackAuthenticationProviderTest.java
@Test(expected = AuthenticationServiceException.class) public void shouldReturnErrorWithInvalidToken() { // Given/*from w w w .ja v a 2 s . co m*/ OpenStackAuthenticationProvider openStackAuthenticationProvider = new OpenStackAuthenticationProvider(); openStackAuthenticationProvider.setSystemPropertiesProvider(systemPropertiesProvider); openStackAuthenticationToken = mock(OpenStackAuthenticationToken.class); openStackAuthenticationProvider.setoSAuthToken(openStackAuthenticationToken); OpenStackAccess openStackAccess = new OpenStackAccess(); openStackAccess.setToken("token1"); openStackAccess.setTenantId("tenantId1"); when(openStackAuthenticationToken.getAdminCredentials(any(Client.class))).thenReturn(openStackAccess); Client client = mock(Client.class); when(openStackAuthenticationToken.getKeystoneURL()).thenReturn(keystoneURL); openStackAuthenticationProvider.setClient(client); WebTarget webResource = mock(WebTarget.class); when(client.target("http://keystone.test")).thenReturn(webResource); Invocation.Builder builder = mock(Invocation.Builder.class); when(webResource.request()).thenReturn(builder); when(builder.accept(MediaType.APPLICATION_JSON)).thenReturn(builder); when(builder.header("X-Auth-Token", "token1")).thenReturn(builder); when(builder.header("X-Subject-Token", "user token")).thenReturn(builder); Response response = mock(Response.class); when(builder.get()).thenReturn(response); when(response.getStatus()).thenReturn(401); // mock response openStackAuthenticationProvider.getTokenCache().removeAll(); UsernamePasswordAuthenticationToken authentication = mock(UsernamePasswordAuthenticationToken.class); when(authentication.getCredentials()).thenReturn("user tenantId"); // When openStackAuthenticationProvider.retrieveUser("user token", authentication); // Then verify(response).getStatus(); }