springboot获取当前登录用户
时间: 2023-04-24 09:00:28 浏览: 73
要获取当前登录用户,可以使用Spring Security框架。Spring Security提供了一个SecurityContextHolder类,可以用来获取当前用户的信息。
首先,在pom.xml文件中添加Spring Security的依赖:
```
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>5.2.2.RELEASE</version>
</dependency>
```
然后,在Spring Boot的配置类中添加@EnableWebSecurity注解,启用Spring Security:
```
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
// ...
}
```
接下来,在控制器中注入Authentication对象,就可以获取当前登录用户的信息了:
```
@RestController
public class UserController {
@GetMapping("/user")
public String getUser(Authentication authentication) {
return "当前登录用户:" + authentication.getName();
}
}
```
在上面的代码中,getName()方法返回当前用户的用户名。如果需要获取更多的用户信息,可以使用getPrincipal()方法获取Principal对象,然后强制转换为具体的用户类型。