watery
watery

Reputation: 5487

How to access Principal in controller methods without it declared as argument?

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.

Upvotes: 0

Views: 504

Answers (1)

Mubaraka Bharucha
Mubaraka Bharucha

Reputation: 206

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.

Upvotes: 1

Related Questions