为某些网址加载其他身份验证提供程序

时间:2018-10-24 14:19:55

标签: spring spring-security kotlin

我想为不同的URL加载不同的身份验证提供程序。例如,如果我的网址匹配“ / foo / something”,则加载FooProvider并输入“ bar / something”-> BarProvider。问题是当我点击“ bar / something” URL时,sessionScope参数(我在提供程序的构造函数中传递)仍然是“ foo”。这意味着FooProvider已加载,但这不是我期望的。 有什么我想念的吗?提前致谢。

 abstract class TokenAuthenticationProvider (
        protected val sessionScope: SessionScope
    ) : AuthenticationProvider { 

    private fun authenticateToken(authentication: TokenAuthentication): Authentication { 
        println("sessionScope $sessionScope")
    }
}

@Component
class FooAuthenticationProvider : TokenAuthenticationProvider (sessionScope = SessionScope.Foo)

@Component
class BarAuthenticationProvider : TokenAuthenticationProvider (sessionScope = SessionScope.Bar)


@Configuration
@EnableWebSecurity
class WebSecurityConfiguration @Autowired constructor(
    private val fooProvider: FooProvider,
    private val barProvider: BarProvider,
    private val authFilter: AuthFilter,
    private val corsFilter: CustomCorsFilter
) : WebSecurityConfigurerAdapter() {

    override fun configure(http: HttpSecurity) {

        ... 

        http.authorizeRequests()
            .antMatchers("foo/**")
            .fullyAuthenticated()
            .and()
            .authenticationProvider(fooProvider)

        http.authorizeRequests()
            .antMatchers("bar/**")
            .fullyAuthenticated()
            .and()
            .authenticationProvider(barProvider)

          ... 
    }

    override fun configure(auth: AuthenticationManagerBuilder) {
        auth.authenticationProvider(fooProvider)
        auth.authenticationProvider(barProvider)
    }
}

1 个答案:

答案 0 :(得分:0)

您需要配置两个WebSecurityConfigurerAdapter,并在antMatcher的顶层添加一个HttpSecurity

@Configuration
@Order(1)
class FooWebSecurityConfiguration(val provider: FooProvider) : WebSecurityConfigurerAdapter() {

    override fun configure(http: HttpSecurity) {
        http.antMatcher("/foo/**")
            .authorizeRequests()
            .antMatchers("/foo/**")
            .fullyAuthenticated()
            .and()                
            .authenticationProvider(provider)
    }
}

@Configuration
@Order(2)
class BarWebSecurityConfiguration(val provider: BarProvider) : WebSecurityConfigurerAdapter() {

    override fun configure(http: HttpSecurity) {
        http.antMatcher("/bar/**")
            .authorizeRequests()
            .antMatchers("/bar/**")
            .fullyAuthenticated()              
            .and()
            .authenticationProvider(provider)
    }
}