org.springframework.security.authentication.UsernamePasswordAuthenticationToken#getCredentials ( )源码实例Demo

下面列出了org.springframework.security.authentication.UsernamePasswordAuthenticationToken#getCredentials ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

@Override
protected void additionalAuthenticationChecks(final UserDetails userDetails,
        final UsernamePasswordAuthenticationToken token) throws AuthenticationException {
    logger.info("> additionalAuthenticationChecks");

    if (token.getCredentials() == null || userDetails.getPassword() == null) {
        logger.info("< additionalAuthenticationChecks");
        throw new BadCredentialsException("Credentials may not be null.");
    }

    if (!passwordEncoder.matches((String) token.getCredentials(), userDetails.getPassword())) {
        logger.info("< additionalAuthenticationChecks");
        throw new BadCredentialsException("Invalid credentials.");
    }

    RequestContext.setUsername(userDetails.getUsername());

    logger.info("< additionalAuthenticationChecks");
}
 
@Override
   protected void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
       if (authentication.getCredentials() == null) {
           log.debug("Authentication failed: password is blank");
           throw new BadCredentialsException(messages.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "密码为空"));
       }
       // 获取密码
       String presentedPassword = authentication.getCredentials().toString();
       // 匹配密码
       if (!passwordEncoder.matches(presentedPassword, userDetails.getPassword())) {
           log.debug("Authentication failed: invalid password");
           SpringContextHolder.publishEvent(new CustomAuthenticationFailureEvent(authentication, userDetails));
		throw new BadCredentialsException(messages.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "用户名或密码错误"));
       }
       SpringContextHolder.publishEvent(new CustomAuthenticationSuccessEvent(authentication, userDetails));
}
 
/**
  * 加载用户信息
  *
  * @param username       username
  * @param authentication authentication
  * @return UserDetails
  * @throws AuthenticationException
  */
 @Override
 protected UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException, TenantNotFoundException{
     UserDetails loadedUser;
     try {
         // 加载用户信息
         loadedUser = this.userDetailsService.loadUserByIdentifierAndTenantCode(TenantContextHolder.getTenantCode(), authentication.getPrincipal().toString());
     } catch (UsernameNotFoundException notFound) {
         if (authentication.getCredentials() != null) {
             String presentedPassword = authentication.getCredentials().toString();
             passwordEncoder.matches(presentedPassword, userNotFoundEncodedPassword);
         }
         throw notFound;
     } catch (Exception tenantNotFound) {
throw new InternalAuthenticationServiceException(tenantNotFound.getMessage(), tenantNotFound);
     }
     if (loadedUser == null) {
         throw new InternalAuthenticationServiceException("get user information failed");
     }
     return loadedUser;
 }
 
源代码4 项目: wecube-platform   文件: UmAuthenticationChecker.java
private UmUserAuthResultDto performUserAuthentication(UmAuthContext authCtx, UmSubSystemAuthResultDto subSystemAuthResult,
		UsernamePasswordAuthenticationToken userToken) throws JsonParseException, JsonMappingException, IOException
		 {
	String host = authCtx.getHost();
	int port = authCtx.getPort();
	String userId = userToken.getName();
	String pwd = (String) userToken.getCredentials();
	String appid = subSystemAuthResult.getId();
	String tmp = generatePwd(userId, pwd);
	String timeStamp = String.valueOf(System.currentTimeMillis() / 1000);
	String sign = md5(userId + tmp + timeStamp);
	String token = subSystemAuthResult.getTok();
	String auth = subSystemAuthResult.getAuth();

	String url = String.format(
			"http://%s:%s/um_service?style=6&appid=%s&id=%s&sign=%s&timeStamp=%s&token=%s&auth=%s", host, port,
			appid, userId, sign, timeStamp, token, auth);

	HttpHeaders headers = new HttpHeaders();
	ResponseEntity<String> resp = sendGetRequestWithUrlParamMap(restTemplate, url, headers, String.class);

	UmUserAuthResultDto authResult = objectMapper.readValue(resp.getBody(), UmUserAuthResultDto.class);
	
	return authResult;
}
 
源代码5 项目: Roothub   文件: SimpleHashUtil.java
/**
 * 这个方法很重要,用于认证用户提供的信息是否正确,
 * 并且返回一个 UserDetails 对象,父类的 authenticate() 方法会用到这个对象
 */
@Override
protected UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication)
		throws AuthenticationException {
	// 调用认证服务接口,加载 UserDetails 对象
	UserDetails userDetails = userDetailsService.loadUserByUsername(username);
	if (userDetails == null) {
           throw new UsernameNotFoundException(username);
       }
	// 判断用户名和密码是否正确,如果正确直接返回
	if (userDetails.getUsername().equals(authentication.getPrincipal().toString()) 
               && passwordEncoder.isPasswordValid(userDetails.getPassword(), authentication.getCredentials().toString(), null)) {
           return userDetails;
       }
	throw new BadCredentialsException("username: " + username + ", credentials: " + authentication.getCredentials());
}
 
