首页 > 解决方案 > 在使用 OAuth2 保护应用程序的同时,我想公开一些可供任何人访问的 URL

问题描述

在我创建了一个小型Spring Boot 2.2.6应用程序并将AWS Cognito配置为身份验证提供程序后,一切正常。访问任何应用程序的 URL 时,我会被重定向到 Cognito,登录后,应用程序运行良好。

我尝试添加一些不需要任何身份验证的公共页面(/api/**)。首先我尝试了这个:

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .antMatchers("/api/**").permitAll();  // This should be permitted for anyone

但是,现在,一切都是开放的。一点安全感都没有。哎呀。

我将其更改为:

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .antMatchers("/api/**").permitAll()  // This should be permitted for anyone
                .anyRequest().authenticated();       // Everything else should be protected

现在,列入白名单的 URL (/api/**) 运行良好,无需密码。但是所有其他 URL(例如 /private)不会将我重定向到登录页面,而是会产生 403 错误:

出现意外错误(类型=禁止,状态=403)。拒绝访问

有谁知道如何保持原始行为(密码)但很少有匿名访问的 URL?

标签: spring-bootspring-securityamazon-cognito

解决方案


WebSecurityConfigurerAdapter另一种方法可以用来忽略某些 url:

@Override
public void configure(WebSecurity web) throws Exception {
     web.ignoring().antMatchers("/api/**");
}

推荐阅读