The integration of SpringMVC 3.1 Spring Security 3.1

Recommended for you: Get network issues from WhatsUp Gold. Not end users.

This article is an introduction to the article, the netizen question saw yesterday, when spring MVC integrated spring security error, speculation about wood solve problems. I will help to build an integrated frame he said yes, he told me that the net. I'll share for entry learning here today. Spring MVC I wood useful too, so here we focus on how to integrate spring security, spring security is a very good open source framework (Google specific understanding of their rights, or to the spring website, give me a DOC3.1: here.). That includes not only the permissions, which includes a full set of authentication and authorization system: authority, prevent session attack, support channel security, support LDAP authentication, OpenID support, and integrated support for CAS single sign on and so on, people used spring security 2 as basic to Chinese resources, then the less ah, especially integration SSH+spring security is even more pitiful, finally still crustily skin of head, finally get the frame, at least know. At the time I wrote a SSH+spring security article, also is a website quoted. Good nonsense not pull, we integrated a springmvc3.1+spring security3.1. we step by step go today.

step1: Set up SpringMVC.

If you would build or set up spring MVC that this step can be skipped. First download the spring mvc3.1 jar to the official website to download or Google, need jar as shown in Figure:

截图01

Then create a packet of a new spring MVC class, and I are as follows:

@Controller 
public class RestConstroller { 
    
    public RestConstroller() {} 
     
    @RequestMapping(value = "/welcome", method = RequestMethod.GET)  
    public String registPost() {  
        return "/hello";  
    } 

}

Above the spring annotation way to instantiate class, this I do not say more, spring MVC also not used do not point. Official website for example you do.

Then a new view tried to put a hello.jsp

Then a new spring-servlet.xml this is a configuration file spring MVC.

<?xml version="1.0" encoding="UTF-8"?>      
<beans xmlns="http://www.springframework.org/schema/beans" 
    xmlns:context="http://www.springframework.org/schema/context" 
    xmlns:p="http://www.springframework.org/schema/p" 
    xmlns:mvc="http://www.springframework.org/schema/mvc" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation=" 
          
          
          
          
            
         ">         
        
     <!-- Start the annotation driven Spring MVC function, mapping the registration request URL annotation and POJO method-->  
     <mvc:annotation-driven />  
     <!-- Start packet scanning function, in order to register with @Controller, @Service, @repository, @Component classes annotated as spring bean -->  
     <context:component-scan base-package="com.mvc.test" />  <!--This package according to their own projects to configure, mine is com.mvc.test--> 
     <!-- Analysis of the model view name, add suffix at the request of the model view name -->  
     <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:prefix="/WEB-INF/view/" p:suffix=".jsp" />    
</beans> 

Then the configuration of web.xml:

     <context-param>  
        <param-name>contextConfigLocation</param-name>  
        <!-- Application of context configuration files -->  
        <param-value>/WEB-INF/spring-servlet.xml</param-value>  
    </context-param>  
    <listener>  
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  
    </listener> 

  <!-- Configure the spring core Servlet -->  
  <servlet>  
      <servlet-name>spring</servlet-name>  
      <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  
      <load-on-startup>1</load-on-startup>  
  </servlet>  
  <!-- Configure url-pattern to / interception -->  
  <servlet-mapping>  
      <servlet-name>spring</servlet-name>  
      <url-pattern>/</url-pattern>  
  </servlet-mapping>  

The concrete structure project:

截图02

Now you can start, here I start unfortunately wrong, look, the lack of logger jar, add commons-logging-1.1.jar, OK to start a successful visit,

Here spring MVC configuration completed. Focus on the integrated spring security below us 3.1

Step 2 spring mvc3.1 integrated spring security 3.1

