Vadim Fedorenko
Vadim Fedorenko

Reputation: 2571

SecurityContextHolder.getContext().getAuthentication() returns String

I was working on security layer in my Spring Boot project and faced with the following problem:

SecurityContextHolder.getContext().getAuthentication() 

This code returns:

So, I want to configure this code to return UserDetails for both cases. How can I do it?

As I guess, I need to implement custom AnonymousAuthenticationFilter. Am I correct?

Upvotes: 2

Views: 2960

Answers (1)

Ali Dehghani
Ali Dehghani

Reputation: 48193

As I guess, I need to implement custom AnonymousAuthenticationFilter. Am I correct?

There is a simpler approach and that's the anonymous() method of the HttpSecurity DSL. Just use that block to set your desired principal:

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    // other configuration methods

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        UserDetails anonymousUserDetails = // your custom UserDetails for anonymous case
        http
                // other configurations
                .anonymous()
                    .principal(anonymousUserDetails);
    }
}

Using a Null Object Pattern-ish approach may be a good idea for that custom implemention for anonymous user.

Upvotes: 3

Related Questions