1. 引言
本文是我們在 Spring Security 系列中持續進行的介紹的延續。
在本文中,我們將探討如何為返回用户開發自定義登錄頁面。用户將看到一個標準的“歡迎…”消息。
2. 添加持久Cookie
識別用户是否返回到我們的網站的一種方式是在用户成功登錄後,添加一個持久Cookie(例如30天)。 為了實現這一邏輯,我們需要實現我們的 AuthenticationSuccessHandler,該Handler在成功認證後添加Cookie。
讓我們創建我們自定義的 MyCustomLoginAuthenticationSuccessHandler 並實現 onAuthenticationSuccess() 方法:
@Override
public void onAuthenticationSuccess(final HttpServletRequest request,
final HttpServletResponse response, final Authentication authentication)
throws IOException {
addWelcomeCookie(gerUserName(authentication), response);
redirectStrategy.sendRedirect(request, response,
"/homepage.html?user=" + authentication.getName());
}重點在於調用 addWelcomeCookie() 方法。
現在,讓我們來查看一下添加 cookie 的代碼:
private String gerUserName(Authentication authentication) {
return ((User) authentication.getPrincipal()).getFirstName();
}
private void addWelcomeCookie(String user, HttpServletResponse response) {
Cookie welcomeCookie = getWelcomeCookie(user);
response.addCookie(welcomeCookie);
}
private Cookie getWelcomeCookie(String user) {
Cookie welcomeCookie = new Cookie("welcome", user);
welcomeCookie.setMaxAge(60 * 60 * 24 * 30);
return welcomeCookie;
}我們已設置一個名為 “welcome” 的 cookie,以及當前用户 firstName 作為其值。該 cookie 將在 30 天后過期。
3. 登錄表單讀取 Cookie
最後一步是在登錄表單加載時讀取 Cookie,如果存在,則獲取其值以顯示問候消息。我們可以很容易地使用 Javascript 完成此操作。
首先,讓我們添加佔位符 “welcometext” 以在登錄頁面上顯示我們的消息:
<form name='f' action="login" method='POST' onsubmit="return validate();">
<span id="welcometext"> </span>
<br /><br />
<label class="col-sm-4" th:text="#{label.form.loginEmail}">Email</label>
<span class="col-sm-8">
<input class="form-control" type='text' name='username' value=''/>
</span>
...
</form>現在,讓我們來查看相應的 Javascript:
function getCookie(name) {
return document.cookie.split('; ').reduce((r, v) => {
const parts = v.split('=')
return parts[0] === name ? decodeURIComponent(parts[1]) : r
}, '')
}
function display_username() {
var username = getCookie('welcome');
if (username) {
document.getElementById("welcometext").innerHTML = "Welcome " + username + "!";
}
}第一個函數僅讀取用户登錄時設置的 Cookie。第二個函數通過操縱 HTML 文檔,如果 Cookie 存在,則設置歡迎消息。
函數 display_username() 在 HTML <body> 標籤的 onload 事件上調用:
<body onload="display_username()">4. 結論
在本文中,我們看到了通過修改 Spring 的默認身份驗證流程,自定義用户體驗的簡單性。 這種簡單的設置可以基於此實現許多複雜的任務。