First of all to speak a little larger version of integration to note, the major version number to keep, the first is often the major version number, little effect on the minor version number. Why to say, I was in the integration of SSH spring with spring 2.X, to download a spring security 3.X does not succeed then. Later found in a foreigner's article, specific address I forget, spring 2.X +spring security 2.X to set spring 3.X +spring security 3.X successful, can be integrated successfully. Now think of was two, ha ha, well after the episode, we continue to.

First download the spring security 3.1jar, address:. I have had this download, do not, jar structure is as follows:

截图03

Red, is the source package, we don't have to join, the blue circle is two examples, you can deploy to learn about. The other is that we need to jar, according to the package name found that each packet is characteristic of a spring security, generally speaking the jar is added, as the project need will be used.

Next we need to create a new applicationContext-security.xml file, this is a file spring security configuration must be. The contents are as follows:

<?xml version="1.0" encoding="UTF-8"?> 
<b:beans xmlns="http://www.springframework.org/schema/security" 
    xmlns:b="http://www.springframework.org/schema/beans" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
                          
                          
                         "> 
       <!-- Open the interceptor. --> 
      <http auto-config='true'> 
         <!-- Allow access to the URI --> 
        <intercept-url pattern="/**" access="ROLE_USER" />    
       </http> 
       
       <!-- Authority management -->     
       <authentication-manager> 
           <!-- Access provider --> 
        <authentication-provider> 
          <!-- Can provide the user login access --> 
          <user-service> 
            <user name="haha" password="haha" authorities="ROLE_USER, ROLE_ADMIN" /> 
            <user name="xixi" password="xixi" authorities="ROLE_USER" /> 
          </user-service> 
        </authentication-provider> 
      </authentication-manager> 
   
</b:beans>

We explain the, the HTTP node which default open several must the interceptor, a list of users can visit the following user-service is, there is no use database so it is configured, if you use the database configuration of a dataSource can be, including the back of the authorities is through the user database management, here we temporarily entry not do in-depth explanation.

The filter configuration and then we need a spring security, web.xml complete configuration.

<?xml version="1.0" encoding="UTF-8"?> 
<web-app version="2.5" 
    xmlns="http://java.sun.com/xml/ns/javaee" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
    http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

    
    <context-param>  
        <param-name>contextConfigLocation</param-name>  
        <!-- Application of context configuration files -->  
        <param-value>/WEB-INF/spring-servlet.xml,/WEB-INF/applicationContext-security.xml</param-value> 
    </context-param> 
      
    <listener>  
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  
    </listener> 
    
    <!-- spring securit start --> 
    <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> 
    <!-- spring securit start --> 
          
    <!-- Configure the spring core Servlet -->  
    <servlet>  
        <servlet-name>spring</servlet-name>  
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  
        <load-on-startup>1</load-on-startup>  
    </servlet>  
    <!-- Configure url-pattern to /, without the file suffix, will cause other static files (JS, CSS) cannot access. As with *.do, does not affect the static file access -->  
    <servlet-mapping>  
        <servlet-name>spring</servlet-name>  
        <url-pattern>/</url-pattern>  
    </servlet-mapping> 

    
    <welcome-file-list> 
      <welcome-file>index.jsp</welcome-file> 
   </welcome-file-list> 
</web-app>

The springSecurityFilterChain  filter must be placed in the front, because the security mechanism of spring security is to protect the security framework in web layer, so any trip you must pass through the authorization spring security voting mechanism can access, otherwise not allowed access. Only the user can access.

The contextConfigLocation configuration is to scan our spring MVC and spring security configuration file.

The following directory structure complete:

截图04

Below we have a look what happens to start web magical things. Below we visit

截图06

Miracles happen, We did not create a landing page, Where the landing page to? Ha-ha, Don't worry, Slowly, Have a look URL spring_security_login , Remember we configured spring security configuration files <http> the default configuration will open several filter, One is that we have no landing and then look for the interception of the landing page, But why would automatically come out? It is by default it a landing page for our, We can specify a login page, We did not specify the examination found no it will default to a landing page to us, Below we have a look on what will happen. (What you do not know the password? The fact that we spring security configuration of the account password).

