【问题标题】:Spring boot security, applying an authentication filter only to certain routesSpring Boot 安全性,仅将身份验证过滤器应用于某些路由
【发布时间】:2016-12-17 00:34:14
【问题描述】:

我正在构建一个 Web 应用程序,它将在单个应用程序中包含一个 API 和一个管理界面。因此,我需要两种类型的身份验证,API 的基于令牌的身份验证和管理界面的基于表单的身份验证。

我几乎可以通过应用过滤器来验证 API 令牌来实现它,但是过滤器正在为每个请求执行,我只希望它在匹配“/api/**”的路径上执行。

希望从我的安全配置中可以清楚地看到我想要做什么,但遗憾的是它没有按预期工作。

所有 API 请求都将以“/api/”开头,而所有管理界面请求都将以“/admin/”开头。所以我希望对每个应用不同的安全规则。

@Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/api/account/login").permitAll();
        http.addFilterBefore(webServiceAuthenticationFilter, UsernamePasswordAuthenticationFilter.class).authorizeRequests().antMatchers("/api/**").hasAuthority("APIUSER");

        http.authorizeRequests().antMatchers("/admin/**").authenticated().and()
            .formLogin()
                .loginPage("/admin/account/login").permitAll()
                .passwordParameter("password")
                .usernameParameter("username")
                .failureUrl("/admin/account/login?error").permitAll()
                .defaultSuccessUrl("/admin/dashboard")
                .and()
            .logout()
                .logoutRequestMatcher(new AntPathRequestMatcher("/admin/account/logout"))
                .logoutSuccessUrl("/admin/account/login");

        http.exceptionHandling().accessDeniedPage("/admin/account/forbidden");
    }

【问题讨论】:

  • 我相信this 的话题可能很有趣。

标签: spring spring-security spring-boot


【解决方案1】:

有一种方法可以根据 url 配置多个 HttpSecuritys,方法是直接在 HttpSecurity 上使用 antMatcher(或更高级的情况下为 requestMatchers)(而不是在 authorizeRequests!)。见:https://docs.spring.io/spring-security/site/docs/current/apidocs/org/springframework/security/config/annotation/web/builders/HttpSecurity.html#antMatcher-java.lang.String-

这需要定义多个WebSecurityConfigurerAdapters 和定义的@Orders,以便Spring 根据给定的url 和配置的顺序使用第一个适当的配置。更多详情请查看http://docs.spring.io/spring-security/site/docs/current/reference/htmlsingle/#multiple-httpsecurity的文档

【讨论】:

  • 谢谢,这正是我所需要的。
  • @SheppardDigital 请考虑将其标记为答案,因此该问题不再被视为未解决问题(安德烈亚斯获得信用:-))。
【解决方案2】:

我不知道这是否是“正确”的做法,但我已经设法仅在路由与“/api/**”匹配时通过添加 if 来执行过滤器代码对过滤器本身的声明;

所以在我的过滤器中,我有以下内容;

AntPathMatcher urlMatch = new AntPathMatcher();
if (urlMatch.match("/api/**", httpRequest.getRequestURI().substring(httpRequest.getContextPath().length()))) {
    // Token authentication in here
}

【讨论】:

    猜你喜欢
    • 2020-02-09
    • 2023-03-19
    • 1970-01-01
    • 2016-11-13
    • 1970-01-01
    • 2019-02-21
    • 2016-10-12
    • 2019-03-13
    • 2014-07-06
    相关资源
    最近更新 更多