use of org.springframework.security.authentication.BadCredentialsException in project spring-security-oauth by spring-projects.
the class TokenEndpointAuthenticationFilter method doFilter.
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
final boolean debug = logger.isDebugEnabled();
final HttpServletRequest request = (HttpServletRequest) req;
final HttpServletResponse response = (HttpServletResponse) res;
try {
Authentication credentials = extractCredentials(request);
if (credentials != null) {
if (debug) {
logger.debug("Authentication credentials found for '" + credentials.getName() + "'");
}
Authentication authResult = authenticationManager.authenticate(credentials);
if (debug) {
logger.debug("Authentication success: " + authResult.getName());
}
Authentication clientAuth = SecurityContextHolder.getContext().getAuthentication();
if (clientAuth == null) {
throw new BadCredentialsException("No client authentication found. Remember to put a filter upstream of the TokenEndpointAuthenticationFilter.");
}
Map<String, String> map = getSingleValueMap(request);
map.put(OAuth2Utils.CLIENT_ID, clientAuth.getName());
AuthorizationRequest authorizationRequest = oAuth2RequestFactory.createAuthorizationRequest(map);
authorizationRequest.setScope(getScope(request));
if (clientAuth.isAuthenticated()) {
// Ensure the OAuth2Authentication is authenticated
authorizationRequest.setApproved(true);
}
OAuth2Request storedOAuth2Request = oAuth2RequestFactory.createOAuth2Request(authorizationRequest);
SecurityContextHolder.getContext().setAuthentication(new OAuth2Authentication(storedOAuth2Request, authResult));
onSuccessfulAuthentication(request, response, authResult);
}
} catch (AuthenticationException failed) {
SecurityContextHolder.clearContext();
if (debug) {
logger.debug("Authentication request for failed: " + failed);
}
onUnsuccessfulAuthentication(request, response, failed);
authenticationEntryPoint.commence(request, response, failed);
return;
}
chain.doFilter(request, response);
}
use of org.springframework.security.authentication.BadCredentialsException in project ranger by apache.
the class PasswordComparisonAuthenticator method authenticate.
// ~ Methods
// ========================================================================================================
public DirContextOperations authenticate(final Authentication authentication) {
Assert.isInstanceOf(UsernamePasswordAuthenticationToken.class, authentication, "Can only process UsernamePasswordAuthenticationToken objects");
// locate the user and check the password
DirContextOperations user = null;
String username = authentication.getName();
String password = (String) authentication.getCredentials();
Iterator dns = getUserDns(username).iterator();
SpringSecurityLdapTemplate ldapTemplate = new SpringSecurityLdapTemplate(getContextSource());
while (dns.hasNext() && user == null) {
final String userDn = (String) dns.next();
try {
user = ldapTemplate.retrieveEntry(userDn, getUserAttributes());
} catch (NameNotFoundException ignore) {
}
}
if (user == null && getUserSearch() != null) {
user = getUserSearch().searchForUser(username);
}
if (user == null) {
throw new UsernameNotFoundException("User not found: " + username);
}
if (logger.isDebugEnabled()) {
logger.debug("Performing LDAP compare of password attribute '" + passwordAttributeName + "' for user '" + user.getDn() + "'");
}
String encodedPassword = passwordEncoder.encodePassword(password, null);
byte[] passwordBytes = encodedPassword.getBytes();
if (!ldapTemplate.compare(user.getDn().toString(), passwordAttributeName, passwordBytes)) {
throw new BadCredentialsException(messages.getMessage("PasswordComparisonAuthenticator.badCredentials", "Bad credentials"));
}
return user;
}
use of org.springframework.security.authentication.BadCredentialsException in project ranger by apache.
the class AuthenticationCheck method getADBindAuthentication.
private Authentication getADBindAuthentication(String ldapUrl, String bindDn, String bindPassword, String userName, String userPassword) {
Authentication result = null;
try {
LdapContextSource ldapContextSource = new DefaultSpringSecurityContextSource(ldapUrl);
ldapContextSource.setUserDn(bindDn);
ldapContextSource.setPassword(bindPassword);
ldapContextSource.setReferral("follow");
ldapContextSource.setCacheEnvironmentProperties(true);
ldapContextSource.setAnonymousReadOnly(false);
ldapContextSource.setPooled(true);
ldapContextSource.afterPropertiesSet();
String searchFilter = "(sAMAccountName={0})";
FilterBasedLdapUserSearch userSearch = new FilterBasedLdapUserSearch(adDomain, searchFilter, ldapContextSource);
userSearch.setSearchSubtree(true);
BindAuthenticator bindAuthenticator = new BindAuthenticator(ldapContextSource);
bindAuthenticator.setUserSearch(userSearch);
bindAuthenticator.afterPropertiesSet();
LdapAuthenticationProvider ldapAuthenticationProvider = new LdapAuthenticationProvider(bindAuthenticator);
if (userName != null && userPassword != null && !userName.trim().isEmpty() && !userPassword.trim().isEmpty()) {
final List<GrantedAuthority> grantedAuths = new ArrayList<>();
grantedAuths.add(new SimpleGrantedAuthority("ROLE_USER"));
final UserDetails principal = new User(userName, userPassword, grantedAuths);
final Authentication finalAuthentication = new UsernamePasswordAuthenticationToken(principal, userPassword, grantedAuths);
result = ldapAuthenticationProvider.authenticate(finalAuthentication);
}
} catch (BadCredentialsException bce) {
logFile.println("ERROR: LDAP Authentication Failed. Please verify values for ranger.admin.auth.sampleuser and " + "ranger.admin.auth.samplepassword\n");
} catch (Exception e) {
logFile.println("ERROR: LDAP Authentication Failed: " + e);
}
return result;
}
use of org.springframework.security.authentication.BadCredentialsException in project ranger by apache.
the class AuthenticationCheck method getLdapBindAuthentication.
private Authentication getLdapBindAuthentication(String ldapUrl, String bindDn, String bindPassword, String userName, String userPassword) {
Authentication result = null;
try {
LdapContextSource ldapContextSource = new DefaultSpringSecurityContextSource(ldapUrl);
ldapContextSource.setUserDn(bindDn);
ldapContextSource.setPassword(bindPassword);
ldapContextSource.setReferral("follow");
ldapContextSource.setCacheEnvironmentProperties(false);
ldapContextSource.setAnonymousReadOnly(true);
ldapContextSource.setPooled(true);
ldapContextSource.afterPropertiesSet();
DefaultLdapAuthoritiesPopulator defaultLdapAuthoritiesPopulator = new DefaultLdapAuthoritiesPopulator(ldapContextSource, groupSearchBase);
defaultLdapAuthoritiesPopulator.setGroupRoleAttribute(roleAttribute);
defaultLdapAuthoritiesPopulator.setGroupSearchFilter(groupSearchFilter);
defaultLdapAuthoritiesPopulator.setIgnorePartialResultException(true);
String searchFilter = "(uid={0})";
FilterBasedLdapUserSearch userSearch = new FilterBasedLdapUserSearch(adDomain, searchFilter, ldapContextSource);
userSearch.setSearchSubtree(true);
BindAuthenticator bindAuthenticator = new BindAuthenticator(ldapContextSource);
bindAuthenticator.setUserSearch(userSearch);
String[] userDnPatterns = new String[] { userDnPattern };
bindAuthenticator.setUserDnPatterns(userDnPatterns);
bindAuthenticator.afterPropertiesSet();
LdapAuthenticationProvider ldapAuthenticationProvider = new LdapAuthenticationProvider(bindAuthenticator, defaultLdapAuthoritiesPopulator);
if (userName != null && userPassword != null && !userName.trim().isEmpty() && !userPassword.trim().isEmpty()) {
final List<GrantedAuthority> grantedAuths = new ArrayList<>();
grantedAuths.add(new SimpleGrantedAuthority("ROLE_USER"));
final UserDetails principal = new User(userName, userPassword, grantedAuths);
final Authentication finalAuthentication = new UsernamePasswordAuthenticationToken(principal, userPassword, grantedAuths);
result = ldapAuthenticationProvider.authenticate(finalAuthentication);
}
} catch (BadCredentialsException bce) {
logFile.println("ERROR: LDAP Authentication Failed. Please verify values for ranger.admin.auth.sampleuser and " + "ranger.admin.auth.samplepassword\n");
} catch (Exception e) {
logFile.println("ERROR: LDAP Authentication Failed: " + e);
}
return result;
}
use of org.springframework.security.authentication.BadCredentialsException in project webofneeds by researchstudio-sat.
the class LinkedDataWebController method register.
@RequestMapping(value = "${uri.path.resource}", method = RequestMethod.POST, produces = { "text/plain" })
public ResponseEntity<String> register(@RequestParam("register") String registeredType, HttpServletRequest request) throws CertificateException, UnsupportedEncodingException {
logger.debug("REGISTERING " + registeredType);
PreAuthenticatedAuthenticationToken authentication = (PreAuthenticatedAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
if (!(authentication instanceof PreAuthenticatedAuthenticationToken)) {
throw new BadCredentialsException("Could not register: PreAuthenticatedAuthenticationToken expected");
}
// Object principal = authentication.getPrincipal();
Object credentials = authentication.getCredentials();
X509Certificate cert;
if (credentials instanceof X509Certificate) {
cert = (X509Certificate) credentials;
} else {
throw new BadCredentialsException("Could not register: expected to find a X509Certificate in the request");
}
try {
if ("owner".equals(registeredType)) {
String result = registrationServer.registerOwner(cert);
logger.debug("successfully registered owner");
return new ResponseEntity<>(result, HttpStatus.OK);
}
if ("node".equals(registeredType)) {
String result = registrationServer.registerNode(cert);
logger.debug("successfully registered node");
return new ResponseEntity<>(result, HttpStatus.OK);
} else {
String supportedTypesMsg = "Request parameter error; supported 'register' parameter values: 'owner', 'node'";
logger.debug(supportedTypesMsg);
return new ResponseEntity<>(supportedTypesMsg, HttpStatus.BAD_REQUEST);
}
} catch (WonProtocolException e) {
logger.info("Could not register " + registeredType, e);
return new ResponseEntity<>(e.getMessage(), HttpStatus.BAD_REQUEST);
}
}
Aggregations