Enter the account password results:

截图07

Jump to the we just want to visit the URI in the middle, we will check the account is entitled to have the right to access, success, no will to do not have access to the page. Well, here spring mvc+spring security integration is completed, the rest of the work is a step by step slowly learning the spring security to use more perfect function. Simple, this thing.

Here we try again if the login does not exist a account of what would happen, I enter a admin, the results appear as below:

截图08

Spring security has helped us to check, account does not exist, he will take us to redirect to the login page, know the login is successful, otherwise you will face is the login page.

Good today the main share of this introduction, the master door by personal practice. But I wanted to think, or to share a bit useful, some people will think if I login page need to customize how to do? Below we talk about.

The first custom landing, we need to modify the applicationContext-security.xml configuration file, is amended as follows:

    <!-- Open the interceptor. --> 
      <http auto-config='true'> 
         <!-- Allow access to the URI --> 
         <intercept-url pattern="/**" access="ROLE_USER" /> 
         <!-- Landing page allocation --> 
          <form-login login-page="/login.jsp" default-target-url="/index.jsp" authentication-failure-url="/login.jsp?error=true"/> 
       </http> 
       
       <!-- Authority management -->     
       <authentication-manager> 
           <!-- Access provider --> 
        <authentication-provider> 
          <!-- Can provide the user login access --> 
          <user-service> 
            <user name="haha" password="haha" authorities="ROLE_USER, ROLE_ADMIN" /> 
            <user name="xixi" password="xixi" authorities="ROLE_USER" /> 
          </user-service> 
        </authentication-provider> 
      </authentication-manager>

The more the configuration of a form node, the login-page is your landing page from naming can be, default-target-url is the default login page, authentication-failure-url is when you enter the illegal account or password automatically redirected to login.jsp.

Next create our own custom landing pages, I is login.jsp, there are people here think, form how to write? How to write can be intercepted? The following:

   

    <h1>user login</h1> 
    <form action="j_spring_security_check" method="post"> 
        User name<input type="text" name="j_username"/><br/> 
        Cipher<input type="password" name="j_password"/><br/> 
        <input type="submit" value="submit"/> 
    </form>

action="j_spring_security_check"You must write this, otherwise the interceptors not to. Landing field j_username j_password must write this, otherwise your login interceptor to obtain less than value. Of course, you can also be customized, but the premise is that you must inherit the UsernamePasswordAuthenticationFilter filter to rewrite it, here we will not trouble, but generally we do not need to rewrite, it can be provided. Well, here we can start the server. We visit again: have a look what changes will happen. As shown in Fig.:

截图10

Why? This is what the situation? URL has changed, we want to access the address. But the page on the form? Don't try so hard, that I had seen many, the first reaction of login.jsp has not been released, intercept, protected resources. We are not talking about spring  security is the outermost layer of protection in the web well, to access any resources need to vote, the authorization to access, this is no exception.

Well, know what the situation, we modify it! Fragments can be amended as follows:

      

     <!-- Open the interceptor. --> 
      <http auto-config='true'> 
         <!--The login.jsp release, without protection--> 
         <intercept-url pattern="/login.jsp" filters="none" /> 
         <!-- Allow access to the URI --> 
         <intercept-url pattern="/**" access="ROLE_USER" /> 
         <!-- Landing page allocation --> 
         <form-login login-page="/login.jsp" default-target-url="/index.jsp" authentication-failure-url="/login.jsp?error=true"/> 
       </http> 

Then we start the server visit again

The unfortunate thing happened, the console error, the server failed to start the following diagram!:

截图11

截图12

In fact, it is this configuration invalid speak following the.

<!For login.jsp release, without protection>

