0

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.

4

1 回答 1

1

您可以创建一个实用程序类,它为您提供主体。

public static Principal getPrincipal() {
    SecurityContext securityContext = SecurityContextHolder.getContext();
    return securityContext.getAuthentication().getPrincipal();
}

当然,如果上下文或身份验证为空,您需要在此处进行空检查。

于 2020-07-26T11:06:43.770 回答