Springセキュリティのカスタムログインフォームの例

Spring Securityのカスタムログインフォームの例

デフォルトでは、ログインフォームが指定されていない場合、Spring Securityはデフォルトのログインフォームを自動的に作成します。 これを参照してください–Spring Security hello world example

このチュートリアルでは、Spring Securityのカスタムログインフォームを作成する方法を示します(XMLの例)。

使用される技術:

  1. Spring 3.2.8.RELEASE

  2. Spring Security 3.2.3.RELEASE

  3. Eclipse 4.2

  4. JDK 1.6

  5. メーベン3

Note
この例では、以前のSpring Security hello world exampleが再利用され、カスタムログインフォームをサポートするように拡張されます。

1. プロジェクトのデモ

2. ディレクトリ構造

このチュートリアルの最終的なディレクトリ構造を確認してください。

spring-security-custom-login-xml-directory

3. Spring Securityの構成

Spring XMLファイルでカスタムログインフォームを定義しました。 以下の説明を参照してください。

  1. login-page=”/login” – The page to display the custom login form

  2. authentication-failure-url=”/login?error” – If authentication failed, forward to page /login?error

  3. logout-success-url=”/login?logout” – If logout successful, forward to view /logout

  4. username-parameter =” username” –“ username”を含むリクエストの名前。 HTMLでは、これは入力テキストの名前です。

  5. – Enable the Cross Site Request Forgery (CSRF) protection, refer to this link. XMLでは、デフォルトでCSRF保護が無効になっています。

通常、ログインやログアウトの処理のような認証には関与せず、Springで処理し、成功または失敗したページを処理するだけです。

spring-security.xml



    
        
        
        
        
        
    

    
        
          
            
          
        
    

上記のお祝いの言葉で、/adminとそのサブフォルダはすべてパスワードで保護されています。

Cross Site Request Forgery (CSRF) Protection
CSRFが有効になっている場合は、ログインまたはログアウトするページに_csrf.tokenを含める必要があります。 以下のlogin.jspおよびadmin.jsp(ログアウトフォーム)を参照してください。 そうしないと、ログイン機能とログアウト機能の両方が失敗します。

Password in clear-text?
かなり悪い考えです。常に、SHAアルゴリズムを使用してパスワードをハッシュする必要があります。このチュートリアルでは、その方法を示します– SpringSecurityパスワードハッシュの例。

4. カスタムログインフォーム

上記と一致するカスタムログインフォーム(ステップ3)Spring Securityのお祝い。 自明であるべきです。

login.jsp

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>


Login Page




    

Spring Security Custom Login Form (XML)

Login with Username and Password

${error}
${msg}
User:
Password:

そして、他の2つのJSPページ、ところでadmin.jspは、SpringSecurityによってパスワードで保護されています。

hello.jsp

<%@page session="false"%>


    

Title : ${title}

Message : ${message}

admin.jsp + logout

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@page session="true"%>


    

Title : ${title}

Message : ${message}

Welcome : ${pageContext.request.userPrincipal.name} | Logout

5. Spring MVCコントローラー

シンプルなコントローラー。

HelloController.java

package com.example.web.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class HelloController {

    @RequestMapping(value = { "/", "/welcome**" }, method = RequestMethod.GET)
    public ModelAndView welcomePage() {

        ModelAndView model = new ModelAndView();
        model.addObject("title", "Spring Security Custom Login Form");
        model.addObject("message", "This is welcome page!");
        model.setViewName("hello");
        return model;

    }

    @RequestMapping(value = "/admin**", method = RequestMethod.GET)
    public ModelAndView adminPage() {

        ModelAndView model = new ModelAndView();
        model.addObject("title", "Spring Security Custom Login Form");
        model.addObject("message", "This is protected page!");
        model.setViewName("admin");

        return model;

    }

    //Spring Security see this :
    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public ModelAndView login(
        @RequestParam(value = "error", required = false) String error,
        @RequestParam(value = "logout", required = false) String logout) {

        ModelAndView model = new ModelAndView();
        if (error != null) {
            model.addObject("error", "Invalid username and password!");
        }

        if (logout != null) {
            model.addObject("msg", "You've been logged out successfully.");
        }
        model.setViewName("login");

        return model;

    }

}

6. Demo

spring-security-custom-login-xml-welcome

6.2 Try to access /admin page, Spring Security will intercept the request and redirect to /login, and your custom login form is displayed.

spring-security-custom-login-xml-login

6.3. ユーザー名とパスワードが正しくない場合、エラーメッセージが表示され、SpringはこのURL/login?errorにリダイレクトします。

spring-security-custom-login-xml-error

6.4. ユーザー名とパスワードが正しい場合、Springは要求された元のURLにリダイレクトし、ページを表示します。

spring-security-custom-login-xml-admin

6.5. ログアウトしてみてください。/login?logoutページにリダイレクトされます。

spring-security-custom-login-xml-logout

ソースコードをダウンロード

ダウンロード–spring-security-custom-login-form-xml.zip(15 KB)