Java Code Examples for org.springframework.security.authentication.UsernamePasswordAuthenticationToken#getCredentials()

The following examples show how to use org.springframework.security.authentication.UsernamePasswordAuthenticationToken#getCredentials() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: CustomUserDetailsAuthenticationProvider.java    From tutorials with MIT License 6 votes vote down vote up
@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;
}
 
Example 2
Source File: CustomUserDetailsAuthenticationProvider.java    From spring-microservice-exam with MIT License 6 votes vote down vote up
@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));
}
 
Example 3
Source File: CustomUserDetailsAuthenticationProvider.java    From spring-microservice-exam with MIT License 6 votes vote down vote up
/**
  * 加载用户信息
  *
  * @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;
 }
 
Example 4
Source File: UmAuthenticationChecker.java    From wecube-platform with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example 5
Source File: SimpleHashUtil.java    From Roothub with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * 这个方法很重要,用于认证用户提供的信息是否正确,
 * 并且返回一个 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());
}
 
Example 6
Source File: CustomAuthenticationProvider.java    From oauth2-server with MIT License 6 votes vote down vote up
@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"));
        }
    }
}
 
Example 7
Source File: AccountAuthenticationProvider.java    From spring-data-fundamentals with Apache License 2.0 6 votes vote down vote up
@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");
}
 
Example 8
Source File: AccountAuthenticationProvider.java    From skeleton-ws-spring-boot with Apache License 2.0 6 votes vote down vote up
@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");
}
 
Example 9
Source File: DatabaseAuthenticationProvider.java    From WebApplication-Project-Skeleton with MIT License 6 votes vote down vote up
@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;
}
 
Example 10
Source File: UserDetailsAuthenticationProviderImpl.java    From spring-backend-boilerplate with Apache License 2.0 6 votes vote down vote up
/**
 * 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);
	}
}
 
Example 11
Source File: UserDetailsAuthenticationProviderImpl.java    From spring-backend-boilerplate with Apache License 2.0 6 votes vote down vote up
/**
 * 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);
	}
}
 
Example 12
Source File: TokenAuthenticationProvider.java    From securing-rest-api-spring-security with Apache License 2.0 5 votes vote down vote up
@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));
}
 
Example 13
Source File: LdapAuthenticationProvider.java    From hesperides with GNU General Public License v3.0 5 votes vote down vote up
@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);
}
 
Example 14
Source File: InMemoryAuthentificationProvider.java    From gravitee-management-rest-api with Apache License 2.0 5 votes vote down vote up
@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"));
    }
}
 
Example 15
Source File: RepositoryAuthenticationProvider.java    From gravitee-management-rest-api with Apache License 2.0 5 votes vote down vote up
@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"));
	}
}
 
Example 16
Source File: CustomUserDetailsAuthenticationProvider.java    From multitenancy with Apache License 2.0 5 votes vote down vote up
@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;
}
 
Example 17
Source File: UmAuthenticationChecker.java    From wecube-platform with Apache License 2.0 5 votes vote down vote up
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.");
	}
}
 
Example 18
Source File: CrustAuthenticationProvider.java    From Milkomeda with MIT License 5 votes vote down vote up
@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"));
    }
}
 
Example 19
Source File: LdapUserRepository.java    From hesperides with GNU General Public License v3.0 4 votes vote down vote up
private static LdapSearchContext createLdapSearchContext(LdapAuthenticationProvider ldapAuthenticationProvider, UsernamePasswordAuthenticationToken auth) {
    String username = auth.getName();
    String password = (String) auth.getCredentials();
    return ldapAuthenticationProvider.createLdapSearchContext(username, password);
}
 
Example 20
Source File: ConnectorAuthStrategyBasicAuthTest.java    From yes-cart with Apache License 2.0 4 votes vote down vote up
@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);

}