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

问题场景:

今天在新建一个 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 Shirly
 */
@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();

    }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容