Springboot整合SpringSecurity 02-使用自定义登陆和登出页面
在Springboot整合SpringSecurity 01-使用入门中我们已经学会了最基本的SpringSecurity的使用。
但是使用的是SpringSecurity自带的登陆页面,通常开发中我们肯定是要使用自己的登陆页面的。
所以本章我们继续学习使用自定义的登陆页面。
代码和配置接着上一章。
本系列的按顺序写的,如果对于某些代码不清楚,请看下前面的几篇文章。
Springboot整合SpringSecurity 01-使用入门
Springboot整合SpringSecurity 02-使用自定义登陆页面
Springboot整合SpringSecurity 03-访问权限控制
Springboot整合SpringSecurity 04-启用登出logout功能
Springboot整合SpringSecurity 05-使用JDBC实现认证和授权
Springboot整合SpringSecurity 06-登陆扩展之自定义登陆验证逻辑
Springboot整合SpringSecurity 07-方法访问权限控制
1.创建一个自定义的登陆页面
<!DOCTYPE HTML>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org" >
<body>
<h1>This is My Login Page</h1>
<form th:action="@{/login}" method="post">
<p th:if="${error != null}">
<span>
<font>Invalid username and password.</font>
</span>
</p>
<p th:if="${logout != null}">
<span>You are logout.</span>
</p>
<p>
<label for="username">Username</label>
<input type="text" id="username" name="username"/>
</p>
<p>
<label for="password">Password</label>
<input type="password" id="password" name="password"/>
</p>
<input type="hidden"
th:name="${_csrf.parameterName}"
th:value="${_csrf.token}"/>
<button type="submit" class="btn">Log in</button>
</form>
</body>
</html>
这里我们在templates目录里面创建了一个login.html来作为我们自己的登陆页面。
因为SpringSecurity默认是开启csrf防护的,所以我们的提交必须携带${_csrf.parameterName},否则会报错。当然我们可以在配置中关掉csrf检测,具体实现只需要在我们的WebSecurityConfig中的configure方法里面添加http.csrf().disable()就可以关掉了。
2.创建跳转到登陆页面的接口
@Controller
public class HelloController {
@GetMapping("hello")
public String hello() {
return "hello";
}
@GetMapping("login")
public String login(@RequestParam(required = false) String error,
@RequestParam(required = false) String logout,
Model model) {
if (error != null) {
model.addAttribute("error", "error");
}
if (logout != null) {
model.addAttribute("logout", "logout");
}
return "login";
}
}
继续在我们的HelloController里面添加登陆页面的接口。
3.配置WebSecurityConfig
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Bean
@Override
public UserDetailsService userDetailsService() {
InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
manager.createUser(User.withDefaultPasswordEncoder().username("user")
.password("user").roles("USER").build());
return manager;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll();
}
}
通过loginPage("/login")来告知我们自己登陆页面的请求地址。
注意这个/login指的是我们自己写的那个接口,这个是GET请求的。
有人已经留意我们的login.html里面表单的提交地址也是/login,这个/login是post请求的,指向的是SpringSecurity的登陆接口。
4.启动项目
这样我们就已经完成了指定自己的登陆页面。下面让我们启动项目。
在浏览器中请求我们的hello接口
http://localhost:10022/security/hello
系统这时候会跳转到我们自己的登陆页面。
然后输入账号密码user/user,成功跳转到hello页面。
这样我们就已经实现了我们自己的登陆页面。