Spring Security hello world example

来源:互联网 发布:质量矩阵模版 编辑:程序博客网 时间:2024/05/21 06:42

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”.

1.   Spring MVC Web Application

A simple controller :

  1. If URL = /welcome or / , return hello page.
  2. If URL = /admin , return admin page.

To integrate Spring security with a Spring MVC web application, just declares DelegatingFilterProxy as a servlet filter to intercept any incoming request.Later, we will show you how to use Spring Security to secure the “/admin” URL with a user login foTo integrate Spring security with a Spring MVC web application, just declares DelegatingFilterProxy as a servlet filter to intrcept any incoming request.rm.

2. HelloController

package com.npf.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;@Controllerpublic 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;}}
3. Two JSP pages.

3.1 hello.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"    pageEncoding="ISO-8859-1"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"><title>Insert title here</title></head><body><h1>Title : ${title}</h1><h1>Message : ${message}</h1></body></html>
3.2 admin.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"    pageEncoding="ISO-8859-1"%><%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"><title>Insert title here</title></head><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>
4. spring-security.xml

<?xml version="1.0" encoding="UTF-8"?><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/beanshttp://www.springframework.org/schema/beans/spring-beans-3.0.xsdhttp://www.springframework.org/schema/securityhttp://www.springframework.org/schema/security/spring-security-4.1.xsd"><http auto-config="true" use-expressions="true"><intercept-url pattern="/admin**" access="hasRole('ROLE_USER')"/></http><authentication-manager>  <authentication-provider>    <user-service><user name="pengfeinie" password="123456" authorities="ROLE_USER" />    </user-service>  </authentication-provider></authentication-manager></beans:beans>
It tells, only user “pengfeinie” is allowed to access the /admin URL.

5.springmvc-web.xml

<?xml version="1.0" encoding="UTF-8"?><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.npf.*" /><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>

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.

<?xml version="1.0" encoding="UTF-8"?><web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   xmlns="http://java.sun.com/xml/ns/javaee"   xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"   id="WebApp_ID" version="3.0">    <display-name>securityHelloWorldXML</display-name><context-param>  <param-name>contextConfigLocation</param-name>  <param-value>classpath:applicationContext.xml,classpath:spring-security.xml</param-value>  </context-param><listener><listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener><servlet><servlet-name>mvc-dispatcher</servlet-name><servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class><init-param>  <param-name>contextConfigLocation</param-name>  <param-value>classpath:springmvc-web.xml</param-value>  </init-param><load-on-startup>1</load-on-startup></servlet><servlet-mapping><servlet-name>mvc-dispatcher</servlet-name><url-pattern>/</url-pattern></servlet-mapping><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. 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.

7.1 Welcome Page – http://localhost:8080/securityHelloWorldXML/welcome


7.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.


7.3 If username and password is incorrect, error messages will be displayed, and Spring will redirect to this URL/spring_security_login?login_error.


7.4  If username and password are correct, Spring will redirect the request to the original requested URL and display the page.


8.you can find the source code in GitHub:https://github.com/SpringSecurityOrganization/securityHelloWorldXML


0 0