访问路由报错401,就说明安全框架自带的登录验证我们还没有取消。

首先需要创建一个类继承抽象类

WebSecurityConfigurerAdapter

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
                .authorizeRequests()
                .anyRequest().permitAll()
                .and()
                .formLogin()
                .and()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
        http.exceptionHandling().accessDeniedHandler(new SimpleAccessDeniedHandler());
 }
 }

其中

.authorizeRequests() .anyRequest().permitAll()

//任意请求允许无授权访问


.csrf().disable()

//禁用跨站csrf攻击防御,否则无法登录成功

配置完成之后,我发现还是报错401。

仔细排查之后发现,由于我是多模块的布局格式,忘记扫描这个类所在的包了,添加扫描即可

@ComponentScan

@MapperScan("com.operative.**.mapper")
@ComponentScan(basePackages = {"com.operative.core","com.operative.auth","com.operative.main"})
@SpringBootApplication
public class MainApplication {
    public static void main(String[] args) {
        SpringApplication.run(MainApplication.class,args);
    }
}

不过好像不需要添加

@ComponentScan

也行,等后续知道了再进行补充


如果自己写了登录之后发现又启用了框架自带的登录

删掉

.and().formLogin()

即可

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
                .authorizeRequests()
                .anyRequest().permitAll()
//                .and()
//                .formLogin()
                .and()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
        http.exceptionHandling().accessDeniedHandler(new SimpleAccessDeniedHandler());
    }


Spring boot + Spring Security实现权限管理——参考链接



版权声明:本文为LJWWD原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/LJWWD/article/details/119145706