Home > Net >  Spring Security work with Chrome but allow GET from Postman without authorization
Spring Security work with Chrome but allow GET from Postman without authorization

Time:11-03

i have problem with my spring security implemntation. I have some basic configuration of UserDetails and UserDetailsService.I've done some Endpoints and some Security Configuration with WebSecurityConfigurerAdapter. Everything works fine on chrome - if you try to access an secured endpoint security cofniugration redirects you to login form and after login redirects you to yours /api. But in postman when sending even GET request authorization not working and you can fetch reposonse with all data that sould be availabe only for admin or after authorization.

Here is my Security Configuration

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@Configuration
@EnableWebSecurity
@EnableTransactionManagement
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
    @Autowired
    AuthenticationSuccessHandler successHandler;

    @Autowired
    UserDetailsService userDetailsService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http./*sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).
                and().*/
                    authorizeRequests()
                    .antMatchers("/api/players").hasAnyRole("ADMIN")
                    .antMatchers("/api/organizers").hasAnyRole("ADMIN")
                    .antMatchers("/api/events").permitAll()
                    .antMatchers("/h2-console/**").permitAll()
                .and()
                    .formLogin()
                    .successHandler(successHandler)
                    .permitAll()
                .and()
                    .logout()
                    .permitAll()
                /*.and()
                .csrf().disable()*/;
    }
    @Bean
    public PasswordEncoder getPasswordEncoder() {return NoOpPasswordEncoder.getInstance();}

}

and configuration for sample GET endpoint

@RestController
@RequestMapping(value="/api",produces = MediaType.APPLICATION_JSON_VALUE)
@RequiredArgsConstructor
public class UserViewRestContoller {
    @NonNull
    private final UserQuery query;

    @GetMapping(value="/players")
    @PreAuthorize("hasRole('ADMIN')")
    List<PlayerView> getPlayers() {
        return query.listPlayers();
    }

    @GetMapping(value="players/{userId}",produces = MediaType.APPLICATION_JSON_VALUE)
    @PreAuthorize("#userId == authentication.principal.userId or hasRole('ADMIN')")
    PlayerDetails getPlayer(@PathVariable UUID userId){
        return query.getPlayerDetails(userId);
    }

So in browser accesing /api/players you will see

enter image description here

and in POSTMAN

enter image description here

CodePudding user response:

Did you enable global method security?

@EnableGlobalMethodSecurity(
  prePostEnabled = true, 
  securedEnabled = true, 
  jsr250Enabled = true)

Also I don't see any JWT token implementation in the code. How are you getting admin role and authorize it. Where do you get Admin role?

CodePudding user response:

Ok i have found a problem that was in definition of antMatchers.

 .antMatchers("/api/players")

ONLY secures /api/players

NOT /api/players/ and /api/players/**

the proper ant matchers should be

 .antMatchers("/api/players/**").hasAnyRole("ADMIN")
              
  • Related