このチュートリアルでは、SpringセキュリティとSpring MVC Webアプリケーションを統合してURLアクセスを保護する方法を説明します。 Spring Securityを実装した後、 “admin”ページのコンテンツにアクセスするには、正しい “username”と “password”を入力する必要があります。

使用される技術:

  1. Spring 3.2.8.RELEASE

  2. 春のセキュリティ3.2.3.RELEASE

  3. Eclipse 4.2

  4. JDK 1.6

  5. Maven 3

1.プロジェクトデモ

2.ディレクトリ構造

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


spring-security-helloworld-directory、width = 461、height = 430

3.春のセキュリティの依存関係

Springセキュリティを使用するには、

spring-security-web`と

spring-security-config`が必要です。

pom.xml

    <properties>
        <jdk.version>1.6</jdk.version>
        <spring.version>3.2.8.RELEASE</spring.version>
        <spring.security.version>3.2.3.RELEASE</spring.security.version>
        <jstl.version>1.2</jstl.version>
    </properties>

    <dependencies>

        <!-- Spring dependencies -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <!-- Spring Security -->
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-web</artifactId>
            <version>${spring.security.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-config</artifactId>
            <version>${spring.security.version}</version>
        </dependency>

        <!-- jstl for jsp page -->
        <dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>${jstl.version}</version>
        </dependency>

    </dependencies>

4. Spring MVC Webアプリケーション

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

  1. URL =

    /welcome`または

    /`の場合、helloページを返します.

  2. URL = `/admin`の場合、adminページを返します.

後で、Spring Securityを使用して “/admin” URLをユーザーログインフォームで保護する方法を説明します。

HelloController.java

package com.mkyong.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.servlet.ModelAndView;

@Controller
public class HelloController {

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

        ModelAndView model = new ModelAndView();
        model.addObject("title", "Spring Security Hello World");
        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 Hello World");
        model.addObject("message", "This is protected page!");
        model.setViewName("admin");

        return model;

    }

}

2つのJSPページ。

hello.jsp

<%@page session="false"%>
<html>
<body>
    <h1>Title : ${title}</h1>
    <h1>Message : ${message}</h1>
</body>
</html>

admin.jsp

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@page session="true"%>
<html>
<body>
    <h1>Title : ${title}</h1>
    <h1>Message : ${message}</h1>

    <c:if test="${pageContext.request.userPrincipal.name != null}">
       <h2>Welcome : ${pageContext.request.userPrincipal.name}
           | <a href="<c:url value="/j__spring__security__logout"/>" > Logout</a></h2>
    </c:if>
</body>
</html>

mvc-dispatcher-servlet.xml

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <context:component-scan base-package="com.mkyong.** "/>

    <bean
      class="org.springframework.web.servlet.view.InternalResourceViewResolver">
      <property name="prefix">
        <value>/WEB-INF/pages/</value>
      </property>
      <property name="suffix">
        <value>.jsp</value>
      </property>
    </bean>

</beans>

5.春のセキュリティ:ユーザ認証

Spring Security XMLファイルを作成します。

spring-security.xml

<beans:beans xmlns="http://www.springframework.org/schema/security"
    xmlns:beans="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/security
    http://www.springframework.org/schema/security/spring-security-3.2.xsd">

    <http auto-config="true">
        <intercept-url pattern="/admin** ** " access="ROLE__USER"/>
    </http>

    <authentication-manager>
      <authentication-provider>
        <user-service>
        <user name="mkyong" password="123456" authorities="ROLE__USER"/>
        </user-service>
      </authentication-provider>
    </authentication-manager>

</beans:beans>

それは、ユーザー “mkyong”だけが/adminのURLにアクセスすることが許可されていることを示しています。

6. Springセキュリティの統合

SpringセキュリティをSpring MVC Webアプリケーションと統合するには、受信リクエストを代行受信するサーブレットフィルタとして `DelegatingFilterProxy`を宣言するだけです。

web.xml

<web-app id="WebApp__ID" version="2.4"
    xmlns="http://java.sun.com/xml/ns/j2ee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
    http://java.sun.com/xml/ns/j2ee/web-app__2__4.xsd">

    <display-name>Spring MVC Application</display-name>

    <!-- Spring MVC -->
    <servlet>
        <servlet-name>mvc-dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>mvc-dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener
        </listener-class>
    </listener>

        <!-- Loads Spring Security config file -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
           /WEB-INF/spring-security.xml
        </param-value>
    </context-param>

    <!-- Spring Security -->
    <filter>
        <filter-name>springSecurityFilterChain</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy
        </filter-class>
    </filter>

    <filter-mapping>
        <filter-name>springSecurityFilterChain</filter-name>
        <url-pattern>/** </url-pattern>
    </filter-mapping>

</web-app>

7.デモ

それだけですが、待ってください…​ログインフォームはどこですか?あなたがカスタムログインフォームを定義しなければ、Springは自動的に単純なログインフォームを作成します。

  • カスタム・ログイン・フォーム** Spring Securityでカスタム・ログイン・フォームを作成する方法を理解するには、この「

    Spring Security form login example

    」を参照してください。


spring-security-helloworld-welcome、width = 608、height = 430

{空} 2。

/admin`ページにアクセスしようとすると、Spring Securityはリクエストを傍受し、

/spring

security

login`にリダイレクトし、定義済みのログインフォームが表示されます。


spring-security-helloworld-login、width = 640、height = 420

{空} 3。ユーザー名とパスワードが間違っていると、エラーメッセージが表示され、SpringはこのURLに `/spring

security

login?login__error`にリダイレクトします。


spring-security-helloworld-login-error、width = 640、height = 395

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


spring-security-helloworld-admin、width = 600、height = 405

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

ダウンロードする –

spring-security-helloworld-xml.zip

(9 KB)

参考文献

サイト]。リンク://spring3/spring-3-mvc-hello-world-example/[Spring 3 MVC hello

世界の例]。リンク://spring-security/spring-security-form-login-example/[Spring

セキュリティフォームのログインの例(認証)]