@Override
protected void additionalAuthenticationChecks(UserDetails userDetails,
                                              UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
    if (authentication.getCredentials() == null) {
        this.logger.debug("Authentication failed: no credentials provided");
        throw new BadCredentialsException(this.messages
            .getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
    } else {
        String presentedPassword = authentication.getCredentials().toString();
        if (!this.passwordEncoder.matches(presentedPassword, userDetails.getPassword())) {
            this.logger.debug("Authentication failed: password does not match stored value");
            throw new BadCredentialsException(this.messages
                .getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
        }
    }
}
 
@Override
protected void additionalAuthenticationChecks(UserDetails userDetails,
        UsernamePasswordAuthenticationToken token)
                throws AuthenticationException {
    logger.debug("> additionalAuthenticationChecks");

    if (token.getCredentials() == null
            || userDetails.getPassword() == null) {
        throw new BadCredentialsException("Credentials may not be null.");
    }

    if (!passwordEncoder.matches((String) token.getCredentials(),
            userDetails.getPassword())) {
        throw new BadCredentialsException("Invalid credentials.");
    }

    RequestContext.setUsername(userDetails.getUsername());

    logger.debug("< additionalAuthenticationChecks");
}
 
/**
 * Implementation of an abstract method defined in the base class. The
 * additionalAuthenticationChecks() method is called by authenticate()
 * method of the base class after the invocation of retrieveUser() method.
 */
@Override
protected void additionalAuthenticationChecks(UserDetails userDetails,
											  UsernamePasswordAuthenticationToken authentication)
		throws AuthenticationException {
	if (authentication.getCredentials() == null) {
		logger.warn("Authentication failed: no credentials provided");
		throw new BadCredentialsException(messages.getMessage(
				"AbstractUserDetailsAuthenticationProvider.badCredentials",
				"Bad credentials"), null);
	}

	String presentedPassword = authentication.getCredentials().toString();

	if (!passwordEncoder.matches(presentedPassword, userDetails.getPassword())) {
		logger.warn("Authentication failed: password does not match stored value");
		throw new BadCredentialsException(messages.getMessage("UserDetailsAuthenticationProviderImpl.badCredentials",
															  "Bad credentials"), null);
	}
}
 
/**
 * Implementation of an abstract method defined in the base class. The
 * additionalAuthenticationChecks() method is called by authenticate()
 * method of the base class after the invocation of retrieveUser() method.
 */
@Override
protected void additionalAuthenticationChecks(UserDetails userDetails,
											  UsernamePasswordAuthenticationToken authentication)
		throws AuthenticationException {
	if (authentication.getCredentials() == null) {
		logger.warn("Authentication failed: no credentials provided");
		throw new BadCredentialsException(messages.getMessage(
				"AbstractUserDetailsAuthenticationProvider.badCredentials",
				"Bad credentials"), null);
	}

	String presentedPassword = authentication.getCredentials().toString();

	if (!passwordEncoder.matches(presentedPassword, userDetails.getPassword())) {
		logger.warn("Authentication failed: password does not match stored value");
		throw new BadCredentialsException(messages.getMessage("UserDetailsAuthenticationProviderImpl.badCredentials",
															  "Bad credentials"), null);
	}
}
 
@Override
protected UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication)
        throws AuthenticationException {
    log.info("retrieveUser, for username={}", username);

    if (StringUtils.isEmpty(username)) {
        setHideUserNotFoundExceptions(false);//Setting this will cause UsernameNotFoundExceptions to be thrown instead of BadCredentialsException
        throw new UsernameNotFoundException("Enter your username.");
    }

    User user = userService.findUserByUsername(username);

    String givenPassword = (String) authentication.getCredentials();
    if (user == null || !user.getPassword().equals(givenPassword)) {
        throw new BadCredentialsException("Incorrect username or password.");
    }

    return user;
}
 
@Override
protected UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication) 
    throws AuthenticationException {
    CustomAuthenticationToken auth = (CustomAuthenticationToken) authentication;
    UserDetails loadedUser;

    try {
        loadedUser = this.userDetailsService.loadUserByUsernameAndDomain(auth.getPrincipal()
            .toString(), auth.getDomain());
    } catch (UsernameNotFoundException notFound) {
        if (authentication.getCredentials() != null) {
            String presentedPassword = authentication.getCredentials()
                .toString();
            passwordEncoder.matches(presentedPassword, userNotFoundEncodedPassword);
        }
        throw notFound;
    } catch (Exception repositoryProblem) {
        throw new InternalAuthenticationServiceException(repositoryProblem.getMessage(), repositoryProblem);
    }

    if (loadedUser == null) {
        throw new InternalAuthenticationServiceException("UserDetailsService returned null, "
            + "which is an interface contract violation");
    }
    return loadedUser;
}
 
