@Override protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) { Map<String, String> parameters = new LinkedHashMap<String, String>(tokenRequest.getRequestParameters()); String username = parameters.get("username"); String password = parameters.get("password"); // Protect from downstream leaks of password parameters.remove("password"); Authentication userAuth = new UsernamePasswordAuthenticationToken(username, password); ((AbstractAuthenticationToken) userAuth).setDetails(parameters); try { userAuth = authenticationManager.authenticate(userAuth); } catch (AccountStatusException ase) { //covers expired, locked, disabled cases (mentioned in section 5.2, draft 31) throw new InvalidGrantException(ase.getMessage()); } catch (BadCredentialsException e) { // If the username/password are wrong the spec says we should send 400/invalid grant throw new InvalidGrantException(e.getMessage()); } if (userAuth == null || !userAuth.isAuthenticated()) { throw new InvalidGrantException("Could not authenticate user: " + username); } OAuth2Request storedOAuth2Request = getRequestFactory().createOAuth2Request(client, tokenRequest); return new OAuth2Authentication(storedOAuth2Request, userAuth); } }
@Test public void deserializeBadCredentialsExceptionMixinTest() throws IOException { BadCredentialsException exception = mapper.readValue(EXCEPTION_JSON, BadCredentialsException.class); assertThat(exception).isNotNull(); assertThat(exception.getCause()).isNull(); assertThat(exception.getMessage()).isEqualTo("message"); assertThat(exception.getLocalizedMessage()).isEqualTo("message"); } }
@Test public void testOIDCPasswordGrantNoIdToken() { UaaLoginHint loginHint = mock(UaaLoginHint.class); when(loginHint.getOrigin()).thenReturn("oidcprovider"); Authentication auth = mock(Authentication.class); when(auth.getPrincipal()).thenReturn("marissa"); when(auth.getCredentials()).thenReturn("koala"); when(zoneAwareAuthzAuthenticationManager.extractLoginHint(auth)).thenReturn(loginHint); RestTemplate rt = mock(RestTemplate.class); when(restTemplateConfig.nonTrustingRestTemplate()).thenReturn(rt); ResponseEntity<Map<String,String>> response = mock(ResponseEntity.class); when(response.hasBody()).thenReturn(true); when(response.getBody()).thenReturn(Collections.emptyMap()); when(rt.exchange(anyString(),any(HttpMethod.class),any(HttpEntity.class),any(ParameterizedTypeReference.class))).thenReturn(response); try { instance.authenticate(auth); fail(); } catch (BadCredentialsException e) { assertEquals("Could not obtain id_token from external OpenID Connect provider.", e.getMessage()); } }
@Test public void testGenerateAutologinCodeFailsWhenMfaRequired() throws Exception { doReturn(true).when(mfaChecker).isMfaEnabled(any(IdentityZone.class), anyString()); LoginInfoEndpoint endpoint = getEndpoint(); try { endpoint.generateAutologinCode(mock(AutologinRequest.class), "Basic 1234"); fail("MFA was not required"); } catch (BadCredentialsException e) { assertEquals("MFA is required", e.getMessage()); } }
@Test public void testOIDCPasswordGrantNoBody() { UaaLoginHint loginHint = mock(UaaLoginHint.class); when(loginHint.getOrigin()).thenReturn("oidcprovider"); Authentication auth = mock(Authentication.class); when(auth.getPrincipal()).thenReturn("marissa"); when(auth.getCredentials()).thenReturn("koala"); when(zoneAwareAuthzAuthenticationManager.extractLoginHint(auth)).thenReturn(loginHint); RestTemplate rt = mock(RestTemplate.class); when(restTemplateConfig.nonTrustingRestTemplate()).thenReturn(rt); ResponseEntity<Map<String,String>> response = mock(ResponseEntity.class); when(response.hasBody()).thenReturn(false); when(rt.exchange(anyString(),any(HttpMethod.class),any(HttpEntity.class),any(ParameterizedTypeReference.class))).thenReturn(response); try { instance.authenticate(auth); fail(); } catch (BadCredentialsException e) { assertEquals("Could not obtain id_token from external OpenID Connect provider.", e.getMessage()); } }
@Test public void testOIDCPasswordGrantNoUserCredentials() { UaaLoginHint loginHint = mock(UaaLoginHint.class); when(loginHint.getOrigin()).thenReturn("oidcprovider"); Authentication auth = mock(Authentication.class); when(zoneAwareAuthzAuthenticationManager.extractLoginHint(auth)).thenReturn(loginHint); try { instance.authenticate(auth); fail(); } catch (BadCredentialsException e) { assertEquals("Request is missing username or password.", e.getMessage()); } }
@Test public void testPerformAutologinFailsWhenMfaRequired() throws Exception { doReturn(true).when(mfaChecker).isMfaEnabled(any(IdentityZone.class), anyString()); LoginInfoEndpoint endpoint = getEndpoint(); try { endpoint.performAutologin(new MockHttpSession()); fail("MFA was not required"); } catch (BadCredentialsException e) { assertEquals("MFA is required", e.getMessage()); } }
@Test public void testOIDCPasswordGrant_NoLoginHintDefaultNotAllowedSingleIdpDoesNotSupportPassword() { IdentityZoneHolder.get().getConfig().setDefaultIdentityProvider("uaa"); Authentication auth = mock(Authentication.class); when(auth.getPrincipal()).thenReturn("marissa"); when(auth.getCredentials()).thenReturn("koala"); Map<String, Object> additionalInfo = Collections.singletonMap(ClientConstants.ALLOWED_PROVIDERS, Collections.singletonList("oidcprovider")); when(clientDetails.getAdditionalInformation()).thenReturn(additionalInfo); IdentityProvider localIdp = mock(IdentityProvider.class); OIDCIdentityProviderDefinition idpConfig = mock(OIDCIdentityProviderDefinition.class); when(localIdp.getOriginKey()).thenReturn("oidcprovider"); when(localIdp.getConfig()).thenReturn(idpConfig); when(localIdp.getType()).thenReturn(OriginKeys.OIDC10); when(idpConfig.isPasswordGrantEnabled()).thenReturn(false); when(identityProviderProvisioning.retrieveActive("uaa")).thenReturn(Arrays.asList(uaaProvider, ldapProvider, localIdp)); when(xoAuthProviderConfigurator.retrieveByOrigin("oidcprovider","uaa")).thenReturn(localIdp); try { instance.authenticate(auth); fail(); } catch (BadCredentialsException e) { assertEquals("The client is not authorized for any identity provider that supports password grant.", e.getMessage()); } }
@Test public void testOIDCPasswordGrant_NoLoginHintDefaultNotAllowedMultipleIdpsOnlyOIDC() { IdentityZoneHolder.get().getConfig().setDefaultIdentityProvider("oidcprovider3"); Authentication auth = mock(Authentication.class); when(zoneAwareAuthzAuthenticationManager.extractLoginHint(auth)).thenReturn(null); Map<String, Object> additionalInfo = Collections.singletonMap(ClientConstants.ALLOWED_PROVIDERS, Arrays.asList("oidcprovider", "oidcprovider2")); when(clientDetails.getAdditionalInformation()).thenReturn(additionalInfo); IdentityProvider localIdp = mock(IdentityProvider.class); OIDCIdentityProviderDefinition idpConfig = mock(OIDCIdentityProviderDefinition.class); when(localIdp.getOriginKey()).thenReturn("oidcprovider2"); when(localIdp.getConfig()).thenReturn(idpConfig); when(localIdp.getType()).thenReturn(OriginKeys.OIDC10); when(idpConfig.isPasswordGrantEnabled()).thenReturn(true); when(identityProviderProvisioning.retrieveActive("uaa")).thenReturn(Arrays.asList(uaaProvider, ldapProvider, idp, localIdp)); try { instance.authenticate(auth); fail(); } catch (BadCredentialsException e) { assertEquals("The client is authorized for multiple identity providers that support password grant and could not determine which identity provider to use.", e.getMessage()); } }
@Test public void testAuthenticateFailure() { OpenIDAuthenticationProvider provider = new OpenIDAuthenticationProvider(); provider.setAuthenticationUserDetailsService( new UserDetailsByNameServiceWrapper<>( new MockUserDetailsService())); Authentication preAuth = new OpenIDAuthenticationToken( OpenIDAuthenticationStatus.FAILURE, USERNAME, "", null); assertThat(preAuth.isAuthenticated()).isFalse(); try { provider.authenticate(preAuth); fail("Should throw an AuthenticationException"); } catch (BadCredentialsException expected) { assertThat("Log in failed - identity could not be verified").isEqualTo( expected.getMessage()); } }
/** * Handle business exception map. * * @param ex the ex * @return the map */ @ExceptionHandler(BadCredentialsException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) public Map<String, Object> handleBusinessException(BadCredentialsException ex) { //用户名或密码错误 return makeErrorMessage(ReturnCode.INVALID_GRANT, "Bad credentials", ex.getMessage()); }
@ExceptionHandler(BadCredentialsException.class) @ResponseStatus(HttpStatus.UNAUTHORIZED) @ResponseBody public String unauthorized(BadCredentialsException ex) { return ex.getMessage(); }
@ExceptionHandler(BadCredentialsException.class) @ResponseStatus(HttpStatus.UNAUTHORIZED) @ResponseBody public String unauthorized(BadCredentialsException ex) { return ex.getMessage(); }
@ExceptionHandler(value = BadCredentialsException.class) @ResponseStatus(HttpStatus.EXPECTATION_FAILED) @ResponseBody public ApiResponse handleBadCredentialsException(BadCredentialsException ex) { ApiResponse apiResponse = new ApiResponse(); apiResponse.setSuccess(false); apiResponse.setData(ex.getMessage()); return apiResponse; }
public class CustomResourceOwnerPasswordTokenGranter extends ResourceOwnerPasswordTokenGranter { protected OAuth2Authentication getOAuth2Authentication ( ClientDetails client, TokenRequest tokenRequest ) { Map parameters = tokenRequest.getRequestParameters(); String username = (String) parameters.get("username"); String password = (String) parameters.get("password"); String realmName = (String) parameters.get("realm_name"); Authentication userAuth = createAuthenticationBasedOnRealmName(username, password, realmName); try { userAuth = this.authenticationManager.authenticate(userAuth); } catch ( AccountStatusException ase ) { throw new InvalidGrantException(ase.getMessage()); } catch ( BadCredentialsException e ) { throw new InvalidGrantException(e.getMessage()); } if ( ( userAuth == null ) || ( ! ( userAuth.isAuthenticated() ) ) ) { throw new InvalidGrantException("Could not authenticate user: " + username); } OAuth2Request storedOAuth2Request = getRequestFactory().createOAuth2Request(client, tokenRequest); return new OAuth2Authentication(storedOAuth2Request, userAuth); } private Authentication createAuthentication ( String username, String password, String realmName ) throws InvalidGrantException { // TODO: decide basing on realm name } }
} catch (BadCredentialsException e) { throw new InvalidGrantException(e.getMessage());
@Override public JsonResult<String> login(String username, String password) { UsernamePasswordAuthenticationToken upToken = new UsernamePasswordAuthenticationToken(username, password); try { final Authentication authentication = authenticationManager.authenticate(upToken); SecurityContextHolder.getContext().setAuthentication(authentication); final UserDetails userDetails = userDetailsService.loadUserByUsername(username); return JsonResult.<String>builder().data(jwtTokenUtil.generateToken(userDetails)).build(); } catch (BadCredentialsException e) { logger.debug(e.getMessage()); return JsonResult.<String>builder().error("帐号或密码错误").build(); } }
@Override protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) { Map<String, String> parameters = new LinkedHashMap<String, String>(tokenRequest.getRequestParameters()); String username = parameters.get("username"); String password = parameters.get("password"); // Protect from downstream leaks of password parameters.remove("password"); Authentication userAuth = new UsernamePasswordAuthenticationToken(username, password); ((AbstractAuthenticationToken) userAuth).setDetails(parameters); try { userAuth = authenticationManager.authenticate(userAuth); } catch (AccountStatusException ase) { //covers expired, locked, disabled cases (mentioned in section 5.2, draft 31) throw new InvalidGrantException(ase.getMessage()); } catch (BadCredentialsException e) { // If the username/password are wrong the spec says we should send 400/invalid grant throw new InvalidGrantException(e.getMessage()); } if (userAuth == null || !userAuth.isAuthenticated()) { throw new InvalidGrantException("Could not authenticate user: " + username); } OAuth2Request storedOAuth2Request = getRequestFactory().createOAuth2Request(client, tokenRequest); return new OAuth2Authentication(storedOAuth2Request, userAuth); } }
@Override protected OAuth2Authentication getOAuth2Authentication(AuthorizationRequest clientToken) { Map<String, String> parameters = clientToken.getAuthorizationParameters(); String username = parameters.get("username"); String password = parameters.get("password"); Authentication userAuth = new InternalAuthentication(username, password, new ArrayList<GrantedAuthority>()); try { userAuth = authenticationManager.authenticate(userAuth); } catch (AccountStatusException ase) { // covers expired, locked, disabled cases (mentioned in section 5.2, draft 31) throw new InvalidGrantException(ase.getMessage(), ase); } catch (BadCredentialsException e) { // If the username/password are wrong the spec says we should send 400/bad grant throw new InvalidGrantException(e.getMessage(), e); } if (userAuth == null || !userAuth.isAuthenticated()) { throw new InvalidGrantException("Could not authenticate user: " + username); } DefaultAuthorizationRequest request = new DefaultAuthorizationRequest(clientToken); request.remove(Arrays.asList("password")); return new OAuth2Authentication(request, userAuth); } }
@Override public Authentication authenticate(T authenticationToken) throws AuthenticationException { if (authenticationToken == null) { throw new InvalidTokenException("Null authentication token"); } org.springframework.security.core.Authentication authentication = getAuthentication(authenticationToken); if (authentication == null) { throw new InvalidTokenException("Invalid authentication token: missing Spring Security Authentication"); } try { authentication = authenticationManager.authenticate(authentication); } catch (UsernameNotFoundException e) { throw new UnknownAccountException(e.getMessage()); } catch (BadCredentialsException e) { throw new InvalidCredentialsException(e.getMessage()); } catch (CredentialsExpiredException | AccountExpiredException e) { throw new ExpiredCredentialsException(e.getMessage()); } catch (DisabledException e) { throw new DisabledAccountException(e.getMessage()); } catch (LockedException e) { throw new LockedAccountException(e.getMessage()); } catch (Exception e) { throw new UnexpectedAuthenticationException(e.getMessage(), e); } return SpringSecurityAuthentication.create(authentication); }