gpt4 book ai didi

spring-security - Spring Boot 使用 CSRF token 和 BasicAuth 保护相同端点

转载 作者:行者123 更新时间:2023-12-05 02:14:57 26 4
gpt4 key购买 nike

我有一个 Spring Boot REST 应用程序,它有两个主要部分:

  • 我想用 token 保护 ajax 调用的 UI
  • 我希望拥有基本身份验证的公共(public)端点

据我所知,我无法使用 CSRF token 保护公共(public)端点,因为它们需要 session 。问题是,某些端点需要两者都可以访问,那么当 UI 使用它时如何使用 CSRF 保护它们并为基本身份验证禁用 CSRF?

这是我目前拥有的,我完全禁用 csrf 以便基本工作...

http.requestMatchers().antMatchers("/form/fill", "/form/fill/*", "/form/fillParams", "/form/fillParams/*").and()
.csrf().disable().authorizeRequests().anyRequest().hasAnyRole(SecurityConfiguration.ROLE_FORMS_AUTHOR,
SecurityConfiguration.ROLE_FORM_FILLER, SecurityConfiguration.ROLE_ADMIN)
.and().httpBasic();

编辑:我找到了 this旧答案,我想知道是否有一种方法可以在我的案例中利用它,但我仍然不确定如何区分“本地”用户和使用 httpBasic() 进行身份验证的用户

最佳答案

在您的 Spring Security java 配置文件中,您可以如下配置 HttpSecurity 对象,以便仅对某些请求启用 CSRF 检查(默认情况下对所有请求启用传入请求和禁用将禁用所有传入请求,因此请求 Mather 可以在此处帮助您找到要启用或禁用 csrf 的路径。)。

确保通过端点或多个路径将 /urls-with-csrf-check/** 替换为您的路径..

 @Override
protected void configure(HttpSecurity http) throws Exception {

RequestMatcher csrfRequestMatcher = new RequestMatcher() {
private RegexRequestMatcher requestMatcher =
new RegexRequestMatcher("/urls-with-csrf-check/**", null);

public boolean matches(HttpServletRequest httpServletRequest) {
if (requestMatcher.matches(httpServletRequest)) {
return true;
}
return false;
}
};

http.requestMatchers().antMatchers("/form/fill", "/form/fill/*", "/form/fillParams", "/form/fillParams/*").and()
.csrf()
.requireCsrfProtectionMatcher(csrfRequestMatcher)
.and()
.authorizeRequests().anyRequest().hasAnyRole(SecurityConfiguration.ROLE_FORMS_AUTHOR, SecurityConfiguration.ROLE_FORM_FILLER, SecurityConfiguration.ROLE_ADMIN)
.and().httpBasic();
}

关于spring-security - Spring Boot 使用 CSRF token 和 BasicAuth 保护相同端点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52854865/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com