首页 > 解决方案 > 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 /计算”}

我的配置有什么问题?正如你在课堂上看到的那样,我什至更进一步,专门设置了计算端点,而不是让 ** 包含所有子路径。

标签: spring-mvcspring-bootspring-security

解决方案


如果“/”有效而“/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")

推荐阅读