Authentication object is null after bypassing the particular request

758 Views Asked by At

The below Code I used in webConfigSecurity class to bypass some requests from the client

@Override
public void configure(WebSecurity webSecurity) throws Exception
{
    webSecurity.ignoring().antMatchers("/adminSettings/get/**")
             .antMatchers("/cases/sayHello/**").antMatchers("/cases/**/downloadPdfFolderPBC/**");
}

In the controller api method requires the user details for further execution, while getting the user details the authentication object is null, so it throws an exception that "user is not authenticated"

 public static User get() {
        final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null) {
            UserPrincipal principal = (UserPrincipal) authentication.getPrincipal();
            if (principal == null) {
                throw new InsufficientAuthenticationException("User not authenticated");
            }
            return principal.getUser();
        }
        throw new AuthenticationCredentialsNotFoundException("User not authenticated");
    }

I'm new to spring security, In this case, what I should do to get logged user details

1

There are 1 best solutions below

0
On

Instead of ignoring(), which causes Spring Security to skip those requests, I believe you want to use permitAll() instead like so:

@Override
public void configure(HttpSecurity http) throws Exception {
    http
        .authorizeRequests((requests) -> requests
            .antMatcher("/adminSettings/get/**").permitAll()
            .antMatcher("/cases/sayHello/**").permitAll()
            // ... etc
            .anyRequest().authenticated()
        )
        .formLogin(Customizer.withDefaults());
}

In this way, Spring Security will still populate the SecurityContextHolder with the logged-in user, but none of the permitAll endpoints will require authentication.