List of usage examples for org.springframework.security.core Authentication getCredentials
Object getCredentials();
From source file:com.himanshu.poc.springbootsec.security.AuthenticationProviderImpl.java
@Override public Authentication authenticate(Authentication arg0) throws AuthenticationException { logger.info(" User name is : " + arg0.getName()); if (arg0.getName() == null || arg0.getName().isEmpty()) { //Token Based Authentication required logger.info("Since username is null or empty, hence token based authentication will be required"); String tokenStr = (String) arg0.getCredentials(); String userName = tokenKeeperService.queryUserByToken(tokenStr); UserDO user = userDao.getUserByUserName(userName); logger.info("Auth success"); UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(user.getPrincipal(), user.getCredentials(), user.getAuthorities()); return token; } else {//from w w w . j av a2 s . c om //Normal Authentication logger.info( "Since username is NOT null, hence username/password based authentication will be required"); UserDO user = userDao.getUserByUserName(arg0.getName()); if (user != null && user.getCredentials().equals(arg0.getCredentials())) { logger.info("Auth success"); UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken( user.getPrincipal(), user.getCredentials(), user.getAuthorities()); return token; } } logger.error("Auth failed"); return null; }
From source file:org.ligoj.app.http.security.RestAuthenticationProviderTest.java
/** * Generate a mock authentication//*from w w w. j av a 2 s .c o m*/ */ private Authentication prepareAuthentication(final String user) { final Authentication authentication = Mockito.mock(Authentication.class); final Object credential = Mockito.mock(Object.class); Mockito.when(credential.toString()).thenReturn(""); final Object principal = Mockito.mock(Object.class); Mockito.when(principal.toString()).thenReturn(user); Mockito.when(authentication.getCredentials()).thenReturn(credential); Mockito.when(authentication.getPrincipal()).thenReturn(principal); return authentication; }
From source file:org.ligoj.app.http.security.RestAuthenticationProviderTest.java
@Test public void authenticateInvalidException() { authenticationProvider.setSsoPostUrl(""); authenticationProvider.setSsoWelcome(""); authenticationProvider.setSsoPostContent("%d%d"); final Authentication authentication = Mockito.mock(Authentication.class); final Object credential = Mockito.mock(Object.class); Mockito.when(credential.toString()).thenReturn(""); final Object principal = Mockito.mock(Object.class); Mockito.when(principal.toString()).thenReturn(null); Mockito.when(authentication.getCredentials()).thenReturn(credential); Mockito.when(authentication.getPrincipal()).thenReturn(principal); Assertions.assertThrows(IllegalFormatConversionException.class, () -> { authenticationProvider.authenticate(authentication); });/*from w w w. j a va 2s . c om*/ }
From source file:org.syncope.core.security.SyncopeAuthenticationProvider.java
@Override @Transactional(noRollbackFor = { BadCredentialsException.class }) public Authentication authenticate(final Authentication authentication) throws AuthenticationException { boolean authenticated; SyncopeUser passwordUser = new SyncopeUser(); SyncopeUser user = null;//from ww w . j av a 2s . co m if (adminUser.equals(authentication.getPrincipal())) { passwordUser.setPassword(authentication.getCredentials().toString(), CipherAlgorithm.MD5, 0); authenticated = adminMD5Password.equalsIgnoreCase(passwordUser.getPassword()); } else { String username; try { username = authentication.getPrincipal().toString(); } catch (NumberFormatException e) { throw new UsernameNotFoundException("Invalid username: " + authentication.getName(), e); } user = userDAO.find(username); if (user == null) { throw new UsernameNotFoundException("Could not find user " + username); } passwordUser.setPassword(authentication.getCredentials().toString(), user.getCipherAlgoritm(), 0); authenticated = user.getPassword().equalsIgnoreCase(passwordUser.getPassword()); } Authentication result; if ((user == null || !user.getSuspended()) && authenticated) { UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken( authentication.getPrincipal(), null, userDetailsService .loadUserByUsername(authentication.getPrincipal().toString()).getAuthorities()); token.setDetails(authentication.getDetails()); result = token; LOG.debug("User {} authenticated with roles {}", authentication.getPrincipal(), token.getAuthorities()); if (user != null) { user.setLastLoginDate(new Date()); user.setFailedLogins(0); userDAO.save(user); } } else { result = authentication; if (user != null && !user.getSuspended()) { user.setFailedLogins(user.getFailedLogins() + 1); userDAO.save(user); } LOG.debug("User {} not authenticated", authentication.getPrincipal()); throw new BadCredentialsException("User " + authentication.getPrincipal() + " not authenticated"); } return result; }
From source file:org.shaigor.rest.retro.client.oauth.OAuthPostAuthListener.java
@Override public void onApplicationEvent(AbstractAuthenticationEvent event) { Authentication authentication = event.getAuthentication(); if (event instanceof AuthenticationSuccessEvent) { ResourceOwnerPasswordResourceDetails resource = getResourceOwnerPasswordResourceDetails(); resource.setScope(Arrays.asList("words")); resource.setUsername(authentication.getName()); resource.setPassword(authentication.getCredentials().toString()); try {//from ww w . jav a 2 s . c om OAuth2AccessToken accessToken = accessTokenProvider.obtainAccessToken(resource, new DefaultAccessTokenRequest()); log.debug("Access token request succeeded for user: '{}', new token is '{}'", resource.getUsername(), accessToken.getValue()); if (authentication instanceof AbstractAuthenticationToken && authentication.getDetails() instanceof CustomAuthenticationDetails) { ((CustomAuthenticationDetails) ((AbstractAuthenticationToken) authentication).getDetails()) .setBearer(accessToken.getValue()); log.debug("Access token was added to authentication as details"); } else if (log.isDebugEnabled()) { log.debug("Access token could not be added to authentication as details"); } } catch (Exception e) { log.error("Access token request failed for user: '" + resource.getUsername() + "'", e); } } if (authentication instanceof CredentialsContainer) { // Authentication is complete. Remove credentials and other secret data from authentication ((CredentialsContainer) authentication).eraseCredentials(); } }
From source file:com.ushahidi.swiftriver.core.api.auth.crowdmapid.CrowdmapIDAuthenticationProviderTest.java
/** * Tests authenticating a user via CrowmdmapID *///from w ww. j av a 2 s . co m @SuppressWarnings("unchecked") @Test public void authenticate() { Authentication mockAuthentication = mock(Authentication.class); Object mockCredentials = mock(Object.class); User mockUser = mock(User.class); Set<Role> userRoles = new HashSet<Role>(); Role role = new Role(); role.setName("user"); userRoles.add(role); when(mockAuthentication.getName()).thenReturn("test@swiftapp.com"); when(mockAuthentication.getCredentials()).thenReturn(mockCredentials); when(mockCredentials.toString()).thenReturn("pa55w0rd"); when(mockCrowdmapIDClient.signIn(anyString(), anyString())).thenReturn(true); when(mockUserDao.findByUsernameOrEmail(anyString())).thenReturn(mockUser); when(mockUser.getRoles()).thenReturn(userRoles); Authentication authentication = authenticationProvider.authenticate(mockAuthentication); List<GrantedAuthority> authorities = (List<GrantedAuthority>) authentication.getAuthorities(); verify(mockUserDao).findByUsernameOrEmail("test@swiftapp.com"); verify(mockCrowdmapIDClient).signIn("test@swiftapp.com", "pa55w0rd"); assertEquals(1, authorities.size()); assertEquals("ROLE_USER", authorities.get(0).getAuthority()); }
From source file:com.springsource.hq.plugin.tcserver.serverconfig.web.support.HqAuthenticationFilter.java
/** * This takes an existing Authentication object, and converts it into an tc Server plugin-based object. * //from www . java2s .co m * @param auth * @param sessionId * @return */ private UsernamePasswordAuthenticationToken createHqAuthenticationToken(Authentication auth, String sessionId) { List<GrantedAuthority> auths = new ArrayList<GrantedAuthority>(); auths.addAll(auth.getAuthorities()); auths.add(new GrantedAuthorityImpl(defaultRole)); UsernamePasswordAuthenticationToken newToken = new HqAuthenticationToken(auth.getPrincipal(), auth.getCredentials(), auths, sessionId); return newToken; }
From source file:de.thm.arsnova.security.CustomBindAuthenticator.java
public DirContextOperations authenticate(Authentication authentication) { DirContextOperations user = null;// w w w . ja va 2 s . c o m Assert.isInstanceOf(UsernamePasswordAuthenticationToken.class, authentication, "Can only process UsernamePasswordAuthenticationToken objects"); String username = authentication.getName(); String password = (String) authentication.getCredentials(); if (!StringUtils.hasLength(password)) { logger.debug("Rejecting empty password for user " + username); throw new BadCredentialsException( messages.getMessage("BindAuthenticator.emptyPassword", "Empty Password")); } // If DN patterns are configured, try authenticating with them directly for (String dn : getUserDns(username)) { user = bindWithDn(dn, username, password); if (user != null) { break; } } // Otherwise use the configured search object to find the user and authenticate // with the returned DN. if (user == null && getUserSearch() != null) { DirContextOperations userFromSearch = getUserSearch().searchForUser(username); user = bindWithDn(userFromSearch.getDn().toString(), username, password); } if (user == null) { throw new BadCredentialsException( messages.getMessage("BindAuthenticator.badCredentials", "Bad credentials")); } return user; }
From source file:com.alliander.osgp.shared.security.CustomAuthenticationManager.java
/** * The login function. Use an Authentication instance with the principal set * to the user name and the credentials set to the password. Authentication * will be granted if the user is permitted for an/this application, the * user name is registered and the password matches. * * @param authentication/*from w w w . j a va 2 s .co m*/ * An Authentication instance containing user name and password. * * @return An CustomAuthentication instance containing user name, users * organisation identification, platform domains, user role, user * applications and an authentication token. */ @Override public Authentication authenticate(final Authentication authentication) { // Check if user has authentication instance. this.checkAuthenticationInstance(authentication); // Get user name and password. final String username = authentication.getName(); final String password = (String) authentication.getCredentials(); // Check user name and password. this.checkUsernameAndPasswordForEmptiness(username, password); // Prepare LoginRequest and LoginResponse. final LoginRequest loginRequest = new LoginRequest(username, password, this.application); LoginResponse loginResponse = null; // Try to login. try { loginResponse = this.authenticationClient.login(loginRequest); } catch (final Exception e) { LOGGER.debug(LOGIN_ATTEMPT_FAILED, e); throw new BadCredentialsException(LOGIN_ATTEMPT_FAILED, e); } // Check the response. this.checkLoginResponse(loginResponse); // Create the CustomAuthentication instance. return this.createCustomAuthenticationInstance(username, password, loginResponse); }
From source file:sk.lazyman.gizmo.security.SimpleBindAunthenticator.java
@Override public DirContextOperations authenticate(Authentication authentication) { DirContextOperations user = null;/* www . j a va 2 s.c o m*/ Assert.isInstanceOf(UsernamePasswordAuthenticationToken.class, authentication, "Can only process UsernamePasswordAuthenticationToken objects"); String username = authentication.getName(); String password = (String) authentication.getCredentials(); if (StringUtils.isEmpty(password)) { LOG.debug("Rejecting empty password for user " + username); throw new BadCredentialsException( messages.getMessage("BindAuthenticator.emptyPassword", "Empty Password")); } // If DN patterns are configured, try authenticating with them directly for (String dn : getUserDns(username)) { user = bindWithDn(dn, username, password); if (user != null) { break; } } // Otherwise use the configured search object to find the user and authenticate with the returned DN. if (user == null && getUserSearch() != null) { DirContextOperations userFromSearch = getUserSearch().searchForUser(username); user = bindWithDn(userFromSearch.getDn().toString(), username, password); } try { if (user != null && StringUtils.isNotEmpty(gizmoGroup)) { BaseLdapPathContextSource ctxSource = (BaseLdapPathContextSource) getContextSource(); DirContext ctx = ctxSource.getReadOnlyContext(); DistinguishedName userDn = new DistinguishedName(user.getDn()); userDn.prepend(ctxSource.getBaseLdapPath()); SearchControls controls = new SearchControls(); controls.setSearchScope(SearchControls.SUBTREE_SCOPE); String filter = String.format(GROUP_SEARCH_QUERY, gizmoGroup, userDn.toCompactString()); NamingEnumeration en = ctx.search("", filter, controls); if (!en.hasMore()) { throw new BadCredentialsException( messages.getMessage("BindAuthenticator.badCredentials", "Bad credentials")); } } } catch (javax.naming.NamingException ex) { throw new BadCredentialsException("Couldn't check group membership"); } if (user == null) { throw new BadCredentialsException( messages.getMessage("BindAuthenticator.badCredentials", "Bad credentials")); } return user; }