源代码12 项目: Milkomeda   文件: CrustAuthenticationProvider.java
@Override
protected void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken authentication)
        throws AuthenticationException {

    // 如果使用BCrypt密码方式,使用父类默认实现
    if (props.isUseBcrypt()) {
        super.additionalAuthenticationChecks(userDetails, authentication);
        return;
    }

    // 检查登录密码
    if (authentication.getCredentials() == null) {
        logger.debug("Authentication failed: no credentials provided");
        throw new BadCredentialsException(messages.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
    }

    boolean isMatched;
    String presentedPassword = authentication.getCredentials().toString();
    // 如果用户有实现自定义加密器
    if (getPasswordEncoder() != null) {
        isMatched = getPasswordEncoder().matches(presentedPassword, userDetails.getPassword());
    } else {
        // 否则使用内置加密器
        String salt = ((CrustUserDetails) userDetails).getSalt();
        isMatched = new PasswordEncoder(salt).matches(presentedPassword, userDetails.getPassword());
    }

    // 如果验证失败
    if (!isMatched) {
        logger.debug("Authentication failed: password does not match stored value");
        throw new BadCredentialsException(messages.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
    }
}
 
源代码13 项目: wecube-platform   文件: UmAuthenticationChecker.java
private void verifyAuthToken(UsernamePasswordAuthenticationToken authToken) {
	String username = authToken.getName();
	String password = (String) authToken.getCredentials();

	if (StringUtils.isBlank(username) || StringUtils.isBlank(password)) {
		throw new BadCredentialsException("Bad credential:blank username or password.");
	}
}
 
@Override
protected UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication)
        throws AuthenticationException {
    CustomAuthenticationToken auth = (CustomAuthenticationToken) authentication;
    UserDetails loadedUser;

    try {
        loadedUser = this.userDetailsService
                .loadUserByUsernameAndTenantname(auth.getPrincipal().toString(),
                        auth.getTenant());
    } catch (UsernameNotFoundException notFound) {
        if (authentication.getCredentials() != null) {
            String presentedPassword = authentication.getCredentials().toString();
            passwordEncoder.matches(presentedPassword, userNotFoundEncodedPassword);
        }
        throw notFound;
    } catch (Exception repositoryProblem) {
        throw new InternalAuthenticationServiceException(repositoryProblem.getMessage(), 
                repositoryProblem);
    }

    if (loadedUser == null) {
        throw new InternalAuthenticationServiceException(
                "UserDetailsService returned null, "
                + "which is an interface contract violation");
    }
    return loadedUser;
}
 
@Override
protected UserDetails retrieveUser(final String username, final UsernamePasswordAuthenticationToken authentication) {
  final Object token = authentication.getCredentials();
  return Optional
    .ofNullable(token)
    .map(String::valueOf)
    .flatMap(auth::findByToken)
    .orElseThrow(() -> new UsernameNotFoundException("Cannot find user with authentication token=" + token));
}
 
@Override
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"));
	}
}
 
@Override
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"));
    }
}
 
源代码18 项目: hesperides   文件: LdapAuthenticationProvider.java
@Override
protected DirContextOperations doAuthentication(UsernamePasswordAuthenticationToken auth) {
    String username = auth.getName();
    String password = (String) auth.getCredentials();
    // L'objet retourné est directement passé à loadUserAuthorities par la classe parente :
    return self.searchCN(username, password);
}
 
源代码19 项目: hesperides   文件: LdapUserRepository.java
private static LdapSearchContext createLdapSearchContext(LdapAuthenticationProvider ldapAuthenticationProvider, UsernamePasswordAuthenticationToken auth) {
    String username = auth.getName();
    String password = (String) auth.getCredentials();
    return ldapAuthenticationProvider.createLdapSearchContext(username, password);
}
 
@Test(expected = BadCredentialsException.class)
public void testAuthBasicBad() throws Exception {

    final AuthenticationManager manager = this.context.mock(AuthenticationManager.class);
    final HttpServletRequest request = this.context.mock(HttpServletRequest.class);

    final ConnectorAuthStrategyBasicAuth auth = new ConnectorAuthStrategyBasicAuth();

    auth.setAuthenticationManager(manager);

    final UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("üsernäme", "pä$sw()rd");
    final String basic = token.getPrincipal() + ":" + token.getCredentials();
    final byte[] encodedBytes = Base64.encodeBase64(basic.getBytes(StandardCharsets.UTF_8));


    this.context.checking(new Expectations() {{
        allowing(request).getHeader("Authorization"); will(returnValue("Basic " + new String(encodedBytes)));
        allowing(manager).authenticate(token); will(throwException(new BadCredentialsException("bad")));
    }});

    auth.authenticated(request);

}