Spring Security hello world example

In this tutorial, we will show you how to integrate Spring Security with a Spring MVC web application to secure a URL access. After implementing Spring Security, to access the content of an “admin” page, users need to key in the correct “username” and “password”.
Technologies used :

  • Spring 3.2.8.RELEASE
  • Spring Security 3.2.3.RELEASE
  • Eclipse 4.2
  • JDK 1.6
  • Maven 3

Note Spring Security 3.0 requires Java 5.0 Runtime Environment or higher

1. Project Demo

2. Directory Structure

Review the final directory structure of this tutorial.


spring-security-helloworld-directory

3. Spring Security Dependencies

To use Spring security, you need spring-security-web and 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 Application

A simple controller :
If URL =/welcome or /, return hello page.
If URL =/admin, return admin page.
Later, we will show you how to use Spring Security to secure the “/admin” URL with a user login form.

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;   
    }
}

Two JSP pages.

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>

從上面的代碼可以看到吁脱,spring security的信息是保存在userPrincipal中的

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 : User Authentication

Create a Spring Security XML file.

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>

It tells, only user “mkyong” is allowed to access the /admin URL.

6. Integrate Spring Security

To integrate Spring security with a Spring MVC web application, just declares DelegatingFilterProxy` as a servlet filter to intercept any incoming request.

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>

spring security就是一個過濾器秩彤,spring mvc就是一個servlet赤兴。

7. Demo

That’s all, but wait… where’s the login form? No worry, if you do not define any custom login form, Spring will create a simple login form automatically.

  1. Welcome Page –http://localhost:8080/spring-security-helloworld-xml/welcome
    spring-security-helloworld-welcome
  2. Try to access /admin page, Spring Security will intercept the request and redirect to /spring_security_login, and a predefined login form is displayed.
    spring-security-helloworld-login
  3. If username and password is incorrect, error messages will be displayed, and Spring will redirect to this URL /spring_security_login?login_error.
    spring-security-helloworld-login-error
  4. If username and password are correct, Spring will redirect the request to the original requested URL and display the page.


    spring-security-helloworld-admin
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末鸠澈,一起剝皮案震驚了整個濱河市怔匣,隨后出現(xiàn)的幾起案子简烘,更是在濱河造成了極大的恐慌,老刑警劉巖甩恼,帶你破解...
    沈念sama閱讀 206,378評論 6 481
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件蟀瞧,死亡現(xiàn)場離奇詭異,居然都是意外死亡条摸,警方通過查閱死者的電腦和手機悦污,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 88,356評論 2 382
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來钉蒲,“玉大人切端,你說我怎么就攤上這事∏晏洌” “怎么了踏枣?”我有些...
    開封第一講書人閱讀 152,702評論 0 342
  • 文/不壞的土叔 我叫張陵,是天一觀的道長线梗。 經(jīng)常有香客問我椰于,道長,這世上最難降的妖魔是什么仪搔? 我笑而不...
    開封第一講書人閱讀 55,259評論 1 279
  • 正文 為了忘掉前任,我火速辦了婚禮蜻牢,結(jié)果婚禮上烤咧,老公的妹妹穿的比我還像新娘。我一直安慰自己抢呆,他們只是感情好煮嫌,可當(dāng)我...
    茶點故事閱讀 64,263評論 5 371
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著抱虐,像睡著了一般昌阿。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上恳邀,一...
    開封第一講書人閱讀 49,036評論 1 285
  • 那天懦冰,我揣著相機與錄音,去河邊找鬼谣沸。 笑死刷钢,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的乳附。 我是一名探鬼主播内地,決...
    沈念sama閱讀 38,349評論 3 400
  • 文/蒼蘭香墨 我猛地睜開眼伴澄,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了阱缓?” 一聲冷哼從身側(cè)響起非凌,我...
    開封第一講書人閱讀 36,979評論 0 259
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎荆针,沒想到半個月后清焕,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 43,469評論 1 300
  • 正文 獨居荒郊野嶺守林人離奇死亡祭犯,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 35,938評論 2 323
  • 正文 我和宋清朗相戀三年秸妥,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片沃粗。...
    茶點故事閱讀 38,059評論 1 333
  • 序言:一個原本活蹦亂跳的男人離奇死亡粥惧,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出最盅,到底是詐尸還是另有隱情突雪,我是刑警寧澤,帶...
    沈念sama閱讀 33,703評論 4 323
  • 正文 年R本政府宣布涡贱,位于F島的核電站咏删,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏问词。R本人自食惡果不足惜督函,卻給世界環(huán)境...
    茶點故事閱讀 39,257評論 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望激挪。 院中可真熱鬧辰狡,春花似錦、人聲如沸垄分。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,262評論 0 19
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽薄湿。三九已至叫倍,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間豺瘤,已是汗流浹背吆倦。 一陣腳步聲響...
    開封第一講書人閱讀 31,485評論 1 262
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留炉奴,地道東北人逼庞。 一個月前我還...
    沈念sama閱讀 45,501評論 2 354
  • 正文 我出身青樓,卻偏偏與公主長得像瞻赶,于是被迫代替她去往敵國和親赛糟。 傳聞我的和親對象是個殘疾皇子派任,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 42,792評論 2 345

推薦閱讀更多精彩內(nèi)容