首页 > 解决方案 > Spring Security 为两个不同的 url 配置两个不同的身份验证

问题描述

我正在开发一个带有 spring 安全性的 web 应用程序,它将被 web 用户和 android 用户使用。目前我已经配置WebSecurityConfigurerAdapter

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter{

@Autowired
private UserDetailsService userDetailsService;

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
            .antMatchers("/","/about","/contact","/v1/**").permitAll()
            .antMatchers("/admin/otp").hasRole("PRE_AUTH_USER")
            .antMatchers("/admin/**").hasAnyRole("SuperAdmin","BackOffice")
            .antMatchers("/admin/dashboard/**").hasAnyRole("BankAdmin","CallAdmin")
            //.antMatchers("/api/**").hasRole("FieldPerson")
            .anyRequest().authenticated();

    http.formLogin()
            .loginPage("/admin/login")
            .permitAll()
            .defaultSuccessUrl("/admin/otp", true)
            .and()
        .logout()
            .logoutSuccessUrl("/admin/login")
            .permitAll();

    http.exceptionHandling().accessDeniedPage("/error/403");
}

@Bean
public DaoAuthenticationProvider authProvider(){
    DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();
    authProvider.setUserDetailsService(userDetailsService);
    authProvider.setPasswordEncoder(new BCryptPasswordEncoder(12));
    return authProvider;
}

@Autowired
public void registerAuthentication(AuthenticationManagerBuilder auth) throws Exception {
    auth.userDetailsService(userDetailsService);
}

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception{
    auth.userDetailsService(userDetailsService).and().authenticationProvider(authProvider());
}
}

这很完美,但我想在没有任何 otp 验证屏幕的情况下使用相同的配置进行 rest api 身份验证(基本上它是一个带有 GOOGLE Authenticator 的网络用户的 2FA)。所以我想为android用户配置数据库身份验证。我尝试了这个解决方案,但我因user is not anonymous. 基本上我只想在用户点击它时配置/api/**它应该被授权。

标签: restspring-bootspring-security

解决方案


推荐阅读