Combining basic authentication and form login for the same REST Api

前端 未结 2 1406
鱼传尺愫
鱼传尺愫 2020-12-01 04:44

Is there a way to set up basic authentication and form login for the same REST service? I\'d like to let logged in user trigger this service both through web browser after l

相关标签:
2条回答
  • 2020-12-01 05:00

    You can achieve this easily by using multiple http configuration as below, this code only explains multiple http configuration. I am assuming that you are well aware of the other essential configurations related to spring security e.g authenticationManger etc.

        @EnableWebSecurity
        public class MultiHttpSecurityCustomConfig {
            @Autowired
            public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
                auth.inMemoryAuthentication().withUser("user").password("password").roles("USER").and().withUser("admin").password("password")
                        .roles("USER", "ADMIN");
            }
    
            @Configuration
            @Order(1)
            public static class ApiWebSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter {
                protected void configure(HttpSecurity http) throws Exception {
                    http.antMatcher("/api/**").authorizeRequests().anyRequest().hasRole("ADMIN").and().httpBasic();
                }
            }
    
            @Configuration
            public static class FormLoginWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {
    
                @Override
                protected void configure(HttpSecurity http) throws Exception {
                    http.authorizeRequests().anyRequest().authenticated().and().formLogin();
                }
    
    
       }
    }
    

    Please refer spring security official link: Multiple HttpSecurity

    I will also reccomend you to check out Secure REST Services with Spring Security

    Feel free to comment if you encounter any problem!

    0 讨论(0)
  • 2020-12-01 05:08

    I found out that the previous code snippet is not working in Spring Security 5 because of an issue in the CSRF filter in the Basic authentication filter chain. It is possible to make it work by disabling CSRF for Basic auth.

    BTW the override of Basic auth by Form auth is because redirection to /error page which is caused by this CSRF filter issue.

            @Configuration
            @Order(1)
            public static class ApiWebSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter {
                protected void configure(HttpSecurity http) throws Exception {
                    http.antMatcher("/api/**")
                        .authorizeRequests()
                        .anyRequest()
                        .hasRole("ADMIN")
                        .and()
                        .httpBasic()
                        .csrf().disable();
                }
            }
    
    0 讨论(0)
提交回复
热议问题