org.springframework.security.core.userdetails.UserDetails#getPassword ( )源码实例Demo

下面列出了org.springframework.security.core.userdetails.UserDetails#getPassword ( ) 实例代码,或者点击链接到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
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    for (UserDetails userDetails : userList) {
        if (userDetails.getUsername().equals(username)) {
            // 此处我尝试过直接返回 user
            // 但是这样的话,只有后台服务启动后第一次登陆会有效
            // 推出后第二次登陆会出现  Empty encoded password 的错误,导致无法登陆
            // 这样写就不会出现这种问题了
            // 因为在第一次验证后,用户的密码会被清除,导致第二次登陆系统拿到的是空密码
            // 所以需要new一个对象或将原对象复制一份
            // 这个解决方案来自 https://stackoverflow.com/questions/43007763/spring-security-encoded-password-gives-me-bad-credentials/43046195#43046195
            return new User(userDetails.getUsername(), userDetails.getPassword(), userDetails.getAuthorities());
        }
    }
    throw new UsernameNotFoundException("用户名不存在,请检查用户名或注册!");
}
 
源代码3 项目: molgenis   文件: TokenAuthenticationProvider.java
@Override
@RunAsSystem
public Authentication authenticate(Authentication authentication) {
  if (!supports(authentication.getClass()))
    throw new IllegalArgumentException("Only RestAuthenticationToken is supported");

  RestAuthenticationToken authToken = (RestAuthenticationToken) authentication;

  if (authToken.getToken() != null) {
    UserDetails userDetails =
        tokenService.findUserByToken(authToken.getToken()); // Throws UnknownTokenException
    userDetailsChecker.check(userDetails);
    // if token is invalid
    authToken =
        new RestAuthenticationToken(
            userDetails,
            userDetails.getPassword(),
            userDetails.getAuthorities(),
            authToken.getToken());
  }

  return authToken;
}
 
@Override
public Authentication authenticate(Authentication authentication) {
  if (!supports(authentication.getClass())) {
    throw new IllegalArgumentException("Only RecoveryAuthenticationToken is supported");
  }

  RecoveryAuthenticationToken authToken = (RecoveryAuthenticationToken) authentication;

  if (authToken.getRecoveryCode() != null) {
    recoveryService.useRecoveryCode(authToken.getRecoveryCode());
    UserDetails userDetails =
        (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

    authToken =
        new RecoveryAuthenticationToken(
            userDetails,
            userDetails.getPassword(),
            userDetails.getAuthorities(),
            authToken.getRecoveryCode());
  } else {
    throw new BadCredentialsException("Invalid recovery code or code already used");
  }

  return authToken;
}
 
源代码5 项目: jump-the-queue   文件: BaseUserDetailsService.java
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

  Set<GrantedAuthority> authorities = getAuthorities(username);
  UserDetails user;
  try {
    user = getAmBuilder().getDefaultUserDetailsService().loadUserByUsername(username);
    User userData = new User(user.getUsername(), user.getPassword(), authorities);
    return userData;
  } catch (Exception e) {
    e.printStackTrace();
    UsernameNotFoundException exception = new UsernameNotFoundException("Authentication failed.", e);
    LOG.warn("Failed to get user {}.", username, exception);
    throw exception;
  }
}
 
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {

	DecodedJWT jwt = ((UserToken)authentication).getToken();



	boolean expire=jwt.getExpiresAt().before(new Date());

	if(expire)
		throw new TokenException("Token 已经失效");

	String username = jwt.getSubject();

	UserDetails user = userService.getUserLoginInfo(username);

	if(user == null || user.getPassword()==null)
		throw new TokenException("Token 已经失效");
	String encryptSalt = user.getPassword();
	try {
           Algorithm algorithm = Algorithm.HMAC256(encryptSalt);
           JWTVerifier verifier = JWT.require(algorithm)
                   .withSubject(username)
                   .build();
           verifier.verify(jwt.getToken());
       } catch (Exception e) {
           throw new BadCredentialsException("Token 认证失败", e);
       }
	UserToken token = new UserToken(user, jwt, user.getAuthorities());

	return token;
}
 
private UsernamePasswordAuthenticationToken authentication(ServletContext servletContext) {
	ApplicationContext context = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
	UserDetailsService  userDetailsService = userDetailsService(context);
	UserDetails userDetails = userDetailsService.loadUserByUsername(this.username);
	return new UsernamePasswordAuthenticationToken(
			userDetails, userDetails.getPassword(), userDetails.getAuthorities());
}
 
源代码8 项目: molgenis   文件: RunAsUserTokenFactory.java
public RunAsUserToken create(
    String key, UserDetails userDetails, Class<? extends Authentication> originalAuthentication) {
  userDetailsChecker.check(userDetails);
  return new RunAsUserToken(
      key,
      userDetails.getUsername(),
      userDetails.getPassword(),
      userDetails.getAuthorities(),
      originalAuthentication);
}
 
