spring security step by step

First we can see the folder structure.


Step 1  : 

Create a new Maven Project.


Step 2 : 

Add below dependencies jar to the project.

One Note here, it is a knowledge here as I only add these but these jars will depend on the other jars, the maven will load it by itself and so on. 


pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

<modelVersion>4.0.0</modelVersion>

<groupId>springSecurity</groupId>

<artifactId>springSecurity</artifactId>

<version>0.0.1-SNAPSHOT</version>

<packaging>war</packaging>

<name>springSecurity</name>

<description>springSecurity</description>

<properties>

<jdk.version>1.7</jdk.version>

<spring.version>3.1.3.RELEASE</spring.version>

<spring.security.version>3.1.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>

</project>

For the spring-security.xml

<?xml version="1.0" encoding="UTF-8"?>  

<beans 

    xmlns:security="http://www.springframework.org/schema/security"  

xmlns="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.1.xsd  

http://www.springframework.org/schema/security   

http://www.springframework.org/schema/security/spring-security-3.1.xsd">  

                        

<security:http auto-config="true">

<security:intercept-url pattern="/index*" access="ROLE_USER" />

<security:form-login login-page="/login" default-target-url="/index" authentication-failure-url="/fail2login" />

<security:logout logout-success-url="/logout" />

</security:http>


<security:authentication-manager>

<security:authentication-provider>

<security:user-service>

<security:user name="dineshonjava" password="sweety" authorities="ROLE_USER" />

</security:user-service>

</security:authentication-provider>

</security:authentication-manager>


</beans>

For this one, it is very important that, the xsi:schemaLocation  the L must be upper case, or it will throw below exception.

May 07, 2015 2:46:54 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions

INFO: Loading XML bean definitions from class path resource [sdnext-security.xml]

May 07, 2015 2:46:54 PM org.springframework.web.context.ContextLoader initWebApplicationContext

SEVERE: Context initialization failed

org.springframework.beans.factory.xml.XmlBeanDefinitionStoreException: Line 9 in XML document from class path resource [sdnext-security.xml] is invalid; nested exception is org.xml.sax.SAXParseException; lineNumber: 9; columnNumber: 75; cvc-elt.1: Cannot find the declaration of element ‘beans‘.

at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:396)

at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:334)

at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:302)

at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:174)

at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:209)

at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:180)

at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:125)

at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:94)

at org.springframework.context.support.AbstractRefreshableApplicationContext.refreshBeanFactory(AbstractRefreshableApplicationContext.java:131)

at org.springframework.context.support.AbstractApplicationContext.obtainFreshBeanFactory(AbstractApplicationContext.java:530)

at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:444)

at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:383)

at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:283)

at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:111)

at org.eclipse.jetty.server.handler.ContextHandler.callContextInitialized(ContextHandler.java:672)

at org.eclipse.jetty.servlet.ServletContextHandler.callContextInitialized(ServletContextHandler.java:403)

at org.eclipse.jetty.server.handler.ContextHandler.startContext(ContextHandler.java:664)

at org.eclipse.jetty.servlet.ServletContextHandler.startContext(ServletContextHandler.java:239)

at org.eclipse.jetty.webapp.WebAppContext.startContext(WebAppContext.java:1212)

at org.eclipse.jetty.server.handler.ContextHandler.doStart(ContextHandler.java:610)

at org.eclipse.jetty.webapp.WebAppContext.doStart(WebAppContext.java:453)

at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:59)

at org.eclipse.jetty.server.handler.HandlerWrapper.doStart(HandlerWrapper.java:89)

at org.eclipse.jetty.server.Server.doStart(Server.java:262)

at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:59)

at runjettyrun.Bootstrap.main(Bootstrap.java:80)

For the spring-servlet.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"   

    xmlns:security="http://www.springframework.org/schema/security"  

    xsi:schemaLocation="http://www.springframework.org/schema/beans   

    http://www.springframework.org/schema/beans/spring-beans-3.1.xsd  

http://www.springframework.org/schema/context

http://www.springframework.org/schema/context/spring-context-3.1.xsd

http://www.springframework.org/schema/security   

http://www.springframework.org/schema/security/spring-security-3.1.xsd">  

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


<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="jspViewResolver">

<property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />

<property name="prefix" value="/WEB-INF/views/" />

<property name="suffix" value=".jsp" />

</bean>


</beans>

 This is for spring mvc. 

For java file

package com.dineshonjava.security.controller;


import java.security.Principal;


import org.springframework.stereotype.Controller;

import org.springframework.ui.ModelMap;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestMethod;


/**

 * @author Rex

 *

 */

@Controller

public class LoginSecurityController {

 

 @RequestMapping(value="/index", method = RequestMethod.GET)

 public String executeSecurity(ModelMap model, Principal principal ) {

 

  String name = principal.getName();

  model.addAttribute("author", name);

  model.addAttribute("message", "Welcome To Login Form Based Spring Security Example!!!");

  return "welcome";

 

 }

 

 @RequestMapping(value="/login", method = RequestMethod.GET)

 public String login(ModelMap model) {

 

  return "login";

 

 }

 

 @RequestMapping(value="/fail2login", method = RequestMethod.GET)

 public String loginerror(ModelMap model) {

 

  model.addAttribute("error", "true");

  return "login";

 

 }

 

 @RequestMapping(value="/logout", method = RequestMethod.GET)

 public String logout(ModelMap model) {

 

  return "login";

 

 }

}

 For the login.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">

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

<html>

<head>

<title>Login Page For Security</title>

<style>

.errorblock {

 color: #ff0000;

 background-color: #ffEEEE;

 border: 3px solid #ff0000;

 padding: 8px;

 margin: 16px;

}

</style>

</head>

<body onload=‘document.f.j_username.focus();‘>

 <h3>Login with Username and Password (Custom Login Page)</h3>

 

 <c:if test="${not empty error}">

  <div class="errorblock">

   Your login attempt was not successful, try again.

 Caused :

   ${sessionScope["SPRING_SECURITY_LAST_EXCEPTION"].message}

  </div>

 </c:if>

 

 <form name=‘f‘ action="<c:url value=‘j_spring_security_check‘ />"

  method=‘POST‘>

 

  <table>

   <tr>

    <td>User:</td>

    <td><input type=‘text‘ name=‘j_username‘ value=‘‘>

    </td>

   </tr>

   <tr>

    <td>Password:</td>

    <td><input type=‘password‘ name=‘j_password‘ />

    </td>

   </tr>

   <tr>

    <td colspan=‘2‘><input name="submit" type="submit"

     value="submit" />

    </td>

   </tr>

   <tr>

    <td colspan=‘2‘><input name="reset" type="reset" />

    </td>

   </tr>

  </table>

 

 </form>

</body>

</html>

For welcome.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"%>

<html>

<head>


<title>WELCOME TO SECURE AREA</title>

</head>

<body>

 <h1>

Message : ${message}</h1>

<h1>

Author : ${author}</h1>

<a href="https://www.blogger.com/%3Cc:url%20value=%22/j_spring_security_logout%22%20/%3E"> Logout</a>

</body>

</html>

In the web.xml, also have the two methods to add config files.   

本文出自 “JodyRex” 博客,请务必保留此出处http://503431920.blog.51cto.com/6681280/1643859

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。