如何在控制器方法中访问未声明为参数的 Principal?

huangapple go评论110阅读模式
英文:

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&lt;MyObj&gt; 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.

huangapple
  • 本文由 发表于 2020年7月26日 18:51:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/63099129.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定