spring-mvc - Spring Boot 应用程序无法访问休息路径
问题描述
我正在尝试为 spring boot 设置规则以允许/拒绝对特定路径的访问。我查找了各种示例和堆栈溢出问题,但没有一个有用。我创建的配置文件如下:
package xyz.blackmonster.window.configs;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
@EnableWebSecurity
@Configuration
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
@Value("${admin.console.username:admin}")
private String username;
@Value("${admin.console.password:admin}")
private String password;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser(username)
.password(passwordEncoder().encode(password)).roles("ADMIN");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/", "/assets/**", "/api/order/calculate", "/api/order/**").permitAll()
.antMatchers("/admin/**").hasRole("ADMIN")
.and()
.formLogin()
.loginPage("/login.html")
.defaultSuccessUrl("/admin/orders.html")
.failureUrl("/login.html?error=true")
.and()
.logout().logoutSuccessUrl("/");
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
我可以毫无问题地访问“/”。在 MVC 控制器的帮助下加载并显示页面。但是我定义为 REST 端点的路径,我无法访问它们。我不断收到 403 响应:
{"timestamp":"2018-10-08T19:22:04.963+0000","status":403,"error":"Forbidden","message":"Forbidden","path":"/api/order /计算”}
我的配置有什么问题?正如你在课堂上看到的那样,我什至更进一步,专门设置了计算端点,而不是让 ** 包含所有子路径。
解决方案
如果“/”有效而“/api/order/calculate”无效,则意味着它们有不同的HTTP动词。
"/" - is a GET request
"/api/order/calculate" - is a POST request
默认情况下,spring security 将启用 csrf 保护(仅适用于 POST,因为 GET 被认为是安全的)。如果您收到 403,则表示您没有发送 csrf 标头 => 您的访问被禁止。
你说这是一个 REST 端点,所以你应该为这个端点禁用 csrf。为此,请使用以下命令更新您的配置:
1.一般禁用csrf(如果你有web表单,不推荐)
http.csrf()
.disable();
2.如果您只需要忽略特定端点的csrf,您可以添加:
http.csrf()
.ignoringAntMatchers("/api/order/calculate")
推荐阅读
- pseudocode - 在未排序的数组中查找特定数量的频率
- wordpress - 下载 sql 文件/db 作为备份,发现在 wordpress 页面或帖子中找不到的乱码。该怎么办?
- ruby - 我需要用 ah`ash 中的值替换数组中的哈希键
- azure-ad-b2c - Azure AD B2C - b2clogin 的示例代码模块
- html - 以不同的方式对具有相同类名的多个 div 进行样式设置
- assembly - 提示用户输入,计算字符串长度和重新打印输入
- python - 如何使用 python sympy 用 3 个方程求解 3 个未知数
- c# - 使用本地数据库时的 Entity Framework Core 错误
- r - 如何将数据从 mql4 (metatrader) 导入到 r 以实现自动化?
- architecture - cpu如何知道硬件中断?