登录成功后,在后续的业务逻辑汇总,可能还需要获取登录成功的用户对象,如果不使用任何安全管理框架,那么可以将用户信息保存在HttpSession中,以后需要的时候直接从HttpSession中获取数据。在SpringSecurity中,用户登录信息本质上还是保存在HttpSession中,但是为了方便使用,SpringSecurity对HttpSession中的用户信息进行了封装,封装之后若在想获取用户登录数据i就会有两种不同的思路:
(1) 从SecurityContextHolder中获取;
(2) 从当前请求对象中获取;
无论是那种获取方式,都离不开一个重要的对象:Authentication,在SpringSecurity中,Authentication对象主要有两方面的功能:
(1) 作为 AuthticationManager 的输入参数,提供用户身份认证的凭证,当他作为一个输入参数时,他的isAuthencated 方法返回 false,表示用户还未认证;
(2) 代表已经经过身份认证的用户,此时的 Authentication 可以从SecurityContext 中获取;
一个 Authentication 对象主要包括三个方面的信息:
(1) principal:定义认证的用户。如果用户使用用户名/密码的方式登录,principal 通常就是一个 UserDetails 对象;
(2) credentials:登录凭证,一般就是密码。当用户登录成功之后,登录凭证会被自动擦除,以防止泄露;
(3) authotities:用户被授予的权限信息;
// 继承自Principal类
public interface Authentication extends Principal, Serializable {
// 获取用户权限
Collection<? extends GrantedAuthority> getAuthorities();
// 获取用户凭证,一般就是凭证
Object getCredentials();
// 获取用户的详细信息,可能是当前的请求之类
Object getDetails();
// 获取当前的用户信息,可能是一个用户名,也可能是一个用户对象
Object getPrincipal();
// 当前用户是否认证成功
boolean isAuthenticated();
void setAuthenticated(boolean var1) throws IllegalArgumentException;
}
可以看到只要获取到Authentication对象,就可以获取到登录用户的详细信息。不同的认证方式对应不同的Authentication实例:

在这些Authentication实例中,最常用的两个:UsernamePasswordAuthenticationToken 和 RememberMeAuthenticationToken。其中 UsernamePasswordAuthenticationToken 代表表单登录时登录的用户信息,RememberMeAuthenticationToken 代表如果用户使用RememberMe登录,封装的登录信息。
登录页面 mylogin.html:
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>登录页面title>
head>
<body>
<h2>自定义登录页面h2>
<form action="/user/login" method="post">
<div th:text="${SPRING_SECURITY_LAST_EXCEPTION}">div>
<table>
<tr>
<td>用户名:td>
<td><input type="text" name="username">td>
tr>
<tr>
<td>密码:td>
<td><input type="password" name="password">td>
tr>
<tr>
<td colspan="2"><button type="submit">登录button>td>
tr>
table>
form>
body>
html>
配置文件application.yml:
spring:
security:
user:
name: zhangsan
password: 123456
配置 SecurityConfig 类:
@EnableWebSecurity(debug = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
// authorizeRequests() 方法表示开启权限配置
http.authorizeRequests()
// 表示所有的请求都要认证后才能访问
.anyRequest().authenticated()
// and()方法相当于又回到 HttpSecurity 实例,重新开启新一轮的配置。
.and()
// 开启表单登录配置
// loginProcessingUrl ,usernameParameter ,passwordParameter
// 和login.html中登录表单的配置一致,即action,用户名name属性值,密码name属性值;
.formLogin()
// 配置登录页面地址
.loginPage("/mylogin.html")
// 配置登录接口地址
.loginProcessingUrl("/user/login")
// 配置登录成功的跳转地址
.successHandler(jsonAthenticationSuccessHandler())
// 配置登录失败的跳转地址
.failureHandler(jsonAuthenticationFailureHandler())
// 登录用户名的参数名称
.usernameParameter("username")
// 登录密码的参数名称
.passwordParameter("password")
// 跟登录相关的页面和接口不做拦截,直接通过
.permitAll()
.and()
.csrf().disable();
}
private AuthenticationFailureHandler jsonAuthenticationFailureHandler() {
return (request, response, exception) -> {
response.setContentType("application/json;charset=utf-8");
Map<String, String> respMap = Map.of(
"code", "500",
"message", "登录失败" + exception.getMessage()
);
ObjectMapper objectMapper = new ObjectMapper();
String json = objectMapper.writeValueAsString(respMap);
response.getWriter().write(json);
};
}
private AuthenticationSuccessHandler jsonAthenticationSuccessHandler() {
return (request, response, authentication) -> {
response.setContentType("application/json;charset=utf-8");
Map<String, String> respMap = Map.of(
"code", "200",
"message", "登录成功"
);
ObjectMapper objectMapper = new ObjectMapper();
String json = objectMapper.writeValueAsString(respMap);
response.getWriter().write(json);
};
}
}
添加一个UserController类:
@RestController
public class UserController {
@GetMapping("/user")
public void userInfo(){
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
String name = authentication.getName();
Collection<? extends GrantedAuthority> authorities =
authentication.getAuthorities();
// 用户名
System.out.println("name = " + name);
// 角色
System.out.println("authorities = " + authorities);
}
}
启动项目,登录成功后,访问/user接口,控制台就会打印出登录用户信息,当然,由于我们目前没有给用户配置角色,所以默认的用户角色为空数组。
name = admin
authorities = []
SecurityContextHolder 是一个静态方法,意味着我们随时随地都可以获取到登录用户信息,在service层也可以获取到登录用户信息。
@RestController
public class UserController {
@RequestMapping("/authentication")
public void authentication(Authentication authentication){
System.out.println("authentication = " + authentication);
}
@RequestMapping("/principal")
public void principal(Principal principal){
System.out.println("principal = " + principal);
}
}
可以直接在 Controller 的请求参数中放入 Authentication 对象来获取登录用户想你想。Authentication 是 Principal的子类,所以也可以直接在请求参数中放入 Principal 来接收当前登录用户信息。
Controller中方法的参数都是当前请求的 HttpServletRequest 带来的,因此前面的 Authentication 和 Principal 参数都是 HttpServletRequest 带来的,那么这些数据是何时放入 HttpServletRequest 的呢?