<intercept-url pattern="/login.jsp" filters="none" />This configuration is spring security 2.X, 3.X invalid, use new ways. But at least you let me cannot be invoked again then, so I know this is not the label, it is understandable, relevant configuration to spend a lot of energy waste, pull the whole, so it can also call, but you can't run. But the wrong tell us how to use the new label, is a new node label, the attribute security= "None" to release, okay, we modify the. To modify some configuration is as follows:

    

       <!-- Configuration of spring securit 3.X new resource release, not a protected resource -->                   
       <http pattern="/login.jsp" security="none"/>              
                        
       <!-- Open the interceptor. --> 
       <http auto-config='true'> 
          <!-- Allow access to the URI --> 
          <intercept-url pattern="/**" access="ROLE_USER" /> 
          <!-- Landing page allocation --> 
          <form-login login-page="/login.jsp" default-target-url="/index.jsp" authentication-failure-url="/login.jsp?error=true"/> 
        </http>

Add a node in the HTTP node, and then the configuration does not need to intercept. The pattern property means by a regular expression to match. security="none"It is not safe, It is not by spring security protected resources, Here I would like to mention a little, Is.Jpg,.Gif,.Swf,.Css,.Js/ and so on resource file will be stopped, Even if he is contained in a JSP page or URI has released the request, how to understand? Is such as: our login.jsp release., But we did not release.Jpg this picture resources, When we visit the login.jsp image is not displayed, Because it has not been released, From here we can see that the spring security is very strict inspection mechanism. If we want to release those who do?

Spring security 2.X configuration is as follows:

     

  <http auto-config='true'> 
      <!-- The public resource file –> 
      <intercept-url pattern="/**/*.jpg" filters="none" />  
      <intercept-url pattern="/**/*.png" filters="none" />  
      <intercept-url pattern="/**/*.gif" filters="none" /> 
      <intercept-url pattern="/**/*.ico" filters="none" /> 
      <intercept-url pattern="/**/*.css" filters="none" /> 
      <intercept-url pattern="/**/*.js" filters="none" />


       <!- allows access to URI --> 
       <intercept-url pattern="/**" access="ROLE_USER" /> 
       <!-- Landing page allocation --> 
       <form-login login-page="/login.jsp" default-target-url="/index.jsp" authentication-failure-url="/login.jsp?error=true"/> 
     </http>

Of course we are here to talk about spring security 3.X, so 3.X is as follows:

<http pattern="/**/*.jpg" security="none"/>              
<http pattern="/**/*.png" security="none"/>              
<http pattern="/**/*.gif" security="none"/> 
<http pattern="/**/*.ico" security="none"/>              
<http pattern="/**/*.css" security="none"/> 
<http pattern="/**/*.js" security="none"/>    
<!-- Configuration of spring securit 3.X new resource release, not a protected resource -->                   
<http pattern="/login.jsp" security="none"/>             

  <http auto-config='true'> 
  
     <!-- Allow access to the URI --> 
     <intercept-url pattern="/**" access="ROLE_USER" /> 
     <!-- Landing page allocation --> 
     <form-login login-page="/login.jsp" default-target-url="/index.jsp" authentication-failure-url="/login.jsp?error=true"/> 
   </http>

The pattern= "/**/*.jpg" configuration means release, all.Jpg resources in the project, after the principle and so on. You can also release a file under the regular expression, specifically the configuration.

Well, we still go back to just modified release resources to try again, start the server access:

截图13

When the login.jsp when we visit again has come out, this time we landed, response page to jump directly to the success of the /welcome. Results as shown in Fig.;

截图14

Here we do not have to configure the user access to resources, so the access to the resources can be accessed directly, if the configuration access after the successful landing, spring security will check whether has the right to access, unauthorized redirection.


Well here, today to share the entry end. Behind the time and then slowly share, this framework is very worth learning. The function is powerful, the official document in a more comprehensive, can be a good read, thanks for taking the time to read.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download

Posted by Lou at November 15, 2013 - 7:40 PM