【Spring Security】Postman调用时无授权与CSRF验证

713 阅读1分钟

前言

配置了Spring Security时,Postman调用相关接口,报401显示无授权,返回体要么是登录页:

在这里插入图片描述

要么只返回一个

1

实现

相关依赖


        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>

实现

Security默认启用了Basic Auth授权,应该在Postman的Authorization页签中设置Basic Auth授权基本信息,设置用户名和密码: 在这里插入图片描述

由于Postman无法用Authorization页签中填上的Basic Auth相关信息生成 CSRF Token,因此需要将CSRF 验证关掉:

设定配置如下: WebSecurityConfig.java

import org.springframework.context.annotation.Configuration;
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;

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
            .antMatchers("/swagger-ui.html").permitAll()
            .antMatchers("/webjars/**").permitAll()
            .antMatchers("/swagger-resources/**").permitAll()
            .antMatchers("/v2/*").permitAll()
            .antMatchers("/csrf").permitAll()
            .antMatchers("/").permitAll()
            .antMatchers("/login").permitAll()
            .anyRequest().authenticated()
            .and()
            .csrf().disable()
            .formLogin()
        ;
    }
}

运行

重新启动服务

调用登录接口尝试登录 在这里插入图片描述 调用自己的接口

在这里插入图片描述

成功调用

参考

www.cnblogs.com/xuruiming/p…