Spring Security自带的登录界面比较简单,不能完成多变的需求,这章来完成自定义登录界面。
修改配置
在configure(HttpSecurity http)中,.formLogin().loginPage加入自定义界面的URI,使Spring Security跳转到自己定义的一个地址。代码:
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/", "/home").permitAll() // 这三个目录不做安全控制
.anyRequest().authenticated()
.and()
.formLogin().loginPage("/login").permitAll(); // 自定义的登录页面
}
写界面
路径配置好了,需要把“/login”实现。在“com.biboheart.demos.security”中创建一个controller包(把安全控制相关的都加到在com.biboheart.demos.security包下进行)。在com.biboheart.demos.security.controller下创建Class,名称为SecurityController。完成“login”页面导航。
package com.biboheart.demos.security.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
public class SecurityController {
@RequestMapping(value = "/login", method = {RequestMethod.GET})
public String getAccessConfirmation() {
return "login";
}
}
在templates下创建login.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<head>
<title>Spring Security Example</title>
</head>
<body>
<form th:action="@{/login}" method="post">
<div>
<label> 用户名: <input type="text" name="username" />
</label>
</div>
<div>
<label> 密码: <input type="password" name="password" />
</label>
</div>
<div>
<input type="submit" value="登录" />
</div>
</form>
</body>
</html>
启动项目,访问http://localhost
首页
点击连接“这里”跳转hello页面,却跳转到了自己写的登录界面。是不是与上一章节《Spring Security实现用户登录》不同了。
自定义的登录界面
貌似比它自带的要丑,这个可以用CSS随意处理了。
输入用户名:user,密码:123,点击登录。进入hello页面。
hello界面
退出登录
前面没做退出功能,界面有了登录还要有退出,这样才完整。
先在Hello界面中加个跳转到首页的。
// hello.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<head>
<title>Hello World!</title>
</head>
<body>
<p>
点击 <a th:href="@{/}">这里</a> 返回首页.
</p>
<h1 th:inline="text">Hello</h1>
</body>
</html>
结果如下,点击“这里”后可以加到首页
加了返回首页
在界面中加入下面代码就可以实现登出。
<form th:action="@{/logout}" method="post">
点击<input type="submit" value="登出" />
</form>
界面效果,点击“登出”即可退出登录,默认跳转到/login页面。
登出按钮
这里有个问题,不论有没有登录都会显示登出按钮。如果在需要登录的页面还好,在首页登出的话就需要判断一下当前是否有用户登录中,有的话才显示。Spring Security 提供了 thymeleaf 标签,需要在pom.xml中引入。
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity5</artifactId>
</dependency>
修改页面中登出按钮
<div sec:authorize="isAuthenticated()">
登录者:<span sec:authentication="name"></span>
<form th:action="@{/logout}" method="post">
点击<input type="submit" value="登出" />
</form>
</div>
配置登出后页面
如果登出后想要返回到首页,可以改配置文件登出后跳转的URL。
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/", "/home").permitAll() // 这三个目录不做安全控制
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")// 自定义的登录页面
.permitAll()
.and()
.logout()
.logoutSuccessUrl("/");
}