Combining basic authentication and form login for the same REST Api

前端 未结 2 1415
鱼传尺愫
鱼传尺愫 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!

提交回复
热议问题