首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何通过url模式配置不同的身份验证过滤器?

如何通过url模式配置不同的身份验证过滤器?
EN

Stack Overflow用户
提问于 2019-06-06 10:08:00
回答 2查看 1.2K关注 0票数 0

我有一个spring引导应用程序,它主要提供REST端点,使用JWT。我希望在secret1中使用JWT来对/I_ API /**API进行身份验证,而使用JWT对其他secret2进行身份验证。我不知道如何配置这个场景。需要两个SecurityConfig类来配置吗?

代码语言:javascript
复制
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
class SecurityConfig : WebSecurityConfigurerAdapter() {

    override fun configure(http: HttpSecurity) {
        http.csrf().disable()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .antMatchers("/internal_api/**")
                .addFilterAt(JwtTokenAuthFilter("secret1"), UsernamePasswordAuthenticationFilter::class.java)
                .authorizeRequests()
                .anyRequest().permitAll()
    }
}

我希望使用JWT(secret1)的用户可以访问/JwtTokenAuthFilter_api/**(通过JwtTokenAuthFilter("secret1")),使用JWT(secret2)可以访问/other_resource/** (通过JwtTokenAuthFilter("secret2") )

EN

Stack Overflow用户

回答已采纳

发布于 2019-06-12 02:31:24

通过这些天的在线搜索,我终于找到了一个更好的实现。

按弹簧正式文件推荐方法。

创建和自定义过滤器链部分:

许多应用程序对一组资源具有与另一组完全不同的访问规则。例如,承载UI和支持API的应用程序可能支持基于cookie的身份验证,将其重定向到UI部件的登录页面,并支持基于令牌的身份验证,对API部件未经身份验证的请求作出401响应。每一组资源都有自己的WebSecurityConfigurerAdapter,具有唯一的顺序和自己的请求匹配器。如果匹配规则重叠,最早排序的过滤链将获胜。

代码语言:javascript
复制
class  SecurityConfig {
  @Configuration
  @Order(SecurityProperties.BASIC_AUTH_ORDER - 10)
  class InternalApiConfig: WebSecurityConfigurerAdapter() {

    override fun configure(http: HttpSecurity) {
        http.antMatcher("/internal_api/**")
        http.authorizeRequests()
               .antMatchers("/internal_api/**").authenticated()
        http.addFilterAt(JwtTokenAuthFilter("secret1"), UsernamePasswordAuthenticationFilter::class.java)
    }
  }

  @Configuration
  @Order(SecurityProperties.BASIC_AUTH_ORDER - 9)
  class ApiConfig : WebSecurityConfigurerAdapter() {

    override fun configure(http: HttpSecurity) {
        http.authorizeRequests()
               .antMatchers("/other_resource/**").authenticated()

        http.addFilterAt(JwtTokenAuthFilter("secret2"), UsernamePasswordAuthenticationFilter::class.java)

    }
  }
}
票数 0
EN
查看全部 2 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56475359

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档