在这个Spring Boot应用程序中,有一个Web服务,它为登录用户返回一些数据:
@RequestMapping("/resource")
public Map<String, Object> home() {
Map<String, Object> model = new HashMap<String, Object>();
model.put("id", UUID.randomUUID().toString());
model.put("content", "Hello World");
return model;
}
Run Code Online (Sandbox Code Playgroud)
想象一下,该方法的返回值取决于当前登录的用户.
如何找出该方法中登录的用户?
Rom*_*ner 84
按要求:
在内部使用Spring Security的 Spring Boot 提供了一个SecurityContextHolder类,它允许通过以下方式查找当前经过身份验证的用户:
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
Run Code Online (Sandbox Code Playgroud)
该认证实例现在提供了以下方法:
getPrincipal()getCredentials()getAuthorities()getDetails()Nik*_*ilP 12
您也可以简单地使用HttpServletRequest获取用户原则,
使用HttpServletRequest请求,
String user=request.getUserPrincipal().getName();
Run Code Online (Sandbox Code Playgroud)
Nik*_*laB 11
从Spring Security 3.2开始,您可以UserDetails通过在控制器方法内添加参数来获得当前登录的用户(您的实现):
import org.springframework.security.web.bind.annotation.AuthenticationPrincipal;
@RequestMapping("/resource")
public Map<String, Object> home(@AuthenticationPrincipal User user) {
..
}
Run Code Online (Sandbox Code Playgroud)
替换User为实现UserDetails接口的类的名称。
编辑:
由于Spring Security 4.0批注已移至其他软件包:
import org.springframework.security.core.annotation.AuthenticationPrincipal;
Run Code Online (Sandbox Code Playgroud)
从 5.2 版开始,您可以使用CurrentSecurityContext注释:
@GetMapping("/hello")
public String hello(@CurrentSecurityContext(expression="authentication?.name")
String username) {
return "Hello, " + username + "!";
}
Run Code Online (Sandbox Code Playgroud)
一种方法是将java.security.Principal添加为参数,如下所示:
@RequestMapping("/resource")
public Map<String, Object> home(Principal principal) {
Map<String, Object> model = new HashMap<String, Object>();
model.put("id", UUID.randomUUID().toString());
model.put("content", "Hello " + principal.getName());
return model;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
55013 次 |
| 最近记录: |