List of usage examples for org.springframework.security.authentication BadCredentialsException BadCredentialsException
public BadCredentialsException(String msg)
BadCredentialsException
with the specified message. From source file:org.apache.syncope.core.spring.security.SyncopeAuthenticationProvider.java
@Override public Authentication authenticate(final Authentication authentication) { String domainKey = SyncopeAuthenticationDetails.class.cast(authentication.getDetails()).getDomain(); if (StringUtils.isBlank(domainKey)) { domainKey = SyncopeConstants.MASTER_DOMAIN; }// w ww .ja v a 2 s . c o m SyncopeAuthenticationDetails.class.cast(authentication.getDetails()).setDomain(domainKey); Boolean authenticated; if (anonymousUser.equals(authentication.getName())) { authenticated = authentication.getCredentials().toString().equals(anonymousKey); } else if (adminUser.equals(authentication.getName())) { if (SyncopeConstants.MASTER_DOMAIN.equals(domainKey)) { authenticated = encryptor.verify(authentication.getCredentials().toString(), CipherAlgorithm.valueOf(adminPasswordAlgorithm), adminPassword); } else { final String domainToFind = domainKey; authenticated = AuthContextUtils.execWithAuthContext(SyncopeConstants.MASTER_DOMAIN, new Executable<Boolean>() { @Override public Boolean exec() { Domain domain = dataAccessor.findDomain(domainToFind); return encryptor.verify(authentication.getCredentials().toString(), domain.getAdminCipherAlgorithm(), domain.getAdminPwd()); } }); } } else { final Pair<String, Boolean> authResult = AuthContextUtils.execWithAuthContext(domainKey, new Executable<Pair<String, Boolean>>() { @Override public Pair<String, Boolean> exec() { return dataAccessor.authenticate(authentication); } }); authenticated = authResult.getValue(); if (authenticated != null && !authenticated) { AuthContextUtils.execWithAuthContext(domainKey, new Executable<Void>() { @Override public Void exec() { provisioningManager.internalSuspend(authResult.getKey()); return null; } }); } } final boolean isAuthenticated = authenticated != null && authenticated; UsernamePasswordAuthenticationToken token; if (isAuthenticated) { token = AuthContextUtils.execWithAuthContext(domainKey, new Executable<UsernamePasswordAuthenticationToken>() { @Override public UsernamePasswordAuthenticationToken exec() { UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken( authentication.getPrincipal(), null, userDetailsService.loadUserByUsername(authentication.getPrincipal().toString()) .getAuthorities()); token.setDetails(authentication.getDetails()); dataAccessor.audit(AuditElements.EventCategoryType.LOGIC, AuditElements.AUTHENTICATION_CATEGORY, null, AuditElements.LOGIN_EVENT, Result.SUCCESS, null, isAuthenticated, authentication, "Successfully authenticated, with entitlements: " + token.getAuthorities()); return token; } }); LOG.debug("User {} successfully authenticated, with entitlements {}", authentication.getPrincipal(), token.getAuthorities()); } else { AuthContextUtils.execWithAuthContext(domainKey, new Executable<Void>() { @Override public Void exec() { dataAccessor.audit(AuditElements.EventCategoryType.LOGIC, AuditElements.AUTHENTICATION_CATEGORY, null, AuditElements.LOGIN_EVENT, Result.FAILURE, null, isAuthenticated, authentication, "User " + authentication.getPrincipal() + " not authenticated"); return null; } }); LOG.debug("User {} not authenticated", authentication.getPrincipal()); throw new BadCredentialsException("User " + authentication.getPrincipal() + " not authenticated"); } return token; }
From source file:org.apache.syncope.core.spring.security.UsernamePasswordAuthenticationProvider.java
@Override public Authentication authenticate(final Authentication authentication) { String domainKey = SyncopeAuthenticationDetails.class.cast(authentication.getDetails()).getDomain(); final String[] username = new String[1]; Boolean authenticated;//from w ww.j a v a2 s.c o m if (anonymousUser.equals(authentication.getName())) { username[0] = anonymousUser; credentialChecker.checkIsDefaultAnonymousKeyInUse(); authenticated = authentication.getCredentials().toString().equals(anonymousKey); } else if (adminUser.equals(authentication.getName())) { username[0] = adminUser; if (SyncopeConstants.MASTER_DOMAIN.equals(domainKey)) { credentialChecker.checkIsDefaultAdminPasswordInUse(); authenticated = ENCRYPTOR.verify(authentication.getCredentials().toString(), CipherAlgorithm.valueOf(adminPasswordAlgorithm), adminPassword); } else { final String domainToFind = domainKey; authenticated = AuthContextUtils.execWithAuthContext(SyncopeConstants.MASTER_DOMAIN, () -> { Domain domain = dataAccessor.findDomain(domainToFind); return ENCRYPTOR.verify(authentication.getCredentials().toString(), domain.getAdminCipherAlgorithm(), domain.getAdminPwd()); }); } } else { final Pair<User, Boolean> authResult = AuthContextUtils.execWithAuthContext(domainKey, () -> dataAccessor.authenticate(authentication)); authenticated = authResult.getValue(); if (authResult.getLeft() != null && authResult.getRight() != null) { username[0] = authResult.getLeft().getUsername(); if (!authResult.getRight()) { AuthContextUtils.execWithAuthContext(domainKey, () -> { provisioningManager.internalSuspend(authResult.getLeft().getKey()); return null; }); } } } if (username[0] == null) { username[0] = authentication.getPrincipal().toString(); } final boolean isAuthenticated = authenticated != null && authenticated; UsernamePasswordAuthenticationToken token; if (isAuthenticated) { token = AuthContextUtils.execWithAuthContext(domainKey, () -> { UsernamePasswordAuthenticationToken token1 = new UsernamePasswordAuthenticationToken(username[0], null, dataAccessor.getAuthorities(username[0])); token1.setDetails(authentication.getDetails()); dataAccessor.audit(AuditElements.EventCategoryType.LOGIC, AuditElements.AUTHENTICATION_CATEGORY, null, AuditElements.LOGIN_EVENT, Result.SUCCESS, null, isAuthenticated, authentication, "Successfully authenticated, with entitlements: " + token1.getAuthorities()); return token1; }); LOG.debug("User {} successfully authenticated, with entitlements {}", username[0], token.getAuthorities()); } else { AuthContextUtils.execWithAuthContext(domainKey, () -> { dataAccessor.audit(AuditElements.EventCategoryType.LOGIC, AuditElements.AUTHENTICATION_CATEGORY, null, AuditElements.LOGIN_EVENT, Result.FAILURE, null, isAuthenticated, authentication, "User " + username[0] + " not authenticated"); return null; }); LOG.debug("User {} not authenticated", username[0]); throw new BadCredentialsException("User " + username[0] + " not authenticated"); } return token; }
From source file:org.apereo.portal.soffit.security.SoffitApiAuthenticationManager.java
@Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { logger.debug("Authenticating the following Authentication object: {}", authentication); if (!SoffitApiUserDetails.class.isInstance(authentication.getPrincipal())) { throw new BadCredentialsException("Unrecognized principal type"); }/*from www .j a v a 2s . c om*/ final SoffitApiUserDetails saud = (SoffitApiUserDetails) authentication.getPrincipal(); if (StringUtils.isBlank(saud.getUsername())) { throw new BadCredentialsException("Missing username"); } return new UsernamePasswordAuthenticationToken(saud.getUsername(), authentication.getCredentials(), saud.getAuthorities()); }
From source file:org.cloudfoundry.identity.uaa.account.PasswordChangeEndpoint.java
@ExceptionHandler public View handleException(ScimResourceNotFoundException e) { // There's no point throwing BadCredentialsException here because it is // caught and // logged (then ignored) by the caller. return new ConvertingExceptionView(new ResponseEntity<>( new ExceptionReport(new BadCredentialsException("Invalid password change request"), false), HttpStatus.UNAUTHORIZED), messageConverters); }
From source file:org.cloudfoundry.identity.uaa.account.PasswordChangeEndpoint.java
@ExceptionHandler(ScimException.class) public View handleException(ScimException e) { // No need to log the underlying exception (it will be logged by the // caller)//www.j a v a 2s . c o m return makeConvertingExceptionView(new BadCredentialsException("Invalid password change request"), e.getStatus()); }
From source file:org.cloudfoundry.identity.uaa.authentication.AbstractClientParametersAuthenticationFilter.java
private Authentication performClientAuthentication(HttpServletRequest req, Map<String, String> loginInfo, String clientId) {//from ww w .ja v a 2 s. c o m if (clientId != null) { Result policyResult = loginPolicy.isAllowed(clientId); if (!policyResult.isAllowed()) { throw new ClientLockoutException("Client " + clientId + " has " + policyResult.getFailureCount() + " failed authentications within the last checking period."); } } String clientSecret = loginInfo.get(CLIENT_SECRET); UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(clientId, clientSecret); authentication.setDetails(new UaaAuthenticationDetails(req, clientId)); try { Authentication auth = clientAuthenticationManager.authenticate(authentication); if (auth == null || !auth.isAuthenticated()) { throw new BadCredentialsException("Client Authentication failed."); } loginInfo.remove(CLIENT_SECRET); AuthorizationRequest authorizationRequest = new AuthorizationRequest(clientId, getScope(req)); authorizationRequest.setRequestParameters(getSingleValueMap(req)); authorizationRequest.setApproved(true); //must set this to true in order for //Authentication.isAuthenticated to return true OAuth2Authentication result = new OAuth2Authentication(authorizationRequest.createOAuth2Request(), null); result.setAuthenticated(true); return result; } catch (AuthenticationException e) { throw new BadCredentialsException(e.getMessage(), e); } catch (Exception e) { logger.debug("Unable to authenticate client: " + clientId, e); throw new BadCredentialsException(e.getMessage(), e); } }
From source file:org.cloudfoundry.identity.uaa.authentication.AuthzAuthenticationFilter.java
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest req = (HttpServletRequest) request; HttpServletResponse res = (HttpServletResponse) response; Map<String, String> loginInfo = getCredentials(req); boolean buggyVmcAcceptHeader = false; try {// w ww . j a v a 2s. c om if (loginInfo.isEmpty()) { throw new BadCredentialsException("Request does not contain credentials."); } else { logger.debug("Located credentials in request, with keys: " + loginInfo.keySet()); if (methods != null && !methods.contains(req.getMethod().toUpperCase())) { throw new BadCredentialsException("Credentials must be sent by (one of methods): " + methods); } Authentication result = authenticationManager .authenticate(new AuthzAuthenticationRequest(loginInfo, new UaaAuthenticationDetails(req))); SecurityContextHolder.getContext().setAuthentication(result); ofNullable(successHandler).ifPresent(s -> s.setSavedAccountOptionCookie(req, res, result)); } } catch (AuthenticationException e) { logger.debug("Authentication failed"); String acceptHeaderValue = req.getHeader("accept"); String clientId = req.getParameter("client_id"); if ("*/*; q=0.5, application/xml".equals(acceptHeaderValue) && "vmc".equals(clientId)) { buggyVmcAcceptHeader = true; } if (buggyVmcAcceptHeader) { HttpServletRequest jsonAcceptingRequest = new HttpServletRequestWrapper(req) { @SuppressWarnings("unchecked") @Override public Enumeration<String> getHeaders(String name) { if ("accept".equalsIgnoreCase(name)) { return new JsonInjectedEnumeration( ((HttpServletRequest) getRequest()).getHeaders(name)); } else { return ((HttpServletRequest) getRequest()).getHeaders(name); } } @Override public String getHeader(String name) { if (name.equalsIgnoreCase("accept")) { return "application/json"; } else { return ((HttpServletRequest) getRequest()).getHeader(name); } } }; authenticationEntryPoint.commence(jsonAcceptingRequest, res, e); } else { authenticationEntryPoint.commence(req, res, e); } return; } chain.doFilter(request, response); }
From source file:org.cloudfoundry.identity.uaa.authentication.BackwardsCompatibleTokenEndpointAuthenticationFilter.java
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { final HttpServletRequest request = (HttpServletRequest) req; final HttpServletResponse response = (HttpServletResponse) res; try {// ww w . jav a 2 s. c o m Authentication userAuthentication = extractCredentials(request, response); if (userAuthentication != null) { 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()); SecurityContextHolder.getContext().setAuthentication(userAuthentication); 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, userAuthentication)); onSuccessfulAuthentication(request, response, userAuthentication); } } catch (UnauthorizedClientException failed) { //happens when all went well, but the client is not authorized for the identity provider UnapprovedClientAuthenticationException ex = new UnapprovedClientAuthenticationException( failed.getMessage(), failed); SecurityContextHolder.clearContext(); logger.debug("Authentication request for failed: " + failed); onUnsuccessfulAuthentication(request, response, ex); authenticationEntryPoint.commence(request, response, ex); return; } catch (AuthenticationException failed) { SecurityContextHolder.clearContext(); logger.debug("Authentication request for failed: " + failed); onUnsuccessfulAuthentication(request, response, failed); authenticationEntryPoint.commence(request, response, failed); return; } catch (InvalidScopeException ex) { String message = ex.getMessage(); response.sendError(UNAUTHORIZED.value(), message); return; } chain.doFilter(request, response); }
From source file:org.cloudfoundry.identity.uaa.authentication.ClientParametersAuthenticationFilter.java
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest req = (HttpServletRequest) request; HttpServletResponse res = (HttpServletResponse) response; Map<String, String> loginInfo = getCredentials(req); String clientId = loginInfo.get(CLIENT_ID); try {//from w ww. jav a 2 s .c om if (loginInfo.isEmpty()) { throw new BadCredentialsException("Request does not contain credentials."); } else if (clientAuthenticationManager == null || loginInfo.get(CLIENT_ID) == null) { logger.debug("Insufficient resources to perform client authentication. AuthMgr:" + clientAuthenticationManager + "; clientId:" + clientId); throw new BadCredentialsException("Request does not contain client credentials."); } else { logger.debug("Located credentials in request, with keys: " + loginInfo.keySet()); Authentication clientAuth = performClientAuthentication(req, loginInfo, clientId); SecurityContextHolder.getContext().setAuthentication(clientAuth); } } catch (AuthenticationException e) { logger.debug("Client Parameter Authentication failed"); authenticationEntryPoint.commence(req, res, e); return; } chain.doFilter(request, response); }
From source file:org.cloudfoundry.identity.uaa.authentication.ClientParametersAuthenticationFilter.java
private Authentication performClientAuthentication(HttpServletRequest req, Map<String, String> loginInfo, String clientId) {/*from ww w .java2 s . co m*/ String clientSecret = loginInfo.get(CLIENT_SECRET); UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(clientId, clientSecret); authentication.setDetails(new UaaAuthenticationDetails(req, clientId)); try { Authentication auth = clientAuthenticationManager.authenticate(authentication); if (auth == null || !auth.isAuthenticated()) { throw new BadCredentialsException("Client Authentication failed."); } loginInfo.remove(CLIENT_SECRET); AuthorizationRequest authorizationRequest = new AuthorizationRequest(clientId, getScope(req)); authorizationRequest.setRequestParameters(getSingleValueMap(req)); authorizationRequest.setApproved(true); //must set this to true in order for //Authentication.isAuthenticated to return true OAuth2Authentication result = new OAuth2Authentication(authorizationRequest.createOAuth2Request(), null); result.setAuthenticated(true); return result; } catch (AuthenticationException e) { throw new BadCredentialsException(e.getMessage(), e); } catch (Exception e) { logger.debug("Unable to authenticate client: " + clientId, e); throw new BadCredentialsException(e.getMessage(), e); } }