Spring Boot应用程序无法访问休息路径

时间:2018-10-08 19:26:05

标签: spring-mvc spring-boot spring-security

我正在尝试为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响应:

  

{“时间戳”:“ 2018-10-08T19:22:04.963 + 0000”,“状态”:403,“错误”:“禁止”,“消息”:“禁止”,“路径”:“ / api / order / calculate“}

我的配置有什么问题?从课堂上可以看到,我什至更进一步,专门设置了计算终点,以反对让**包括所有子路径。

1 个答案:

答案 0 :(得分:0)

如果“ /”有效,而“ / 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(如果您具有网络表单,则不建议使用)

http.csrf()
     .disable();

2。如果仅需要对特定端点忽略csrf,则可以添加:

http.csrf()
    .ignoringAntMatchers("/api/order/calculate")