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

The following examples show how to use org.springframework.security.core.userdetails.UserDetails#getUsername() . 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: UiUser.java    From haven-platform with Apache License 2.0 6 votes vote down vote up
public static UiUser fromDetails(UserDetails details) {
    UiUser user = new UiUser();
    String username = details.getUsername();
    user.setUser(username);
    if(details instanceof ExtendedUserDetails) {
        ExtendedUserDetails eud = (ExtendedUserDetails) details;
        user.setTitle(eud.getTitle());
        user.setTenant(eud.getTenant());
        user.setEmail(eud.getEmail());
    }
    user.setPassword(details.getPassword() == null? null : PWD_STUB);
    Collection<? extends GrantedAuthority> authorities = details.getAuthorities();
    List<UiRole> roles = authorities.stream().map(UiRole::fromAuthority).collect(Collectors.toList());
    roles.sort(null);
    user.setRoles(roles);
    user.setTenant(MultiTenancySupport.getTenant(details));
    user.setAccountNonExpired(details.isAccountNonExpired());
    user.setAccountNonLocked(details.isAccountNonLocked());
    user.setCredentialsNonExpired(details.isCredentialsNonExpired());
    user.setEnabled(details.isEnabled());
    return user;
}
 
Example 2
Source File: CustomLogoutHandler.java    From Spring-5.0-Cookbook with MIT License 6 votes vote down vote up
protected String targetUrl(Authentication authentication) {
UserDetails p = (UserDetails )authentication.getPrincipal();
String username = p.getUsername();
      String password = p.getPassword();
  
      String url = "";
      Collection<? extends GrantedAuthority> authorities = p.getAuthorities();
      List<String> roles = new ArrayList<String>();
      for (GrantedAuthority a : authorities) {
          roles.add(a.getAuthority());
      }
      System.out.println("logout handler" + roles);
             
      if (isUser(roles)) {
          url = "/after_logout.html?message="+"Thank your, "+ username +" with password " + password +" and role(s): " + roles;
      } else if (isAdmin(roles)){
      	 url = "/after_logout.html?message="+"Thank your, "+ username +" with password " + password +" and role(s): " + roles;
      } else if (isHrAdmin(roles)){
      	 url = "/after_logout.html?message="+"Thank your, "+ username +" with password " + password +" and role(s): " + roles;
      } else{   	
    url = "/after_logout.html?message="+"Thank you, friend!";
      }
      return url;
  }
 
Example 3
Source File: JsonFileAuthorizationProvider.java    From geowave with Apache License 2.0 6 votes vote down vote up
@Override
public String[] getAuthorizations() {
  final Authentication auth = SecurityContextHolder.getContext().getAuthentication();
  if (auth == null) {
    return new String[0];
  }
  final Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
  String userName = principal.toString();
  if (principal instanceof UserDetails) {
    // most likely type of principal
    final UserDetails userDetails = (UserDetails) principal;
    userName = userDetails.getUsername();
  }
  final List<String> auths = authorizationSet.findAuthorizationsFor(userName);
  final String[] result = new String[auths.size()];
  auths.toArray(result);
  return result;
}
 
Example 4
Source File: AuthenticationController.java    From botanic-ng with Apache License 2.0 5 votes vote down vote up
@RequestMapping(value = "/api/info", method = { RequestMethod.GET })
public AuthenticationToken info() {

	final String username = SecurityContextHolder.getContext().getAuthentication().getName();
	final UserDetails details = this.userDetailsService.loadUserByUsername(username);

	final List<String> roles = new ArrayList<>();

	for (GrantedAuthority authority : details.getAuthorities()) {
		roles.add(authority.toString());
	}

	return new AuthenticationToken(details.getUsername(), roles);
}
 
Example 5
Source File: ConsoleIndex.java    From eagle with Apache License 2.0 5 votes vote down vote up
@ResponseBody
@RequestMapping(value = "/user", method = RequestMethod.HEAD)
public void getLoginUser(HttpServletResponse response) {
    UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    String userName = userDetails.getUsername();
    if (Strings.isNullOrEmpty(userName)) {
        AuthenticatUtil.needAuthenticate(response);
        return;
    }
    AuthenticatUtil.authenticateSuccess(response, userName);
}
 
Example 6
Source File: SecurityUtils.java    From tutorials with MIT License 5 votes vote down vote up
/**
 * Get the login of the current user.
 *
 * @return the login of the current user
 */
