org.springframework.security.authentication.BadCredentialsException.getMessage()方法的使用及代码示例

x33g5p2x  于2022-01-16 转载在 其他  
字(15.4k)|赞(0)|评价(0)|浏览(132)

本文整理了Java中org.springframework.security.authentication.BadCredentialsException.getMessage()方法的一些代码示例,展示了BadCredentialsException.getMessage()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。BadCredentialsException.getMessage()方法的具体详情如下:
包路径:org.springframework.security.authentication.BadCredentialsException
类名称:BadCredentialsException
方法名:getMessage

BadCredentialsException.getMessage介绍

暂无

代码示例

代码示例来源:origin: spring-projects/spring-security-oauth

@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);
  }
}

代码示例来源:origin: spring-projects/spring-security

@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");
  }
}

代码示例来源:origin: cloudfoundry/uaa

@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());
  }
}

代码示例来源:origin: cloudfoundry/uaa

@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());
  }
}

代码示例来源:origin: cloudfoundry/uaa

@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());
  }
}

代码示例来源:origin: cloudfoundry/uaa

@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());
  }
}

代码示例来源:origin: cloudfoundry/uaa

@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());
  }
}

代码示例来源:origin: cloudfoundry/uaa

@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());
  }
}

代码示例来源:origin: cloudfoundry/uaa

@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());
  }
}

代码示例来源:origin: spring-projects/spring-security

@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());
  }
}

代码示例来源:origin: zhangxd1989/springboot-dubbox

/**
 * 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());
}

代码示例来源:origin: org.n52.sensorweb.sos/admin-controller

@ExceptionHandler(BadCredentialsException.class)
@ResponseStatus(HttpStatus.UNAUTHORIZED)
@ResponseBody
public String unauthorized(BadCredentialsException ex) {
  return ex.getMessage();
}

代码示例来源:origin: 52North/SOS

@ExceptionHandler(BadCredentialsException.class)
@ResponseStatus(HttpStatus.UNAUTHORIZED)
@ResponseBody
public String unauthorized(BadCredentialsException ex) {
  return ex.getMessage();
}

代码示例来源:origin: isopropylcyanide/Jwt-Spring-Security-JPA

@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;
}

代码示例来源:origin: stackoverflow.com

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
  }
}

代码示例来源:origin: stackoverflow.com

} catch (BadCredentialsException e) {
  throw new InvalidGrantException(e.getMessage());

代码示例来源:origin: DigAg/digag-server

@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();
  }
}

代码示例来源:origin: org.springframework.security.oauth/spring-security-oauth2

@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);
  }
}

代码示例来源:origin: osiam/server

@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);
  }
}

代码示例来源:origin: com.holon-platform.core/holon-spring-security

@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);
}

相关文章

微信公众号

最新文章

更多