Spring security 多个 httpSecurities:表单登录未被重定向

时间:2021-04-25 11:51:11

标签: spring-boot spring-security

我有以下配置。一个用于表单登录,另一个用于 Rest API 的基本身份验证。问题是如果用户没有登录,它不会被重定向到登录页面。而是询问 HTTP 登录/密码提示窗口。

@Configuration
@EnableWebSecurity
public class WebSecurityConfig {

    @Autowired
    protected void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth
                .inMemoryAuthentication()
                .withUser("user").password("{noop}12345").roles("API_USER").and()
                .withUser("admin").password("{noop}12345").roles("USER", "ADMIN");
    }

    @Configuration
    @Order(Ordered.HIGHEST_PRECEDENCE)
    public static class ApiWebSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter {
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http
                    .authorizeRequests()
                    .antMatchers("/api/**").hasAuthority("ROLE_API_USER")
                    .anyRequest().authenticated()
                    .and()
                    .httpBasic()
                    .and()
                    .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
        }
    }

    @Configuration
    public static class FormLoginWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http
                    .authorizeRequests()
                    .antMatchers("/", "/home").permitAll()
                    .antMatchers("/admin/**").hasRole("ADMIN")
                    .anyRequest().authenticated()
                    .and()
                    .formLogin().permitAll()
                    .and()
                    .logout().permitAll();
        }
    }
}

0 个答案:

没有答案