Step 2 - Adding security

Decide the resources for which you want to provide restricted access.

Here, we will do it for the data.htm URL:

  1. Add filter mapping for DelegatingFilterProxy as a filter in web.xml, as discussed earlier.
  2. Create the spring-security.xml file under WEB-INF to map security constraints, which has the spring-security namespace mapping. You can read the discussion of how to configure the namespace.
  1. Add the basic <http> element, as shown in the following block of code:
        <security:http> 
          <security:intercept-url pattern="/data.htm"
access="hasRole('ROLE_USER')" /> <security:http-basic /> </security:http>

We will use security as a prefix because we defined it as a namespace, as discussed in the Configuring security in Spring via namespace section.

The preceding configuration tells the container to use basic authentication whenever someone tries to access the data.htm URL. If the credential entered by the user matches ROLE_USER, he will get the resource, otherwise, the access will be denied.

  1. We added the access for ROLE_USER, but we haven't provided the authentication provider that verifies whether the entered credentials are matching for the allowed role or not. Let's add the authentication provider in the context file as follows:
<security:authentication-manager> 
    <security:authentication-provider> 
      <security:user-service> 
         <security:user name="user1" password="user1"   
           authorities="ROLE_USER" /> 
         <security:user name="user2" password="user2"  
           authorities="ROLE_USER, ROLE_ADMIN" /> 
         <security:user name="admin" password="admin"  
           authorities="ROLE_ADMIN" /> 
      </security:user-service> 
   </security:authentication-provider> 
</security:authentication-manager>
  1. As there are multiple configuration files to be used by the Spring context, add contextConfigLocation to specify the list of files to be used for initialization. It can be done by updating the basic Front Controller mapping, as shown here:
<servlet> 
    <servlet-name>security</servlet-name> 
    <servlet-class> 
       org.springframework.web.servlet.DispatcherServlet 
        </servlet-class> 
    <init-param> 
      <param-name>contextConfigLocation</param-name> 
      <param-value>WEB-INF/security-servlet.xml WEB-INF/spring-security.xml</param-value> 
    </init-param> 
    <load-on-startup>1</load-on-startup> 
  </servlet> 
 
  <context-param> 
    <param-name>contextConfigLocation</param-name> 
    <param-value>WEB-INF/security-servlet.xml WEB-INF/spring-security.xml</param-value> 
  </context-param> 
  <listener> 
    <listener-class>     
      org.springframework.web.context.ContextLoaderListener 
    </listener-class> 
 </listener> 
  1. The following diagram gives us a clear idea about the flow of an application:
  1. On executing the project, we will get the the following output:

Now, we have a complete orientation about how to add security in the application. Here, we used basic authentication. The form that we got for authentication is always dependent on the client, which affects user experience. It doesn't have a logout concept. Once we execute an application and provide credentials, the output will always be the same, and our main motive to authenticate the user will be failed. Spring facilitates the form-based authentication under the situation where we need a login page with a good look and feel. It is also more secure. The form-based authentication allows us to configure a customized login page, discussed as follows. We will modify the Ch08_Security_Getting_Startetd application:

  1. The configuration that needs to be updated will be the <http> from the spring-security.xml file. Comment on the previous configuration in order to modify it. The updated configuration is as follows:
<security:http> 
    <security:intercept-url pattern="/data.htm" 
      access="hasRole('ROLE_USER')" /> 
    <security:form-login login-page="/mylogin.htm" 
      authentication-failure-url="/error.htm" /> 
    <security:csrf disabled="true"/> 
</security:http>

In the configuration, we specified the following:

    • The login page will be returned by the method mapped for URL as mylogin.htm.
    • In case of wrong credentials, the page will be provided by the method mapped for the error.htm URL.
    • csrf : The cross-site request forgery (CSRF) is disabled. The CSRF is an attack that happens when the action is taken by the browser, not because the user did it, but because an email, blog, or a program forced the browser to do so.
  1. Now DataController needs to be updated for handling the mylogin.htm and error.htm URLs, as shown in the following piece of code:
@RequestMapping("/mylogin.htm") 
   public ModelAndView login() 
   { 
      return new ModelAndView("login"); 
   } 
    
   @RequestMapping("/error.htm") 
   public ModelAndView login_fail() 
   { 
      return new ModelAndView("login","error","please provide correct credentials"); 
   } 
  1. The method is returning view name as login. It means that we need to add login.jsp under the jsps folder.
  2. The code for login.jsp is as follows:
<form action="<c:url value='/login'/>" method="post"> 
    <table align="center"> 
       <tr style="height: 50px"> 
          <td align="left">User Name</td> 
          <td><input type="text" name="username" value=""></td> 
        </tr> 
        <tr> 
           <td align="left">Password</td> 
           <td><input type="password" name="password"></td> 
        </tr> 
        <tr> 
           <td></td> 
           <td align="right"><input type="submit"   
                value="LOGIN"></td> 
        </tr> 
     </table> 
</form> 
<center> 
   <font color="red" style="font-style: italic; font-size: large;"> 
      <c:out value="${error}"></c:out> 
    </font> 
</center> 

To keep it simple, I have omitted the code for presentation.

  1. You are now set to run the application.
  2. From the index page, click on CLICK THE LINKS TO READ THE data!!!!.
  3. If you added the correct credentials for the user having a role as ROLE_USER from the xml configuration, you will get the success page. You will get the form and success page as shown in the following screenshot:

In both the demos, we used the credentials configured in the context file. Spring provides many authentication providers, one of which we used in the earlier demo. Let's explore it in depth.

AuthenticationManger is one who has the responsibility to pass the request to ProviderManager, who has the credential information against which the username and password will be verified. ProviderManger doesn't handle the request by itself, it forwards it to AuthenticationProviderS, which are configured in the Spring context. Once the request is delegated to ProviderManager, each of the configured AuthenticationProviderS will be queried one by one. The result returned by each of the provider will either be an exception if the credentials are not available, or if it's available, then an object of Authentication. Multiple AuthenticationProviderS can be configured as follows:

<bean id="authenticationManager" class=  
        "org.springframework.security.providers.ProviderManager"> 
    <property name="providers"> 
        <list> 
           <ref local="daoAuthenticationProvider"/> 
           <ref local="rememberMeAuthenticationProvider"/> 
        </list> 
    </property> 
</bean> 

Spring supports many third-party authentication providers, such as LDAP and CAS. UserDetailsService is used to look up for username, password, and GrantAuthoritieS. It is done by simply comparing the username and password obtained from UsernamePasswordAuthenticationToken against the loaded UserDetailsService from the configuration. Spring supplies two very useful implementations for authentication, as follows:

  • In-memory authentication
  • JDBC authentication
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.2.184