当前位置: 首页>>代码示例>>Java>>正文


Java BadCredentialsException类代码示例

本文整理汇总了Java中org.springframework.security.authentication.BadCredentialsException的典型用法代码示例。如果您正苦于以下问题:Java BadCredentialsException类的具体用法?Java BadCredentialsException怎么用?Java BadCredentialsException使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


BadCredentialsException类属于org.springframework.security.authentication包,在下文中一共展示了BadCredentialsException类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: authenticate

import org.springframework.security.authentication.BadCredentialsException; //导入依赖的package包/类
@Override
public JwtToken authenticate(Authentication authentication) throws AuthenticationException {

    JwtToken token = (JwtToken) authentication;

    if (token.getPrincipal() instanceof String) {

        try {
            Claims claims = Jwts.parser()
                    .setSigningKey(secret)
                    .parseClaimsJws((String) token.getPrincipal())
                    .getBody();

            UserDetails user = handler.parseClaims(claims);

            return new JwtToken(user, claims, user.getAuthorities());
        } catch (ClaimJwtException ex) {
            throw new BadCredentialsException("JWT error", ex);
        }
    } else {
        return null;
    }
}
 
开发者ID:LIBCAS,项目名称:ARCLib,代码行数:24,代码来源:JwtTokenProvider.java

示例2: authenticate

import org.springframework.security.authentication.BadCredentialsException; //导入依赖的package包/类
@Override
public Authentication authenticate(Authentication auth){
 Usuario user = userRepository.findByEmail(auth.getName());
 if (user == null) {
	 throw new BadCredentialsException("User not found");
 }
 String password = (String) auth.getCredentials();
 if (!new BCryptPasswordEncoder().matches(password, user.getContraseña())) {
	 throw new BadCredentialsException("Wrong password");
 }

 List<GrantedAuthority> roles = new ArrayList<>();
 for (String role : user.getRol()) {
	 roles.add(new SimpleGrantedAuthority(role));
	 }
 return new UsernamePasswordAuthenticationToken(user.getEmail(), password, roles);
}
 
开发者ID:jeche21,项目名称:SaleWeb,代码行数:18,代码来源:UsuarioRepositoryAuthenticationProvider.java

示例3: authenticate

import org.springframework.security.authentication.BadCredentialsException; //导入依赖的package包/类
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) authentication;
    String email = token.getName();
    CalendarUser user = email == null ? null : calendarService.findUserByEmail(email);
    if(user == null) {
        throw new UsernameNotFoundException("Invalid username/password");
    }
    // Database Password already encrypted:
    String password = user.getPassword();

    boolean passwordsMatch = passwordEncoder.matches(token.getCredentials().toString(), password);

    if(!passwordsMatch) {
        throw new BadCredentialsException("Invalid username/password");
    }
    Collection<? extends GrantedAuthority> authorities = CalendarUserAuthorityUtils.createAuthorities(user);
    UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(user, password, authorities);
    return usernamePasswordAuthenticationToken;
}
 
开发者ID:PacktPublishing,项目名称:Spring-Security-Third-Edition,代码行数:21,代码来源:CalendarUserAuthenticationProvider.java

示例4: onAuthenticationFailure

import org.springframework.security.authentication.BadCredentialsException; //导入依赖的package包/类
@Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
		AuthenticationException exception) throws IOException, ServletException {
	System.out.println("failure");
	String targetUrl = "";
	if(exception instanceof BadCredentialsException){
		targetUrl = "/login.html?error=" + exception.getMessage();
	}
	else {
		targetUrl = "/login.html?error=" + true;
	}
	  
	if (response.isCommitted()) {
            System.out.println("Internal problem in redirection");
            return;
    }
   
    redirectStrategy.sendRedirect(request, response, targetUrl);
}
 
开发者ID:PacktPublishing,项目名称:Spring-5.0-Cookbook,代码行数:20,代码来源:CustomFailureHandler.java

示例5: authenticate

