public Authentication authenticate(Authentication authentication) throws AuthenticationException { Assert.isInstanceOf(UsernamePasswordAuthenticationToken.class, authentication, () -> this.messages.getMessage("LdapAuthenticationProvider.onlySupports", "Only UsernamePasswordAuthenticationToken is supported")); final UsernamePasswordAuthenticationToken userToken = (UsernamePasswordAuthenticationToken) authentication; String username = userToken.getName(); String password = (String) authentication.getCredentials(); if (this.logger.isDebugEnabled()) { this.logger.debug("Processing authentication request for user: " + username); } if (!StringUtils.hasLength(username)) { throw new BadCredentialsException(this.messages.getMessage( "LdapAuthenticationProvider.emptyUsername", "Empty Username")); } if (!StringUtils.hasLength(password)) { throw new BadCredentialsException(this.messages.getMessage( "AbstractLdapAuthenticationProvider.emptyPassword", "Empty Password")); } Assert.notNull(password, "Null password was supplied in authentication token"); DirContextOperations userData = doAuthentication(userToken); UserDetails user = this.userDetailsContextMapper.mapUserFromContext(userData, authentication.getName(), loadUserAuthorities(userData, authentication.getName(), (String) authentication.getCredentials())); return createSuccessfulAuthentication(userToken, user); }
@Override protected DirContextOperations doAuthentication( UsernamePasswordAuthenticationToken auth) { String username = auth.getName(); String password = (String) auth.getCredentials(); DirContext ctx = bindAsUser(username, password); try { 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); } }
@Test public void getAuthenticationWhenAuthenticationManagerBeanThenAuthenticates() throws Exception { UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("user", "password"); this.spring.register(AuthenticationConfiguration.class, ObjectPostProcessorConfiguration.class, AuthenticationManagerBeanConfig.class).autowire(); AuthenticationManager authentication = this.spring.getContext().getBean(AuthenticationConfiguration.class).getAuthenticationManager(); when(authentication.authenticate(token)).thenReturn(TestAuthentication.authenticatedUser()); assertThat(authentication.authenticate(token).getName()).isEqualTo(token.getName()); }
@Test public void getAuthenticationWhenGlobalAuthenticationConfigurerAdapterThenAuthenticates() throws Exception { UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("user", "password"); this.spring.register(AuthenticationConfiguration.class, ObjectPostProcessorConfiguration.class, UserGlobalAuthenticationConfigurerAdapter.class).autowire(); AuthenticationManager authentication = this.spring.getContext().getBean(AuthenticationConfiguration.class).getAuthenticationManager(); assertThat(authentication.authenticate(token).getName()).isEqualTo(token.getName()); }
@Override public final AuthenticationResponse authenticate(final LoginCredentials credentials) throws InvalidLoginCredentialsException, IdentityAccessException { if (provider == null) { throw new IdentityAccessException("The Kerberos authentication provider is not initialized."); } try { // Perform the authentication final UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(credentials.getUsername(), credentials.getPassword()); logger.debug("Created authentication token for principal {} with name {} and is authenticated {}", token.getPrincipal(), token.getName(), token.isAuthenticated()); final Authentication authentication = provider.authenticate(token); logger.debug("Ran provider.authenticate() and returned authentication for " + "principal {} with name {} and is authenticated {}", authentication.getPrincipal(), authentication.getName(), authentication.isAuthenticated()); return new AuthenticationResponse(authentication.getName(), credentials.getUsername(), expiration, issuer); } catch (final AuthenticationException e) { throw new InvalidLoginCredentialsException(e.getMessage(), e); } }
@Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) authentication; try { //Do authentication //Delete previous tokens Collection<OAuth2AccessToken> tokenCollection = tokenStore.findTokensByUserName(token.getName()); for (OAuth2AccessToken oToken : tokenCollection){ tokenStore.removeAccessToken(oToken); } //return Authentication; } }
@RequestMapping(value = "/userAndSession/{providedSessionId}", method = RequestMethod.GET) public String getUserAndSessionId(UsernamePasswordAuthenticationToken principal, HttpServletRequest httpServletRequest, @PathVariable("providedSessionId") String sessionID) { // Session ID String sessionId = httpServletRequest.getRequestedSessionId(); if(sessionId.equals(providedSessionId)) { // Username String name = principal.getName(); } }
public class CustomAuthenticationProvider implements AuthenticationProvider{ private UserDetailsService service; @Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) authentication; String username = token.getName(); String password = token.getCredentials(); // retrieve the password // do something here // if ok then return the authentication return new UsernamePasswordAuthenticationToken(username, password, authorities); } }
@Override public void handleRequestStart(ItcbVaadinApplication application, HttpServletRequest servletRequest) { if(application.getUser() != null) { MDC.put(ItcbConstants.MDC_USER_KEY, ((UsernamePasswordAuthenticationToken)application.getUser()).getName()); } else { MDC.put(ItcbConstants.MDC_USER_KEY, ""); } }
public class LdapAndDatabaseAuthenticationProvider extends LdapAuthenticationProvider{ public LdapAndDatabaseAuthenticationProvider(LdapAuthenticator authenticator, LdapAuthoritiesPopulator authoritiesPopulator) { super(authenticator, authoritiesPopulator); } @Override protected DirContextOperations doAuthentication( UsernamePasswordAuthenticationToken authentication) { log.debug("Checking if user <{}> is defined at database to use this application.", authentication.getName()); // Here is the part we need to check in the database if user has required role to log into the application. // After check if user has the role, do nothing, otherwise throw exception like below example. boolean canUserAuthenticate = isActiveUserExist(authentication.getName()); log.debug("canUserAuthenticate: {}", canUserAuthenticate); if (!canUserAuthenticate) throw new DisabledException("User does not have access to Application!"); return super.doAuthentication(authentication); } private boolean isActiveUserExist(String userId) { // Do your logic here are return boolean value... }
@Override public void handleRequestStart(ItcbVaadinApplication application, PortletRequest portletRequest) { if(application.getUser() != null) { MDC.put(ItcbConstants.MDC_USER_KEY, ((UsernamePasswordAuthenticationToken)application.getUser()).getName()); } else { MDC.put(ItcbConstants.MDC_USER_KEY, ""); } }
@GetMapping("/paver/v1/userinfo") public Map<String, Object> home(Principal user) { UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) user; return ImmutableMap .<String, Object> builder() .put("username", token.getName()) .put("authorities", token.getAuthorities().stream().map(GrantedAuthority::getAuthority).collect(toList())) .build(); } }
@Override protected DirContextOperations doAuthentication(UsernamePasswordAuthenticationToken authentication) { try { return super.doAuthentication(authentication); } catch (InternalAuthenticationServiceException e) { // This sometimes happens ... for unknown reasons the underlying libraries cannot // figure out correct exception. Which results to wrong error message (MID-4518) // So, be smart here and try to figure out correct error. throw processInternalAuthenticationException(e, e); } catch (IncorrectResultSizeDataAccessException e) { LOGGER.error("Failed to authenticate user {}. Error: {}", authentication.getName(), e.getMessage(), e); throw new BadCredentialsException("LdapAuthentication.bad.user", e); } catch (RuntimeException e) { LOGGER.error("Failed to authenticate user {}. Error: {}", authentication.getName(), e.getMessage(), e); auditProvider.auditLoginFailure(authentication.getName(), null, ConnectionEnvironment.create(SchemaConstants.CHANNEL_GUI_USER_URI), "bad credentials"); throw e; } }
@Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { UsernamePasswordAuthenticationToken userToken = (UsernamePasswordAuthenticationToken)authentication; String username = userToken.getName(); String password = (String) authentication.getCredentials(); //Do whatevr you want with the credentials //Then populate the authorities for this credential YourPojo user=new YourPojo (); user.setUserName("add username"); //set other details List<GrantedAuthority> grantedAuthorityList = new ArrayList<GrantedAuthority>(); //if user is admin add the below line GrantedAuthorityImpl grantedAuthorityImpl = new GrantedAuthorityImpl("eCommerceAdmin"); //Add other authorities as applicable like 'user' etc. user.setAuthorities(grantedAuthorityList); return new UsernamePasswordAuthenticationToken(username, password, user.getAuthorities());
@Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { UsernamePasswordAuthenticationToken auth = (UsernamePasswordAuthenticationToken) authentication; /* * The incoming username will be in the form of a Kerberos user principal name, * e.g. user@EXAMPLE.ORG. We typically need to strip off the realm name before * doing any LDAP operations with the username. */ String validatedUsername = trimRealmFromUsername(m_kerberosClient.login(auth.getName(), auth.getCredentials().toString())); DirContextOperations ldapUserEntry = m_ldapUserSearch.searchForUser(validatedUsername); Collection<? extends GrantedAuthority> grantedAuthorities = m_ldapAuthoritiesPopulator.getGrantedAuthorities(ldapUserEntry, validatedUsername); UserDetails userDetails = new User(validatedUsername, "notUsed", true, true, true, true, grantedAuthorities); UsernamePasswordAuthenticationToken output = new UsernamePasswordAuthenticationToken(userDetails, auth.getCredentials(), grantedAuthorities); return output; }
@Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { UsernamePasswordAuthenticationToken auth = (UsernamePasswordAuthenticationToken) authentication; String validatedUsername = kerberosClient.login(auth.getName(), auth.getCredentials().toString()); UserDetails userDetails = this.userDetailsService.loadUserByUsername(validatedUsername); UsernamePasswordAuthenticationToken output = new UsernamePasswordAuthenticationToken(userDetails, auth.getCredentials(), userDetails.getAuthorities()); output.setDetails(authentication.getDetails()); return output; }
@Override public final AuthenticationResponse authenticate(final LoginCredentials credentials) throws InvalidLoginCredentialsException, IdentityAccessException { if (provider == null) { throw new IdentityAccessException("The Kerberos authentication provider is not initialized."); } try { // Perform the authentication final UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(credentials.getUsername(), credentials.getPassword()); logger.debug("Created authentication token for principal {} with name {} and is authenticated {}", token.getPrincipal(), token.getName(), token.isAuthenticated()); final Authentication authentication = provider.authenticate(token); logger.debug("Ran provider.authenticate() and returned authentication for " + "principal {} with name {} and is authenticated {}", authentication.getPrincipal(), authentication.getName(), authentication.isAuthenticated()); return new AuthenticationResponse(authentication.getName(), credentials.getUsername(), expiration, issuer); } catch (final AuthenticationException e) { throw new InvalidLoginCredentialsException(e.getMessage(), e); } }
@Override protected DirContextOperations doAuthentication( UsernamePasswordAuthenticationToken auth) { String username = auth.getName(); String password = (String) auth.getCredentials(); DirContext ctx = bindAsUser(username, password); try { 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); } }
@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()); } 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; }
@Override public Authentication authenticate(final Authentication authentication) { final UsernamePasswordAuthenticationToken auth = (UsernamePasswordAuthenticationToken) authentication; IWindowsIdentity windowsIdentity; try { windowsIdentity = this.authProvider.logonUser(auth.getName(), auth.getCredentials().toString()); } catch (final Win32Exception e) { throw new AuthenticationServiceException(e.getMessage(), e); } 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()); } 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; }