public static String getCurrentUserLogin() {
    SecurityContext securityContext = SecurityContextHolder.getContext();
    Authentication authentication = securityContext.getAuthentication();
    String userName = null;
    if (authentication != null) {
        if (authentication.getPrincipal() instanceof UserDetails) {
            UserDetails springSecurityUser = (UserDetails) authentication.getPrincipal();
            userName = springSecurityUser.getUsername();
        } else if (authentication.getPrincipal() instanceof String) {
            userName = (String) authentication.getPrincipal();
        }
    }
    return userName;
}
 
Example 7
Source File: SecurityUtils.java    From expper with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Get the login of the current user.
 */
public static String getCurrentUserLogin() {
    SecurityContext securityContext = SecurityContextHolder.getContext();
    Authentication authentication = securityContext.getAuthentication();
    String userName = null;
    if (authentication != null) {
        if (authentication.getPrincipal() instanceof UserDetails) {
            UserDetails springSecurityUser = (UserDetails) authentication.getPrincipal();
            userName = springSecurityUser.getUsername();
        } else if (authentication.getPrincipal() instanceof String) {
            userName = (String) authentication.getPrincipal();
        }
    }
    return userName;
}
 
Example 8
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 9
Source File: SecurityUtils.java    From flair-engine with Apache License 2.0 5 votes vote down vote up
/**
 * Get the login of the current user.
 *
 * @return the login of the current user
 */
public static String getCurrentUserLogin() {
    SecurityContext securityContext = SecurityContextHolder.getContext();
    Authentication authentication = securityContext.getAuthentication();
    String userName = null;
    if (authentication != null) {
        if (authentication.getPrincipal() instanceof UserDetails) {
            UserDetails springSecurityUser = (UserDetails) authentication.getPrincipal();
            userName = springSecurityUser.getUsername();
        } else if (authentication.getPrincipal() instanceof String) {
            userName = (String) authentication.getPrincipal();
        }
    }
    return userName;
}
 
Example 10
Source File: SmsTokenGranter.java    From spring-security-oauth2-demo with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 在这里查询我们用户,构建用户的授权信息
 *
 * @param client 客户端
 * @param tokenRequest tokenRequest
 * @return OAuth2Authentication
 */
@Override
protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) {
    Map<String, String> params = tokenRequest.getRequestParameters();
    String sms = params.getOrDefault("sms", "");
    UserDetails userDetails = userDetailsService.loadUserByUsername(sms);
    if (Objects.isNull(userDetails)) {
        throw new UsernameNotFoundException("用户不存在");
    }
    Authentication user = new UsernamePasswordAuthenticationToken(userDetails.getUsername(),
            userDetails.getPassword(), userDetails.getAuthorities());
    return new OAuth2Authentication(tokenRequest.createOAuth2Request(client), user);
}
 
Example 11
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 12
Source File: LoginSuccessListener.java    From spring-microservice-exam with MIT License 5 votes vote down vote up
@Override
public void onApplicationEvent(CustomAuthenticationSuccessEvent event) {
	// 登录成功后的处理
	UserDetails userDetails = event.getUserDetails();
	if (userDetails instanceof CustomUserDetails) {
		CustomUserDetails customUserDetails = (CustomUserDetails) userDetails;
		String tenantCode = customUserDetails.getTenantCode();
		String username = userDetails.getUsername();
		log.info("Login success, username: {} , tenantCode: {}", username, tenantCode);
		// 记录日志
		Log logInfo = new Log();
		logInfo.setTitle("用户登录");
		logInfo.setCommonValue(username, SysUtil.getSysCode(), tenantCode);
		logInfo.setTime(String.valueOf(System.currentTimeMillis() - customUserDetails.getStart()));
		logInfo.setType(CommonConstant.STATUS_NORMAL);
		ServletRequestAttributes requestAttributes = currentRequestAttributes();
		if (requestAttributes != null) {
			HttpServletRequest request = requestAttributes.getRequest();
			logInfo.setMethod(request.getMethod());
			logInfo.setRequestUri(request.getRequestURI());
			// 获取ip、浏览器信息
			logInfo.setIp(request.getRemoteAddr());
			logInfo.setUserAgent(request.getHeader(HttpHeaders.USER_AGENT));
		}
		logInfo.setServiceId(ServiceConstant.AUTH_SERVICE);
		// 记录日志和登录时间
		UserDto userDto = new UserDto();
		userDto.setId(customUserDetails.getId());
		userDto.setIdentifier(username);
		userDto.setLoginTime(DateUtils.asDate(LocalDateTime.now()));
		saveLoginInfo(logInfo, userDto);
	}
}
 