import org.springframework.security.authentication.BadCredentialsException; //导入依赖的package包/类
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {

    // Determine if this AuthenticationProvider's identityProvider should be able to support this AuthenticationRequest
    boolean tokenOriginatedFromThisIdentityProvider = checkTokenOriginatedFromThisIdentityProvider(authentication);

    if (!tokenOriginatedFromThisIdentityProvider) {
        // Returning null indicates to The Spring Security AuthenticationManager that this AuthenticationProvider
        // cannot authenticate this token and another provider should be tried.
        return null;
    }

    AuthenticationRequestToken authenticationRequestToken = ((AuthenticationRequestToken)authentication);
    AuthenticationRequest authenticationRequest = authenticationRequestToken.getAuthenticationRequest();

    try {
        AuthenticationResponse authenticationResponse = identityProvider.authenticate(authenticationRequest);
        if (authenticationResponse == null) {
            return null;
        }
        return buildAuthenticatedToken(authenticationRequestToken, authenticationResponse);
    } catch (InvalidCredentialsException e) {
        throw new BadCredentialsException("Identity Provider authentication failed.", e);
    }

}
 
开发者ID:apache,项目名称:nifi-registry,代码行数:27,代码来源:IdentityAuthenticationProvider.java

示例6: extractAndDecodeHeader

import org.springframework.security.authentication.BadCredentialsException; //导入依赖的package包/类
private String[] extractAndDecodeHeader(String header, HttpServletRequest request) throws IOException {
    byte[] base64Token = header.substring(6).getBytes("UTF-8");

    byte[] decoded;
    try {
        decoded = Base64.decode(base64Token);
    } catch (IllegalArgumentException var7) {
        throw new BadCredentialsException("Failed to decode basic authentication token");
    }

    String token = new String(decoded, "UTF-8");
    int delim = token.indexOf(":");
    if (delim == -1) {
        throw new BadCredentialsException("Invalid basic authentication token");
    } else {
        return new String[]{token.substring(0, delim), token.substring(delim + 1)};
    }
}
 
开发者ID:TZClub,项目名称:OMIPlatform,代码行数:19,代码来源:TZAuthenticationSuccessHandler.java

示例7: onAuthenticationFailure

import org.springframework.security.authentication.BadCredentialsException; //导入依赖的package包/类
@Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
		AuthenticationException e) throws IOException, ServletException {
	
	response.setStatus(HttpStatus.UNAUTHORIZED.value());
	response.setContentType(MediaType.APPLICATION_JSON_VALUE);
	
	if (e instanceof BadCredentialsException) {
		mapper.writeValue(response.getWriter(), ErrorResponse.of("Invalid username or password", ErrorCode.AUTHENTICATION, HttpStatus.UNAUTHORIZED));
	} else if (e instanceof JwtExpiredTokenException) {
		mapper.writeValue(response.getWriter(), ErrorResponse.of("Token has expired", ErrorCode.JWT_TOKEN_EXPIRED, HttpStatus.UNAUTHORIZED));
	} else if (e instanceof AuthMethodNotSupportedException) {
	    mapper.writeValue(response.getWriter(), ErrorResponse.of(e.getMessage(), ErrorCode.AUTHENTICATION, HttpStatus.UNAUTHORIZED));
	}

	mapper.writeValue(response.getWriter(), ErrorResponse.of("Authentication failed", ErrorCode.AUTHENTICATION, HttpStatus.UNAUTHORIZED));
}
 
开发者ID:mjfcolas,项目名称:infotaf,代码行数:18,代码来源:AjaxAwareAuthenticationFailureHandler.java

示例8: attemptAuthentication

import org.springframework.security.authentication.BadCredentialsException; //导入依赖的package包/类
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
    throws AuthenticationException, IOException, ServletException {

    try {
        OAuth2AccessToken accessToken = restTemplate.getAccessToken();
        FacebookUser facebookUser = userIdentity.findOrCreateFrom(accessToken);

        repository.save(facebookUser);

        Authentication authentication = new UsernamePasswordAuthenticationToken(
                facebookUser, null, Arrays.asList(new SimpleGrantedAuthority("ROLE_USER")));
        publish(new AuthenticationSuccessEvent(authentication));
        return authentication;
    } catch (OAuth2Exception e) {
        BadCredentialsException error = new BadCredentialsException(
                "Cannot retrieve the access token", e);
        publish(new OAuth2AuthenticationFailureEvent(error));
        throw error;
    }
}
 
