org.springframework.security.authentication.BadCredentialsException类的使用及代码示例

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

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

BadCredentialsException介绍

[英]Thrown if an authentication request is rejected because the credentials are invalid. For this exception to be thrown, it means the account is neither locked nor disabled.
[中]如果由于凭据无效而拒绝身份验证请求,则引发。对于要引发的此异常,这意味着该帐户既没有被锁定也没有被禁用。

代码示例

代码示例来源:origin: ChinaSilence/any-video

@Override
public Authentication authenticate(Authentication auth) throws AuthenticationException {
  if (auth.getName() != null && auth.getCredentials() != null) {
    User user = getUserInfo(auth.getName());
    return new UsernamePasswordAuthenticationToken(user,
        null, AUTHORITIES);
  }
  throw new BadCredentialsException("Bad Credentials");
}

代码示例来源: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

private BadCredentialsException badCredentials(Throwable cause) {
  return (BadCredentialsException) badCredentials().initCause(cause);
}

代码示例来源: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: svlada/springboot-security-jwt

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
  Assert.notNull(authentication, "No authentication data provided");
  String username = (String) authentication.getPrincipal();
  String password = (String) authentication.getCredentials();
  User user = userService.getByUsername(username).orElseThrow(() -> new UsernameNotFoundException("User not found: " + username));
  
  if (!encoder.matches(password, user.getPassword())) {
    throw new BadCredentialsException("Authentication Failed. Username or Password not valid.");
  }
  if (user.getRoles() == null) throw new InsufficientAuthenticationException("User has no roles assigned");
  
  List<GrantedAuthority> authorities = user.getRoles().stream()
      .map(authority -> new SimpleGrantedAuthority(authority.getRole().authority()))
      .collect(Collectors.toList());
  
  UserContext userContext = UserContext.create(user.getUsername(), authorities);
  
  return new UsernamePasswordAuthenticationToken(userContext, null, userContext.getAuthorities());
}

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