Example 13
Source File: GrafanaUserDetailsService.java    From Insights with Apache License 2.0 5 votes vote down vote up
/**
 * used to loads user-specific data.
 *
 */
@Override
public UserDetails loadUserByUsername(String login) {
	log.debug(" In GrafanaUserDetailsService Grafana ...... ");
	BCryptPasswordEncoder encoder = passwordEncoder();
	UserDetails user = GrafanaUserDetailsUtil.getUserDetails(request);
	return new org.springframework.security.core.userdetails.User(user.getUsername(),
			encoder.encode(user.getPassword()), user.getAuthorities());
}
 
Example 14
Source File: UserDetailsFormatter.java    From hawkbit with Eclipse Public License 1.0 5 votes vote down vote up
private static String formatUserName(final int expectedNameLength, final UserDetails userDetails) {
    if (!(userDetails instanceof UserPrincipal)) {
        return userDetails.getUsername();
    }

    final UserPrincipal userPrincipal = (UserPrincipal) userDetails;
    return trimAndFormatDetail(userPrincipal.getLoginname(), expectedNameLength);
}
 
Example 15
Source File: SecurityUtils.java    From jhipster-ribbon-hystrix with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Get the login of the current user.
 *
 * @return the login of the current user
 */
public static String getCurrentUserLogin() {
    SecurityContext securityContext = SecurityContextHolder.getContext();
    Authentication authentication = securityContext.getAuthentication();
    String userName = null;
    if (authentication != null) {
        if (authentication.getPrincipal() instanceof UserDetails) {
            UserDetails springSecurityUser = (UserDetails) authentication.getPrincipal();
            userName = springSecurityUser.getUsername();
        } else if (authentication.getPrincipal() instanceof String) {
            userName = (String) authentication.getPrincipal();
        }
    }
    return userName;
}
 
Example 16
Source File: SimpleSocialUserDetailsService.java    From pazuzu-registry with MIT License 4 votes vote down vote up
@Override
public SocialUserDetails loadUserByUserId(String username) throws UsernameNotFoundException {
    UserDetails details = userDetailsManager.loadUserByUsername(username);
    return new SocialUser(details.getUsername(), "", AuthorityUtils.createAuthorityList("USER"));
}
 
Example 17
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 18
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 19
Source File: TokenUtils.java    From Spring with Apache License 2.0 4 votes vote down vote up
static String createToken(UserDetails userDetails) {
	long expires = System.currentTimeMillis() + 1000L * 60 * 60;
	return userDetails.getUsername() + ":" + expires + ":"
			+ computeSignature(userDetails, expires);
}
 
Example 20
Source File: AbstractUserDetailsAuthenticationProvider.java    From Taroco with Apache License 2.0 4 votes vote down vote up
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    String username = authentication.getPrincipal() == null ? "NONE_PROVIDED" : authentication.getName();
    boolean cacheWasUsed = true;
    UserDetails user = this.userCache.getUserFromCache(username);
    if (user == null) {
        cacheWasUsed = false;

        try {
            user = this.retrieveUser(username, authentication);
        } catch (UsernameNotFoundException var6) {
            log.error("User \'" + username + "\' not found");
            if (this.hideUserNotFoundExceptions) {
                throw new BadCredentialsException(this.messages.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
            }

            throw var6;
        }

        Assert.notNull(user, "retrieveUser returned null - a violation of the interface contract");
    }

    try {
        this.preAuthenticationChecks.check(user);
        this.additionalAuthenticationChecks(user, authentication);
    } catch (AuthenticationException var7) {
        if (!cacheWasUsed) {
            throw var7;
        }

        cacheWasUsed = false;
        user = this.retrieveUser(username, authentication);
        this.preAuthenticationChecks.check(user);
        this.additionalAuthenticationChecks(user, authentication);
    }

    this.postAuthenticationChecks.check(user);
    if (!cacheWasUsed) {
        this.userCache.putUserInCache(user);
    }

    Object principalToReturn = user;
    if (this.forcePrincipalAsString) {
        principalToReturn = user.getUsername();
    }

    return this.createSuccessAuthentication(principalToReturn, authentication, user);
}