Spring Security exclude url patterns in security annotation configurartion

后端 未结 4 1849
迷失自我
迷失自我 2020-11-29 01:23

I have spring web application with Spring security configured using java config approach. I want to exclude some URL patterns from authentication(eg: static resources etc..)

4条回答
  •  北海茫月
    2020-11-29 02:13

    Where are you configuring your authenticated URL pattern(s)? I only see one uri in your code.

    Do you have multiple configure(HttpSecurity) methods or just one? It looks like you need all your URIs in the one method.

    I have a site which requires authentication to access everything so I want to protect /*. However in order to authenticate I obviously want to not protect /login. I also have static assets I'd like to allow access to (so I can make the login page pretty) and a healthcheck page that shouldn't require auth.

    In addition I have a resource, /admin, which requires higher privledges than the rest of the site.

    The following is working for me.

    @Override
    protected void configure(HttpSecurity http) throws Exception {
    
        http.authorizeRequests()
            .antMatchers("/login**").permitAll()
            .antMatchers("/healthcheck**").permitAll()
            .antMatchers("/static/**").permitAll()
            .antMatchers("/admin/**").access("hasRole('ROLE_ADMIN')")
            .antMatchers("/**").access("hasRole('ROLE_USER')")
            .and()
                .formLogin().loginPage("/login").failureUrl("/login?error")
                    .usernameParameter("username").passwordParameter("password")
            .and()
                .logout().logoutSuccessUrl("/login?logout")
            .and()
                .exceptionHandling().accessDeniedPage("/403")
            .and()
                .csrf();
    
    }
    

    NOTE: This is a first match wins so you may need to play with the order. For example, I originally had /** first:

            .antMatchers("/**").access("hasRole('ROLE_USER')")
            .antMatchers("/login**").permitAll()
            .antMatchers("/healthcheck**").permitAll()
    

    Which caused the site to continually redirect all requests for /login back to /login. Likewise I had /admin/** last:

            .antMatchers("/**").access("hasRole('ROLE_USER')")
            .antMatchers("/admin/**").access("hasRole('ROLE_ADMIN')")
    

    Which resulted in my unprivledged test user "guest" having access to the admin interface (yikes!)

提交回复
热议问题