Java Code Examples for org.springframework.security.core.userdetails.UserDetails#getPassword()

The following examples show how to use org.springframework.security.core.userdetails.UserDetails#getPassword() . 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: CustomUserDetailsService.java    From SpringSecurity-JWT-Vue-Deom with MIT License 6 votes vote down vote up
@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("用户名不存在,请检查用户名或注册!");
}
 
Example 2
Source File: BaseUserDetailsService.java    From jump-the-queue with Apache License 2.0 6 votes vote down vote up
@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;
  }
}
 
Example 3
Source File: RecoveryAuthenticationProviderImpl.java    From molgenis with GNU Lesser General Public License v3.0 6 votes vote down vote up
@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;
}
 
Example 4
Source File: TokenAuthenticationProvider.java    From molgenis with GNU Lesser General Public License v3.0 6 votes vote down vote up
@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;
}
 
Example 5
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 6
Source File: TokenBasedRememberMeServices.java    From jasypt with Apache License 2.0 5 votes vote down vote up
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) + "'");
    }
    
}
 
Example 7
Source File: SpringSecurityUtils.java    From lemon with Apache License 2.0 5 votes vote down vote up
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);
}
 
Example 8
Source File: AccountAuthenticationProvider.java    From spring-boot-oauth2-password-flow with Apache License 2.0 5 votes vote down vote up
@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.");
    }
}
 
Example 9
Source File: MockMvcTests.java    From Spring with Apache License 2.0 5 votes vote down vote up
@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());
}
 
Example 10
Source File: SpringSecurityUtils.java    From lemon with Apache License 2.0 5 votes vote down vote up
/**
 * 将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);
}
 
Example 11
Source File: TokenUtils.java    From Spring with Apache License 2.0 5 votes vote down vote up
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())));
}
 
Example 12
Source File: DhisWebSpringTest.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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()
    );
}
 
Example 13
Source File: TweetsController.java    From twissandra-j with Apache License 2.0 5 votes vote down vote up
@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:/";
}
 
Example 14
Source File: RunAsUserTokenFactory.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
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);
}
 
Example 15
Source File: SecurityRequestPostProcessors.java    From maven-framework-project with MIT License 5 votes vote down vote up
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());
}
 
Example 16
Source File: TokenBasedRememberMeServices.java    From jasypt with Apache License 2.0 4 votes vote down vote up
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;
    
}
 
Example 17
Source File: LoginAuthenticationFilter.java    From mall4j with GNU Affero General Public License v3.0 4 votes vote down vote up
@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;
}
 
Example 18
Source File: SimpleSocialUsersDetailService.java    From blog-social-login-with-spring-social with Apache License 2.0 4 votes vote down vote up
@Override
public SocialUserDetails loadUserByUserId(String userId) throws UsernameNotFoundException, DataAccessException {
    UserDetails userDetails = userDetailsService.loadUserByUsername(userId);
    return new SocialUser(userDetails.getUsername(), userDetails.getPassword(), userDetails.getAuthorities());
}
 
Example 19
Source File: MethodSecurityApplicationTests.java    From Spring with Apache License 2.0 4 votes vote down vote up
private void installAuthentication(String username) {
	UserDetails principal = this.userDetailsService.loadUserByUsername(username);
	Authentication authentication = new UsernamePasswordAuthenticationToken(principal, principal.getPassword(), principal.getAuthorities());
	SecurityContextHolder.getContext().setAuthentication(authentication);
}
 
Example 20
Source File: TokenAuthenticationProvider.java    From ChengFeng1.5 with MIT License 4 votes vote down vote up
@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;
}