How do I instantiate java.security.Principal? All the subclasses are deprecated

2.6k views Asked by At

I have a Spring API service which accepts Principal.

public ResponseEntity<ApiCustomResponse> create(Principal principal, UrlInfoData urlinfo) throws ApiException;

The Principal is created automatically by Spring for OAuth2 API calls. I would like to use the same service for the web page admin interface.

@Autowired
private IShortUrlService apiService;
...
    Principal principal = new Principal();
    apiService.create(principal, urlinfo);

I want to instantiate the Principal with the current logged in admin user's name. However, all the instantiating classes are deprecated. How can I instantiate a Principal to pass to the service?

https://docs.oracle.com/javase/8/docs/api/java/security/Principal.html

1

There are 1 answers

1
AudioBubble On BEST ANSWER

Since java.security.Principal is an interface, why don't you implement it?

Principal principal = new Principal() {

        @Override
        public String getName() {
            return adminName;
        }

    }
apiService.create(principal, urlinfo);

Also, you can get the Principal for the current logged in user with: SecurityContextHolder.getContext().getAuthentication().getPrincipal()