记一次使用Springboot+Thymeleaf模板插件+SpringSecurity进行页面跳转
首先:搭建Springboot项目(此处省略)
引入pom依赖
<!-- thymeleaf模板插件 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!-- springsecurity -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
我们首先访问时是用springsecurity自带的页面,为了美观我们可以自定义页面
编写配置文件SecurityConfig
package com.idea.portal.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
super.configure(auth);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/login","/login.html").permitAll()//保护的url,需要用户登录
.anyRequest().authenticated()
.and()
.formLogin()
//指定登录页的路径
.loginPage("/login")
//指定自定义form表单请求的路径
.loginProcessingUrl("/authentication/form")
.failureUrl("/login?error")
.defaultSuccessUrl("/success")
//必须允许所有用户访问我们的登录页(例如未验证的用户,否则验证流程就会进入死循环)
//这个formLogin().permitAll()方法允许所有用户基于表单登录访问/login这个page。
.permitAll();
//默认都会产生一个hiden标签 里面有安全相关的验证 防止请求伪造 这边我们暂时不需要 可禁用掉
http .csrf().disable();
}
@Override
public void configure(WebSecurity web) throws Exception {
super.configure(web);
}
}
编写配置文件 .yml文件
spring:
thymeleaf:
cache: false
prefix: classpath:/templates/
suffix: .html
encoding: UTF-8
content-type: text/html
mode: HTML5
security:
user:
name: "admin"
password: "admin"
#设置用户名密码,否则在控制台找到加密后的密码
Using generated security password: b5c91851-3d02-457d-93d8-7fb8a7a8d126
最后在resources中的templates编写html代码