源代码9 项目: twissandra-j   文件: TweetsController.java
@RequestMapping(value="/register", method=RequestMethod.POST)
public String register(Model model,
		@RequestParam("j_username")String username, 
		@RequestParam("j_password")String password1, 
		@RequestParam("j_password2")String password2 
) {
	if (username == null || username.isEmpty()) {
		return registrationError("username cannot be emtpy", model);
	}
	boolean existing = m_tweetRepository.getPassword(username) != null;
	if (existing) {
		return registrationError("user " + username + " already exists!", model);
	}
	if (password1 == null) {
		return registrationError("Password cannot be null", model);
	}
	if (!password1.equals(password2)) {
		return registrationError("Password1 and Password2 must match", model);
	}
	
	m_tweetRepository.saveUser(username, password1);
	
	UserDetails userDetails = m_userManager.loadUserByUsername(username);
	Authentication auth = new UsernamePasswordAuthenticationToken (userDetails.getUsername (),userDetails.getPassword (),userDetails.getAuthorities ());
	SecurityContextHolder.getContext().setAuthentication(auth);

	return "redirect:/";
}
 
源代码10 项目: dhis2-core   文件: DhisWebSpringTest.java
protected UsernamePasswordAuthenticationToken getPrincipal( String... authorities )
{
    User user = createAdminUser( authorities );
    List<GrantedAuthority> grantedAuthorities = user.getUserCredentials().getAllAuthorities()
        .stream().map( SimpleGrantedAuthority::new ).collect( Collectors.toList() );

    UserDetails userDetails = new org.springframework.security.core.userdetails.User(
        user.getUserCredentials().getUsername(), user.getUserCredentials().getPassword(), grantedAuthorities );

    return new UsernamePasswordAuthenticationToken(
        userDetails,
        userDetails.getPassword(),
        userDetails.getAuthorities()
    );
}
 
源代码11 项目: jasypt   文件: TokenBasedRememberMeServices.java
public void onLoginSuccess(final HttpServletRequest request, final HttpServletResponse response,
        final Authentication successfulAuthentication) {

    if (this.digester == null) {
        throw new IllegalStateException("Service incorrectly initialized: a " +
                "digester has not been set. A value must be specified for the \"digester\"" +
                " property in service of class " + this.getClass().getName());
    }
    
    String username = null;
    String password = null;
    
    if (successfulAuthentication.getPrincipal() instanceof UserDetails) {
        final UserDetails userDetails = (UserDetails) successfulAuthentication.getPrincipal();
        username = userDetails.getUsername();
        password = userDetails.getPassword();
    } else {
        username = successfulAuthentication.getPrincipal().toString();
        password = (successfulAuthentication.getCredentials() == null? null : successfulAuthentication.getCredentials().toString());
    }

    if (CommonUtils.isEmpty(username) || CommonUtils.isEmpty(password)) {
        // both user name and password have to be non-empty. No cookie to be added
        return;
    }

    final int tokenValiditySeconds = getTokenValiditySeconds();
    final long expiryTime = 
        System.currentTimeMillis() + 1000L* (tokenValiditySeconds < 0 ? TWO_WEEKS_S : tokenValiditySeconds);

    final String signature = this.digester.digest(getSignatureData(expiryTime, username, password));

    setCookie(new String[] {username, Long.toString(expiryTime), signature}, tokenValiditySeconds, request, response);

    if (this.logger.isDebugEnabled()) {
        this.logger.debug("Added remember-me cookie for user '" + username + "', expiry: '" + new Date(expiryTime) + "'");
    }
    
}
 
源代码12 项目: Spring   文件: TokenUtils.java
private static String computeSignature(UserDetails userDetails, long expires) {
	String signature = "";
	signature += (userDetails.getUsername()) + (":");
	signature += (expires) + (":");
	signature += (userDetails.getPassword()) + (":");
	signature += (TokenUtils.MAGIC_KEY);
	return new String(Hex.encode(MESSAGE_DIGEST.digest(signature.getBytes())));
}
 
源代码13 项目: lemon   文件: SpringSecurityUtils.java
/**
 * 将UserDetails保存到Security Context.
 * 
 * @param userDetails
 *            已初始化好的用户信息.
 * @param request
 *            用于获取用户IP地址信息,可为Null.
 */
public static void saveUserDetailsToContext(UserDetails userDetails,
        HttpServletRequest request) {
    PreAuthenticatedAuthenticationToken authentication = new PreAuthenticatedAuthenticationToken(
            userDetails, userDetails.getPassword(),
            userDetails.getAuthorities());

    if (request != null) {
        authentication.setDetails(new WebAuthenticationDetails(request));
    }

    SecurityContextHolder.getContext().setAuthentication(authentication);
}
 
源代码14 项目: Spring   文件: MockMvcTests.java
@Test
public void indexWhenSecurityContextThenOk() throws Exception {
	UserDetails user = new User("user", "password",
			AuthorityUtils.createAuthorityList("ROLE_USER"));
	Authentication auth = new UsernamePasswordAuthenticationToken(user,
			user.getPassword(), user.getAuthorities());
	SecurityContext context = new SecurityContextImpl();
	context.setAuthentication(auth);
	MockHttpServletRequestBuilder request = get("/").accept(MediaType.TEXT_HTML)
			.with(securityContext(context));
	this.mockMvc.perform(request).andExpect(status().isOk());
}
 