String principal = principalPrefix + authentication.getName();
String password = "";
if (authentication.getCredentials() != null) {
  password = authentication.getCredentials().toString();
  throw new BadCredentialsException("Blank username and/or password!");

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

String username = (authentication.getPrincipal() == null) ? "NONE_PROVIDED"
    : authentication.getName();
      throw new BadCredentialsException(messages.getMessage(
          "AbstractUserDetailsAuthenticationProvider.badCredentials",
          "Bad credentials"));

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

.equals(authentication.getPrincipal().toString()) && !CasAuthenticationFilter.CAS_STATELESS_IDENTIFIER
        .equals(authentication.getPrincipal().toString()))) {
    throw new BadCredentialsException(
        messages.getMessage("CasAuthenticationProvider.incorrectKey",
            "The presented CasAuthenticationToken does not contain the expected key"));
if ((authentication.getCredentials() == null)
    || "".equals(authentication.getCredentials())) {
  throw new BadCredentialsException(messages.getMessage(
      "CasAuthenticationProvider.noServiceTicket",
      "Failed to provide a CAS service ticket to validate"));

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

@RequestHeader(value = "Authorization", required = false) String auth) throws Exception {
if (mfaChecker.isMfaEnabled(IdentityZoneHolder.get(), "uaa")) {
  throw new BadCredentialsException("MFA is required");
  throw new BadCredentialsException("No basic authorization client information in request");
  throw new BadCredentialsException("No username in request");
  String password = request.getPassword();
  if (!hasText(password)) {
    throw new BadCredentialsException("No password in request");
  throw new BadCredentialsException("Invalid authorization header.");
codeData.put("client_id", clientId);
codeData.put("username", username);
if (userAuthentication!=null && userAuthentication.getPrincipal() instanceof UaaPrincipal) {
  UaaPrincipal p = (UaaPrincipal)userAuthentication.getPrincipal();
  if (p!=null) {
    codeData.put("user_id", p.getId());

代码示例来源:origin: gocd/gocd

public AccessToken(Map<String, String> credentials) {
  if (credentials == null || credentials.isEmpty()) {
    throw new BadCredentialsException("Credentials cannot be empty!");
  }
  this.credentials = credentials;
}

代码示例来源: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: geoserver/geoserver

@Override
  public Authentication authenticate(Authentication authentication, HttpServletRequest request)
      throws AuthenticationException {

    UsernamePasswordAuthenticationToken token =
        (UsernamePasswordAuthenticationToken) authentication;

    // check if name is root
    if (GeoServerUser.ROOT_USERNAME.equals(token.getPrincipal()) == false) return null;

    // check password
    if (token.getCredentials() != null) {
      if (getSecurityManager().checkMasterPassword(token.getCredentials().toString())) {
        Collection<GrantedAuthority> roles = new ArrayList<GrantedAuthority>();
        roles.add(GeoServerRole.ADMIN_ROLE);

        UsernamePasswordAuthenticationToken result =
            new UsernamePasswordAuthenticationToken(
                GeoServerUser.ROOT_USERNAME, null, roles);
        result.setDetails(token.getDetails());
        return result;
      }
    }

    // not BadCredentialException is thrown, maybe there is another user with
    // the same name
    log(new BadCredentialsException("Bad credentials for: " + token.getPrincipal()));
    return null;
  }
}

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

logger.debug("Authentication credentials found for '" + credentials.getName() + "'");
  logger.debug("Authentication success: " + authResult.getName());
  throw new BadCredentialsException(
      "No client authentication found. Remember to put a filter upstream of the TokenEndpointAuthenticationFilter.");
map.put(OAuth2Utils.CLIENT_ID, clientAuth.getName());
AuthorizationRequest authorizationRequest = oAuth2RequestFactory.createAuthorizationRequest(map);

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

@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
    throws AuthenticationException, IOException, ServletException {
  if (allowOnlyPost && !"POST".equalsIgnoreCase(request.getMethod())) {
    throw new HttpRequestMethodNotSupportedException(request.getMethod(), new String[] { "POST" });
  }
  String clientId = request.getParameter("client_id");
  String clientSecret = request.getParameter("client_secret");
  // If the request is already authenticated we can assume that this
  // filter is not needed
  Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
  if (authentication != null && authentication.isAuthenticated()) {
    return authentication;
  }
  if (clientId == null) {
    throw new BadCredentialsException("No client credentials presented");
  }
  if (clientSecret == null) {
    clientSecret = "";
  }
  clientId = clientId.trim();
  UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(clientId,
      clientSecret);
  return this.getAuthenticationManager().authenticate(authRequest);
}

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

private Authentication performClientAuthentication(HttpServletRequest req, Map<String, String> loginInfo, String clientId) {
  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);
  }
}

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

@Test
public void successfulLoginAuthenticationInvokesLoginAuthManager() throws Exception {
  SecurityContextHolder.getContext().setAuthentication(loginAuthentication);
  when(am.authenticate(any(Authentication.class))).thenThrow(new BadCredentialsException("Invalid authentication manager invoked"));
  when(loginAuthMgr.authenticate(any(Authentication.class))).thenReturn(new UsernamePasswordAuthenticationToken("joe", null));
  when(loginAuthentication.isClientOnly()).thenReturn(Boolean.TRUE);
  @SuppressWarnings("rawtypes")
  ResponseEntity response = (ResponseEntity) endpoint.authenticate(new MockHttpServletRequest(), "joe","origin", null);
  assertEquals(HttpStatus.OK, response.getStatusCode());
}

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

public Authentication authenticate(Authentication authentication)
      throws AuthenticationException {
    Object principal = authentication.getPrincipal();
    String username = String.valueOf(principal);
    User user = myUserRepository.findByUsername(username);
    if (user == null) {
      throw new UsernameNotFoundException("No user for principal "
          + principal);
    }
    if (!authentication.getCredentials().equals(user.getPassword())) {
      throw new BadCredentialsException("Invalid password");
    }
    return new TestingAuthenticationToken(principal, null, "ROLE_USER");
  }
};

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

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

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

@SuppressWarnings("deprecation")
protected void additionalAuthenticationChecks(UserDetails userDetails,
    UsernamePasswordAuthenticationToken authentication)
    throws AuthenticationException {
  if (authentication.getCredentials() == null) {
    logger.debug("Authentication failed: no credentials provided");
    throw new BadCredentialsException(messages.getMessage(
        "AbstractUserDetailsAuthenticationProvider.badCredentials",
        "Bad credentials"));
  }
  String presentedPassword = authentication.getCredentials().toString();
  if (!passwordEncoder.matches(presentedPassword, userDetails.getPassword())) {
    logger.debug("Authentication failed: password does not match stored value");
    throw new BadCredentialsException(messages.getMessage(
        "AbstractUserDetailsAuthenticationProvider.badCredentials",
        "Bad credentials"));
  }
}

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

@Override
public Authentication authenticate(Authentication req) throws AuthenticationException {
  logger.debug("Processing authentication request for " + req.getName());
  if (req.getCredentials() == null) {
    BadCredentialsException e = new BadCredentialsException("No password supplied");
    publish(new AuthenticationFailureBadCredentialsEvent(req, e));
    throw e;
    logger.debug("No user named '" + req.getName() + "' was found for origin:"+ origin);
    publish(new UserNotFoundEvent(req));
  } else {
  BadCredentialsException e = new BadCredentialsException("Bad credentials");
  publish(new AuthenticationFailureBadCredentialsEvent(req, e));
  throw e;

相关文章

微信公众号

最新文章

更多