プレビューリンク://spring-security/spring-security-hello-world-example/[post]では、XMLファイルを使用してSpring MVC環境でSpring Securityを設定しています。このチュートリアルでは、以前のXMLベースのSpring Securityプロジェクトを純粋なSpringアノテーションプロジェクトに変換する方法を説明します。
使用される技術:
-
Spring 3.2.8.RELEASE
-
春のセキュリティ3.2.3.RELEASE
-
Eclipse 4.2
-
JDK 1.6
-
Maven 3
-
Tomcat 7(Servlet 3.x)
-
このチュートリアルでは `WebApplicationInitializer`を使用してSpringをロードしています
Context Loaderは自動的にServlet 3.xコンテナのみでサポートされます(Tomcat 7やJetty 8など)。
-
WebApplicationInitializer`を使用しているので、
web.xml`ファイルは
不要です。
-
Spring Securityアノテーションは、古いサーブレット2.xでサポートされています
Tomcat 6などのコンテナにデプロイできます。従来のXMLファイルを使用してSpringコンテキストをロードする場合、このチュートリアルは引き続きServlet 2.xコンテナ(Tomcat 6など)にデプロイできます
1.プロジェクトデモ
それがどのように機能するかを見てください
2.ディレクトリ構造
このチュートリアルの最終的なディレクトリ構造を確認してください。
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 3 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アプリケーション
シンプルなコントローラ:
-
URL =
/welcome`または
/`の場合、helloページを返します. -
URL = `/admin`の場合、adminページを返します.
-
URL = `/dba`の場合、adminページを返します.
後で
/admin`と
/dba`の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 - Admin Page!"); model.setViewName("admin"); return model; } @RequestMapping(value = "/dba** ** ", method = RequestMethod.GET) public ModelAndView dbaPage() { ModelAndView model = new ModelAndView(); model.addObject("title", "Spring Security Hello World"); model.addObject("message", "This is protected page - Database 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="/logout"/>" > Logout</a></h2> </c:if> </body> </html>
5.春のセキュリティ設定
5.1
Springセキュリティコンフィグレーションファイルを作成し、 `@ EnableWebSecurity`で注釈を付けます。
SecurityConfig.java
package com.mkyong.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication().withUser("mkyong").password("123456").roles("USER"); auth.inMemoryAuthentication().withUser("admin").password("123456").roles("ADMIN"); auth.inMemoryAuthentication().withUser("dba").password("123456").roles("DBA"); } @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/admin/** ** ").access("hasRole('ROLE__ADMIN')") .antMatchers("/dba/** ** ").access("hasRole('ROLE__ADMIN') or hasRole('ROLE__DBA')") .and().formLogin(); } }
Spring Security XMLファイルに相当する:
<http auto-config="true"> <intercept-url pattern="/admin** ** " access="ROLE__ADMIN"/> <intercept-url pattern="/dba** ** " access="ROLE__ADMIN,ROLE__DBA"/> </http> <authentication-manager> <authentication-provider> <user-service> <user name="mkyong" password="123456" authorities="ROLE__USER"/> <user name="admin" password="123456" authorities="ROLE__ADMIN"/> <user name="dba" password="123456" authorities="ROLE__DBA"/> </user-service> </authentication-provider> </authentication-manager>
5.2
クラスを作成して
AbstractSecurityWebApplicationInitializer`を拡張すると、
springSecurityFilterChain`が自動的にロードされます。
SpringSecurityInitializer.java
package com.mkyong.config.core; import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer; public class SpringSecurityInitializer extends AbstractSecurityWebApplicationInitializer { //do nothing }
`web.xml`ファイルの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>
6. Spring MVCの設定
6.1
Configクラス。ビューの技術を定義し、 `SecurityConfig.java`の上にインポートします。
AppConfig.java
package com.mkyong.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.view.InternalResourceViewResolver; import org.springframework.web.servlet.view.JstlView; @EnableWebMvc @Configuration @ComponentScan({ "com.mkyong.web.** " }) @Import({ SecurityConfig.class }) public class AppConfig { @Bean public InternalResourceViewResolver viewResolver() { InternalResourceViewResolver viewResolver = new InternalResourceViewResolver(); viewResolver.setViewClass(JstlView.class); viewResolver.setPrefix("/WEB-INF/pages/"); viewResolver.setSuffix(".jsp"); return viewResolver; } }
Spring XMLファイルに相当する:
<context:component-scan base-package="com.mkyong.web.** "/> <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>
6.2
すべてをロードするための `Initializer`クラスを作成します。
SpringMvcInitializer.java
package com.mkyong.config.core; import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; import com.mkyong.config.AppConfig; public class SpringMvcInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { @Override protected Class<?>[]getRootConfigClasses() { return new Class[]{ AppConfig.class }; } @Override protected Class<?>[]getServletConfigClasses() { return null; } @Override protected String[]getServletMappings() { return new String[]{ "/" }; } }
完了しました。
-
Note ** Servlet 3.xコンテナ環境では、Springコンテナは `Initializer`クラスを自動的に検出してロードします。
7.デモ
7.2
/admin`ページにアクセスしようとすると、Spring Securityはリクエストを傍受して
/login`にリダイレクトし、デフォルトのログインフォームが表示されます。
7.3。ユーザー名とパスワードが間違っていると、エラーメッセージが表示され、SpringはこのURLに `/login?error`をリダイレクトします。
7.4。ユーザー名とパスワードが正しい場合、Springは要求を元の要求されたURLにリダイレクトし、ページを表示します。
7.5。権限のないユーザーの場合、Springは403アクセス拒否ページを表示します。たとえば、ユーザー “mkyong”または “dba”は、
/admin
URLにアクセスしようとします。
ソースコードをダウンロードする
ダウンロードする –
spring-security-helloworld-annotation.zip
(12 KB)
参考文献
セキュリティJava設定プレビュー:Webセキュリティ]。
http://docs.spring.io/spring-security/site/docs/3.2.x/guides/hellomvc.html
[Hello
Spring MVCセキュリティJava Config]。
ウィキペディア:Javaサーブレット
-
リンク://spring-security/spring-security-hello-world-example/[Spring
セキュリティHello World XMLの例]