开发者ID:PacktPublishing,项目名称:OAuth-2.0-Cookbook,代码行数:21,代码来源:FacebookLoginFilter.java

示例9: validateTicket

import org.springframework.security.authentication.BadCredentialsException; //导入依赖的package包/类
@Override
public KerberosTicketValidation validateTicket(byte[] token) throws BadCredentialsException {

    boolean validTicket;
    try {
         validTicket = Arrays.equals(validKerberosTicket.getBytes("UTF-8"), token);
    } catch (UnsupportedEncodingException e) {
        throw new IllegalStateException(e);
    }

    if (!validTicket) {
        throw new BadCredentialsException(MockKerberosTicketValidator.class.getSimpleName() + " does not validate token");
    }

    return new KerberosTicketValidation(
            "[email protected]",
            "HTTP/[email protected]",
            null,
            null);
}
 
开发者ID:apache,项目名称:nifi-registry,代码行数:21,代码来源:SecureKerberosIT.java

示例10: authenticate

import org.springframework.security.authentication.BadCredentialsException; //导入依赖的package包/类
@Override
public Authentication authenticate(Authentication authentication)
    throws AuthenticationException {
  logger.debug(
      "==== Authenticating using BarAuthenticationProvider: " +
          authentication);

  // here goes username/password authentication for Foo
  Response response = userService
      .authenticateBar(String.valueOf(authentication.getPrincipal()),
          String.valueOf(authentication.getCredentials()));

  if (response.isOk()) {
    List<GrantedAuthority> authorities = new ArrayList<>();
    authorities.add(new SimpleGrantedAuthority("BAR_READ"));
    authorities.add(new SimpleGrantedAuthority("BAR_WRITE"));
    return new BarUsernamePasswordAuthenticationToken(
        authentication.getPrincipal(), authentication.getCredentials(),
        authorities);
  } else {
    throw new BadCredentialsException("Authentication failed.");
  }
}
 
开发者ID:gdong42,项目名称:spring-auth-example,代码行数:24,代码来源:BarAuthenticationProvider.java

示例11: authenticate

import org.springframework.security.authentication.BadCredentialsException; //导入依赖的package包/类
@Override
public Authentication authenticate(Authentication authentication)
    throws AuthenticationException {
  logger.debug(
      "==== Authenticating using FooAuthenticationProvider: " +
          authentication);

  // here goes username/password authentication for Foo
  Response response = userService
      .authenticateFoo(String.valueOf(authentication.getPrincipal()),
          String.valueOf(authentication.getCredentials()));

  if (response.isOk()) {
    List<GrantedAuthority> authorities = new ArrayList<>();
    authorities.add(new SimpleGrantedAuthority("FOO_READ"));
    authorities.add(new SimpleGrantedAuthority("FOO_WRITE"));
    return new FooUsernamePasswordAuthenticationToken(
        authentication.getPrincipal(), authentication.getCredentials(),
        authorities);
  } else {
    throw new BadCredentialsException("Authentication failed.");
  }
}
 
开发者ID:gdong42,项目名称:spring-auth-example,代码行数:24,代码来源:FooAuthenticationProvider.java

示例12: authenticate

import org.springframework.security.authentication.BadCredentialsException; //导入依赖的package包/类
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    // 获取认证的用户名 & 密码
    String name = authentication.getName();
    String password = authentication.getCredentials().toString();

    User user = userRepository.findByUserName(name);
    if (user == null) throw new UsernameNotFoundException("username not found!");
    if (!user.isEnable()) throw new AuthenticationException("user has been disabled!") {};
    // 认证逻辑
    if (user.validatePassword(password)) {

        // 这里设置权限和角色
        ArrayList<GrantedAuthority> authorities = new ArrayList<>();
        // authorities.add( new GrantedAuthorityImpl("ROLE_ADMIN") );
        // authorities.add( new GrantedAuthorityImpl("AUTH_WRITE") );
        // 生成令牌
        Authentication auth = new UsernamePasswordAuthenticationToken(name, password, authorities);
        return auth;
    }else {
        throw new BadCredentialsException("密码错误~");
    }
}
 
