下面列出了org.springframework.security.core.userdetails.UserDetails#getUsername ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
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;
}
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;
}
@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;
}
/**
* 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;
}
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);
}
/**
* 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());
}
@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);
}
}
@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:/";
}
/**
* 在这里查询我们用户,构建用户的授权信息
*
* @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);
}
/**
* 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;
}
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) + "'");
}
}
/**
* 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;
}
/**
* 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;
}
@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);
}
@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);
}
@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);
}
@Override
public SocialUserDetails loadUserByUserId(String username) throws UsernameNotFoundException {
UserDetails details = userDetailsManager.loadUserByUsername(username);
return new SocialUser(details.getUsername(), "", AuthorityUtils.createAuthorityList("USER"));
}
@Override
public SocialUserDetails loadUserByUserId(String userId) throws UsernameNotFoundException, DataAccessException {
UserDetails userDetails = userDetailsService.loadUserByUsername(userId);
return new SocialUser(userDetails.getUsername(), userDetails.getPassword(), userDetails.getAuthorities());
}
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;
}
static String createToken(UserDetails userDetails) {
long expires = System.currentTimeMillis() + 1000L * 60 * 60;
return userDetails.getUsername() + ":" + expires + ":"
+ computeSignature(userDetails, expires);
}