如果使用了 SpringSecurity 框架,那么我们在Controller参数中拿到的 HttpServletRequest 实例将是 Servlet3SecurityContextHolderAwareRequestWrapper,这是被 SpringSecurity 封装过的请求。SecurityContextHolderAwareRequestWrapper源码:
public class SecurityContextHolderAwareRequestWrapper extends HttpServletRequestWrapper {
private final AuthenticationTrustResolver trustResolver;
private final String rolePrefix;
public SecurityContextHolderAwareRequestWrapper(HttpServletRequest request, String rolePrefix) {
this(request, new AuthenticationTrustResolverImpl(), rolePrefix);
}
public SecurityContextHolderAwareRequestWrapper(HttpServletRequest request, AuthenticationTrustResolver trustResolver, String rolePrefix) {
super(request);
Assert.notNull(trustResolver, "trustResolver cannot be null");
this.rolePrefix = rolePrefix;
this.trustResolver = trustResolver;
}
// 获取当前登录对象Authentication
private Authentication getAuthentication() {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
return !this.trustResolver.isAnonymous(auth) ? auth : null;
}
// 获取当前登录用户的用户名
// 如果Authentication对象中存储的Principal是当前登录用户对象,则返回用户名
// 如果Authentication对象中存储的Principal是当前登录用户名,则直接返回即可
public String getRemoteUser() {
Authentication auth = this.getAuthentication();
if (auth != null && auth.getPrincipal() != null) {
return auth.getPrincipal() instanceof UserDetails ? ((UserDetails)auth.getPrincipal()).getUsername() : auth.getPrincipal().toString();
} else {
return null;
}
}
// 返回当前登录对象,其实就是Authentication的实例
public Principal getUserPrincipal() {
Authentication auth = this.getAuthentication();
return auth != null && auth.getPrincipal() != null ? auth : null;
}
// 判断当前登录用户是否具备某一个指定的角色
// 先对传入进来的角色进行预处理,有的情况下可能需要添加ROLE_前缀
// 然后调用Authentication#getAuthorities方法,获取当前登录用户所具备的所有角色
// 最后再和传入进来的参数进行比较
private boolean isGranted(String role) {
Authentication auth = this.getAuthentication();
if (this.rolePrefix != null && role != null && !role.startsWith(this.rolePrefix)){
role = this.rolePrefix + role;
}
if (auth != null && auth.getPrincipal() != null) {
Collection<? extends GrantedAuthority> authorities = auth.getAuthorities();
if (authorities == null) {
return false;
} else {
Iterator var4 = authorities.iterator();
GrantedAuthority grantedAuthority;
do {
if (!var4.hasNext()) {
return false;
}
grantedAuthority = (GrantedAuthority)var4.next();
} while(!role.equals(grantedAuthority.getAuthority()));
return true;
}
} else {
return false;
}
}
// 调用isGranted方法,进而判断当前用户是否具备某一个指定角色的功能
public boolean isUserInRole(String role) {
return this.isGranted(role);
}
}
因此我们通过HttpServletRequest就可以获取到很多当前登录用户的信息了,代码如下:
@RestController
public class UserController {
@RequestMapping("/info")
public void info(HttpServletRequest request){
// 当前登录用户的用户名
String remoteUser = request.getRemoteUser();
Principal userPrincipal = request.getUserPrincipal();
Authentication authentication = (Authentication) userPrincipal;
// 判断当前用户是否具备某一个指定的角色
boolean admin = request.isUserInRole("admin");
// 登录用户的用户名
System.out.println("remoteUser = " + remoteUser);
System.out.println("authentication.getName():"+authentication.getName());
System.out.println("admin = " + admin);
}
}
打印结果:
remoteUser = zhangsan
authentication.getName():zhangsan
admin = false