SpringSecurity配置
当Springboot项目中添加了SpringSecurity时,其默认任何请请求都必须在登陆的状态。
任意接口都会跳转到一个莫名其妙的login登录页面
解决办法:
方法一:配置SpringSecurity配置类。
创建SecurityConfig配置类,并继承WebSecurityConfigurerAdapter
类,重写configure
方法。具体配置代码如下:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
// 定义白名单URL路径数组
private static final String URL_WHITELIST[] = {
"/login",
"/logout",
"/captcha",
"/password",
"/image/**",
"/test/**"
} ;
/**
* 配置应用程序的安全规则
* 开启跨域资源共享(CORS)功能,并关闭跨站请求伪造(CSRF)攻击防护
* 配置登录相关设置
* 禁用会话(session)的创建
* 配置拦截规则
* @param http HttpSecurity对象,用于配置应用程序的安全规则
* @throws Exception 配置过程中可能抛出的异常
*/
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.cors() // 开启CORS功能(跨域)
.and()
.csrf().disable() // 关闭CSRF攻击防护
.formLogin() // 配置登录相关设置
// .successHandler() // 自定义登录成功处理器(如果需要)
// .failureHandler() // 自定义登录失败处理器(如果需要)
// .and()
// .logout() // 配置注销设置(如果需要)
// .logoutSuccessHandler() // 自定义注销成功处理器(如果需要)
.and()
//session禁用配置
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS) // 禁用会话的创建(无状态)
.and()
.authorizeRequests()
.antMatchers(URL_WHITELIST).permitAll() // 白名单中的URL路径允许无需身份验证/permitAll放行所有
.anyRequest().authenticated(); // 其他所有请求需要身份验证
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
super.configure(auth);
}
}
方法二:排除安全自动配置SecurityAutoConfiguration.class
在启动类的添加@SpringBootApplication注解添加exclude = {SecurityAutoConfiguration.class}。
如下:
@SpringBootApplication(exclude = {SecurityAutoConfiguration.class})
@MapperScan("com.javaandvue.mapper")
public class JavaVueDameApplication {
public static void main(String[] args) {
SpringApplication.run(JavaVueDameApplication.class, args);
}
}