开发者ID:myliang,项目名称:fish-admin,代码行数:24,代码来源:JwtAuthenticationProvider.java

示例13: run

import org.springframework.security.authentication.BadCredentialsException; //导入依赖的package包/类
@Override
public KerberosTicketValidation run() throws Exception {
    byte[] responseToken = new byte[0];
    GSSName gssName = null;
    GSSContext context = GSSManager.getInstance().createContext((GSSCredential) null);
    boolean first = true;
    while (!context.isEstablished()) {
        if (first) {
            kerberosTicket = tweakJdkRegression(kerberosTicket);
        }
        responseToken = context.acceptSecContext(kerberosTicket, 0, kerberosTicket.length);
        gssName = context.getSrcName();
        if (gssName == null) {
            throw new BadCredentialsException("GSSContext name of the context initiator is null");
        }
        first = false;
    }
    if (!holdOnToGSSContext) {
        context.dispose();
    }
    return new KerberosTicketValidation(gssName.toString(), servicePrincipal, responseToken, context);
}
 
开发者ID:LIBCAS,项目名称:ARCLib,代码行数:23,代码来源:PasswordTicketValidator.java

示例14: handleAuthenticationException

import org.springframework.security.authentication.BadCredentialsException; //导入依赖的package包/类
private void handleAuthenticationException(AuthenticationException authenticationException,
    HttpServletResponse response) throws IOException {
  response.setStatus(HttpStatus.UNAUTHORIZED.value());
  if (authenticationException instanceof BadCredentialsException) {
    mapper.writeValue(response.getWriter(), IoTPErrorResponse.of("Invalid username or password",
        IoTPErrorCode.AUTHENTICATION, HttpStatus.UNAUTHORIZED));
  } else if (authenticationException instanceof JwtExpiredTokenException) {
    mapper.writeValue(response.getWriter(), IoTPErrorResponse.of("Token has expired",
        IoTPErrorCode.JWT_TOKEN_EXPIRED, HttpStatus.UNAUTHORIZED));
  } else if (authenticationException instanceof AuthMethodNotSupportedException) {
    mapper.writeValue(response.getWriter(), IoTPErrorResponse.of(authenticationException.getMessage(),
        IoTPErrorCode.AUTHENTICATION, HttpStatus.UNAUTHORIZED));
  }
  mapper.writeValue(response.getWriter(), IoTPErrorResponse.of("Authentication failed",
      IoTPErrorCode.AUTHENTICATION, HttpStatus.UNAUTHORIZED));
}
 
开发者ID:osswangxining,项目名称:iotplatform,代码行数:17,代码来源:IoTPErrorResponseHandler.java

示例15: authenticate

import org.springframework.security.authentication.BadCredentialsException; //导入依赖的package包/类
public Authentication authenticate(Authentication authentication)
        throws AuthenticationException {

    UsernamePasswordAuthenticationToken auth = (UsernamePasswordAuthenticationToken) authentication;

    UserEntity entity;
    try {
        entity = user.authenticate(String.valueOf(auth.getPrincipal()), String.valueOf(auth.getCredentials()));

        if (entity == null) {
            throw new NotFoundException(ExceptionConstants.USER_NOT_FOUND);
        }
    } catch (Exception e) {
        throw new BadCredentialsException(ExceptionConstants.PASSWORD_DOES_NOT_MATCH);
    }

    return new UsernamePasswordAuthenticationToken(UserParser.toDTO(entity), null, Collections.singletonList(new SimpleGrantedAuthority(entity.getRoles().name())));
}
 
开发者ID:farchanjo,项目名称:webcron,代码行数:19,代码来源:SecurityProvider.java


注:本文中的org.springframework.security.authentication.BadCredentialsException类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。