Home > Back-end >  Way to allow anonymous request to intermediate endpoint in spring security
Way to allow anonymous request to intermediate endpoint in spring security

Time:11-18

I have app that work with decks (decks of one trading card game).

My security config:

    @Bean //httpSecurity прототип
    public SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception {

        httpSecurity
            .authorizeRequests()
                .antMatchers("/", "/registration", "/css/**", "/images/**", "/static/**").permitAll()
                .anyRequest().authenticated()
                .and()
            .formLogin()
                .loginPage("/login")
                .permitAll()
                .and()
            .logout()
                .logoutSuccessUrl("/")
                .permitAll();
        return httpSecurity.build();
    }

and now I want to unsecure intermediate endpoint:

GET /decks <-- secured. return view with all decks of specified user
GET /decks/{id} <-- must be not secured. return single deck view by its id
GET /decks/{id}/edit <-- must be secured. return view for editing deck.

Is there are way to allow via Spring Security anonymous calls for GET /decks/{id}?

CodePudding user response:

Just add /decks/{\\d } in permiteAll statement.

CodePudding user response:

NOTE: If you are using Spring MVC, I recommend mvcMatchers instead of antMatchers for security reasons.

authorizeRequests works like catch blocks, with the larger scoped expressions at the bottom. So, to "catch" /decks/{id}, I'd do:

httpSecurity.authorizeRequests()
    .mvcMatchers("/", "/registration", ...).permitAll()
    .mvcMatchers("/decks/{id}").permitAll()
    .anyRequest().authenticated()

This will permit /decks/{id}, but not decks or /decks/{id}/*.

  • Related