【问题标题】:Disable Basic Authentication for a specific URL Spring禁用特定 URL Spring 的基本身份验证
【发布时间】:2017-04-15 16:47:10
【问题描述】:

我是 Spring 新手,我需要为我的 REST 控制器的 8/10 URL 启用基本身份验证,另外 2 个应该可以在没有任何基本身份验证的情况下访问。 我正在使用 gradle 通过应用程序构建,因此不涉及任何 xml 文件。 (我看到了一些带有 web.xml 的解决方案,我没有) 这是我的网络安全配置:

 @Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

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

    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().withUser("user").password("password");

    }
}

这是我的控制器:

    @RestController
@RequestMapping(value = "/abcd")
public class PaymentController implements ElasticSearchConstants {

    @RequestMapping(value = "/sample", method = RequestMethod.POST, consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
    public static void authExpemtedController(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //do something
    }
}

我试过 web.ignoring().antMatchers("/abcd/");没有帮助。当我从邮递员那里尝试时,我总是收到 401 错误: { “时间戳”:1492274727955, “状态”:401, “错误”:“未经授权”, "message": "访问该资源需要完全认证", “路径”:“/abcd/样本” }

我需要公开这样的 API,不需要任何身份验证,而其他 API 需要进行身份验证。

提前感谢您的帮助

更新: 我知道 http.authoriseRequest().antMatchers("/abcd").permitAll() 此方法只允许任何用户访问。我根本不想将任何用户信息传递给此 API。

【问题讨论】:

    标签: java spring authentication


    【解决方案1】:

    您可能想参考Section 5.4 Authorize Requests of the Spring Security docs

    我们的示例只要求对用户进行身份验证,并且对我们应用程序中的每个 URL 都进行了验证。我们可以通过向我们的 http.authorizeRequests() 方法添加多个子项来为我们的 URL 指定自定义要求。例如:

    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()                                                                                    
                .antMatchers("/resources/**", "/signup", "/about").permitAll()                                  
                .antMatchers("/admin/**").hasRole("ADMIN")                                                  
                .antMatchers("/db/**").access("hasRole('ADMIN') and hasRole('DBA')")                        
                .anyRequest().authenticated()
                .and()
            // ...
            .formLogin();
    }
    

    【讨论】:

    • 我已经尝试过此选项,但无法正常工作。仍然遇到同样的问题。我给了 http .authorizeRequests() .antMatchers("/abcd/**").permitAll() .anyRequest().authenticated();
    猜你喜欢
    • 1970-01-01
    • 2019-05-31
    • 2018-06-15
    • 1970-01-01
    • 2017-12-22
    • 2016-11-05
    • 2013-02-11
    • 2020-03-29
    • 1970-01-01
    相关资源
    最近更新 更多