英文:
How to access Principal in controller methods without it declared as argument?
问题
我在Rest API上添加了Spring Security和JWT身份验证。现在我需要从令牌中检索一些数据,无论是用户名还是其他信息,在每个控制器方法中都需要 - 无论是用户名还是其他信息。
由于几乎所有的控制器方法都需要一个Principal
变量,是否有一种方法可以避免将其声明为每个方法的参数?
我曾经使用过 ObjectProvider
来做类似的事情,例如:
@RequestScope
@Component
public class MyObj // ...
用法:
@Component
public class OtherObj {
@Autowired
private ObjectProvider<MyObj> provider;
// ...
@Override
public boolean meth() throws Exception {
MyObj o = provider.getIfAvailable();
// ...
但我发现如果没有实例存在,它会被创建,而不是返回null
或抛出异常。
英文:
I added Spring Security on a Rest API with JWT authentication. Now I need to retrieve some data from the token in every controller method - be it either the username or other information.
Since almost all of my controller methods would need a Principal
variable, is there a way to avoid declaring it as an argument to each method?
I once used ObjectProvider
to do a similar thing, like:
@RequestScope
@Component
public class MyObj // ...
Usage:
@Component
public class OtherObj {
@Autowired
private ObjectProvider<MyObj> provider;
// ...
@Override
public boolean meth() throws Exception {
MyObj o = provider.getIfAvailable();
// ...
But there I found that if no instance exists, it is created instead of being returned null
or an exception being thrown.
答案1
得分: 1
你可以创建一个实用类,它为你提供了主体。
public static Principal getPrincipal() {
SecurityContext securityContext = SecurityContextHolder.getContext();
return securityContext.getAuthentication().getPrincipal();
}
当然,在这里你需要添加空值检查,以防上下文或认证为空。
英文:
You can create one utility class, which provides you the principal.
public static Principal getPrincipal() {
SecurityContext securityContext = SecurityContextHolder.getContext();
return securityContext.getAuthentication().getPrincipal();
}
Ofcourse, here you would need to put the null checks in case the context or authentication is null.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论