戻るユーザー用のカスタムログインページ

返品ユーザー用のカスタムログインページ

1. 前書き

この記事は、進行中のregistration with Spring Security seriesの続きです。

In this article, we are going to have a look at how to develop a custom login page for a user who is returning to our application.ユーザーは標準の「ようこそ…」メッセージで迎えられます。

One way to identify if the user is returning to our website is to add a long-lived cookie (e.g. 30 days) after the user has successfully logged in.このロジックを開発するには、認証が成功するとCookieを追加するAuthenticationSuccessHandlerを実装する必要があります。

カスタム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”と現在のユーザーのfirstNameである値を使用してCookieを設定しました。 Cookieは30日後に有効期限が切れるように設定されています。

最後の手順は、ログインフォームが読み込まれるたびにCookieを読み取り、存在する場合はグリーティングメッセージを表示するための値を取得することです。 これはJavascript.で簡単に実行できます

まず、プレースホルダー“welcometext”を追加して、ログインページにメッセージを表示しましょう。



...

それでは、対応する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を単に読み取ります。 2番目の関数は、Cookieが存在する場合、HTMLドキュメントを操作してウェルカムメッセージを設定します。

関数display_username()は、HTML <body>タグのonloadイベントで呼び出されます。

4. 結論

この簡単な記事では、Springのデフォルトの認証フローを変更することにより、ユーザーエクスペリエンスをカスタマイズすることがいかに簡単かを説明しました。 この単純な設定に基づいて、多くの複雑なことができます。

この例のログインページには、/customLoginのURLからアクセスできます。 この記事の完全なコードはover on GitHubにあります。