引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
自定义登录页面 /templates/myLogin.html
<!DOCTYPE html>
<html lang="en" xmlns:sec="http://www.thymeleaf.org/extras/spring-security">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<style>
div{
text-align: center;
}
</style>
<body>
<div class="main">
<form class="login-form" action="doLogin" method="post" novalidate >
<!--输入框-->
<div class="input-content">
<!--autoFocus-->
<div>
<label for="username" >用户名:</label><br>
<input id="username" type="text" autocomplete="off"
placeholder="用户名" name="username" required/>
</div>
<div >
<label for="password" >密码:</label><br>
<input id="password" type="password"
autocomplete="off" placeholder="登录密码" name="password" required maxlength="32"/>
</div>
</div>
<!--登入按钮-->
<div >
<button type="submit" >登录</button>
</div>
</form>
</div>
</body>
</html>
配置WebSecurityConfig
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
//.antMatchers("/myLogin.html","doLogin").permitAll()
.anyRequest()
.authenticated()
.and()
.formLogin()
.loginPage("/myLogin.html")
//.defaultSuccessUrl("/hello",true)
.successForwardUrl("/hello")
.loginProcessingUrl("/doLogin")
.permitAll()
.and()
.csrf().disable();
}
}
配置登录页面动态LoginController控制器
@Controller
public class LoginController {
@GetMapping("/myLogin.html")
public String login(){
return "myLogin";
}
}
配置登录成功页面控制器
@RestController
public class HelloConrotller {
@RequestMapping("/hello")
public String hello(){
return "hello";
}
}
注意事项:
配置 .successForwardUrl("/hello")
时,
使用
@RequestMapping("/hello")
使用GetMapping(“hello”) 会报错。
使用thymeleaf 是动态加载页面,要使用
@Controller
public class LoginController {
@GetMapping("/myLogin.html")
public String login(){
return “myLogin”;
}
}
进行页面跳转。
否则访问不到自定义的登录页面。
如果不适用thymeleaf 可以把自定义的登陆页面放在static 文件夹内或者public 文件内,不配置LoginController 就可以直接访问自定义的登录页面。
这里为了便于测试在application.properties 文件中配置了用户名和密码
spring.security.user.name=user
spring.security.user.password=123