@Override
protected void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken token)
        throws AuthenticationException {
    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.");
    }
}
 
源代码16 项目: lemon   文件: SpringSecurityUtils.java
public static void saveUserDetailsToContext(UserDetails userDetails,
        HttpServletRequest request, SecurityContext securityContext) {
    PreAuthenticatedAuthenticationToken authentication = new PreAuthenticatedAuthenticationToken(
            userDetails, userDetails.getPassword(),
            userDetails.getAuthorities());

    if (request != null) {
        authentication.setDetails(new WebAuthenticationDetails(request));
    }

    securityContext.setAuthentication(authentication);
}
 
@Override
public SocialUserDetails loadUserByUserId(String userId) throws UsernameNotFoundException, DataAccessException {
    UserDetails userDetails = userDetailsService.loadUserByUsername(userId);
    return new SocialUser(userDetails.getUsername(), userDetails.getPassword(), userDetails.getAuthorities());
}
 
源代码18 项目: mall4j   文件: LoginAuthenticationFilter.java
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
    if (!ServletUtil.METHOD_POST.equals(request.getMethod())) {
        throw new AuthenticationServiceException(
                "Authentication method not supported: " + request.getMethod());
    }
    String requestBody = getStringFromStream(request);

    if (StrUtil.isBlank(requestBody)) {
        throw new AuthenticationServiceException("无法获取输入信息");
    }
    AdminAuthenticationToken adminAuthenticationToken  =  Json.parseObject(requestBody, AdminAuthenticationToken.class);


    String username = adminAuthenticationToken.getPrincipal() == null?"NONE_PROVIDED":adminAuthenticationToken.getName();


    String kaptchaKey = SecurityConstants.SPRING_SECURITY_RESTFUL_IMAGE_CODE + adminAuthenticationToken.getSessionUUID();

    String kaptcha = RedisUtil.get(kaptchaKey);

    RedisUtil.del(kaptchaKey);

    if(StrUtil.isBlank(adminAuthenticationToken.getImageCode()) || !adminAuthenticationToken.getImageCode().equalsIgnoreCase(kaptcha)){
        throw new ImageCodeNotMatchExceptionBase("验证码有误");
    }

    UserDetails user;
    try {
        user = yamiUserDetailsService.loadUserByUsername(username);
    } catch (UsernameNotFoundExceptionBase var6) {
        throw new UsernameNotFoundExceptionBase("账号或密码不正确");
    }

    String encodedPassword = user.getPassword();
    String rawPassword = adminAuthenticationToken.getCredentials().toString();

    // 密码不正确
    if (!passwordEncoder.matches(rawPassword,encodedPassword)){
        throw new BadCredentialsExceptionBase("账号或密码不正确");
    }

    if (!user.isEnabled()) {
        throw new UsernameNotFoundExceptionBase("账号已被锁定,请联系管理员");
    }
    AdminAuthenticationToken result = new AdminAuthenticationToken(user, adminAuthenticationToken.getCredentials());
    result.setDetails(adminAuthenticationToken.getDetails());
    return result;
}
 
源代码19 项目: jasypt   文件: TokenBasedRememberMeServices.java
protected UserDetails processAutoLoginCookie(final String[] cookieTokens, 
        final HttpServletRequest request, final HttpServletResponse response) {

    if (this.digester == null) {
        throw new IllegalStateException("Service incorrectly initialized: a " +
                "digester has not been set. A value must be specified for the \"digester\"" +
                " property in service of class " + this.getClass().getName());
    }
    
    if (cookieTokens.length != 3) {
        throw new InvalidCookieException("Wrong number of tokens in cookie");
    }

    final String usernameToken = cookieTokens[0];
    final String expiryToken = cookieTokens[1];
    final String digestedSignature = cookieTokens[2];
    
    long expiryTimestamp = -1;
    try {
        expiryTimestamp = new Long(expiryToken).longValue();
    } catch (NumberFormatException nfe) {
        throw new InvalidCookieException("Invalid cookie expiry token");
    }

    if (expiryTimestamp < System.currentTimeMillis()) {
        // Cookie has expired
        throw new InvalidCookieException("Cookie has expired (expired on '" + new Date(expiryTimestamp) + "'; current time is '" + new Date() + "')");
    }

    // Retrieve user details
    final UserDetails userDetails = 
        getUserDetailsService().loadUserByUsername(usernameToken);
    final String username = userDetails.getUsername();
    final String password = userDetails.getPassword();
    
    // Check signature data
    if (!this.digester.matches(getSignatureData(expiryTimestamp, username, password), digestedSignature)) {
        throw new InvalidCookieException("Cookie signature is not valid");
    }

    return userDetails;
    
}
 
源代码20 项目: Spring   文件: MethodSecurityApplicationTests.java
private void installAuthentication(String username) {
	UserDetails principal = this.userDetailsService.loadUserByUsername(username);
	Authentication authentication = new UsernamePasswordAuthenticationToken(principal, principal.getPassword(), principal.getAuthorities());
	SecurityContextHolder.getContext().setAuthentication(authentication);
}