测试知识整理合集Java相关

SpringBoot 项目访问接口跳转到默认登录页

2021-10-22  本文已影响0人  思念_似水流年

问题场景:

今天在新建一个 SpringBoot 项目时,在项目启动成功后,发现接口请求时跳转到了默认的 login 登录页面,而不是 Controller 中指定的跳转链接。


SpringBoot 默认登录页
接口无法正常返回数据

问题原因:

在 SpringBoot 项目中使用了 SpringSecurity,而 SpringSecurity 默认是生效的,此时接口都是被保护的,我们需要通过验证才能正常访问接口。 SpringSecurity 提供了一个默认的用户,用户名是 user,而密码则是启动项目时自动生成的。
可以看到,在项目启动的日志中,会打印出一段生成安全密码的日志:


自动生成的安全密码

大部分情况下,我们都不需要使用 SpringSecurity 默认的登录页面来限制接口的访问,那么要怎么修改配置来解决呢?

解决方案:

方案一:

在启动类中添加注解,去掉 SpringSecurity:

@SpringBootApplication(exclude = {SecurityAutoConfiguration.class})
@MapperScan("com.sso.mbg.mapper")
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

重新启动项目,再发送请求,发现可以正常返回接口数据:


接口正常返回数据

方案二:

在项目中添加一个配置类做处理(推荐使用

package com.sso.security;

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;

/**
 * add by liunian
 */
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
//        super.configure(http);
        http.csrf().disable().cors();
        // 配置不需要登录验证
        http.authorizeRequests().anyRequest().permitAll().and().logout().permitAll();
    }
}

再次重启项目,调用接口,发现接口可以正常返回数据

适用方案:

一般选择第二种解决方案,新建一个 WebSecurityConfig 类继承 WebSecurityConfigurerAdapter,在 configure 方法中,指定过滤的规则,选择性地过滤掉部分不需要验证的接口。
如下所示:

@Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable().cors();
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

        HttpMethod permitHttpMethod = HttpMethod.OPTIONS;
        String[] permitAntPatterns = new String[]{
                "/",
                "/user/login",
                "/" + frontend + "/**",
                "/springboot-admin/**"
        };

        http.authorizeRequests()
                .antMatchers(permitHttpMethod).permitAll()
                .antMatchers(permitAntPatterns).permitAll()
                .anyRequest().authenticated();

    }
上一篇 下一篇

猜你喜欢

热点阅读