Showing posts with label Spring Security. Show all posts
Showing posts with label Spring Security. Show all posts

Wednesday, 12 December 2012

URL Permission Based Security

Posted by Naveen Katiyar On 05:07 No comments

URL Permission Based User Interface Creation in Spring Security

In the previous tutorial, we learned how to customize jsp out put based on the role of the logged in user with the help of the Spring Security JSP Taglibs. Now, we will learn the way to customize the jsp page on the basis of a secure url. That means if the logged in user will have permission to visit the url specified in the taglib attribute, the particular jsp segment will be rendered otherwise, the segment will not shown to the user.
Think about the situation, when we are creating a common menu bar for the logged in users. The menu will contain link for the uses of admin as well as the customers. Some of the menu items are common to both users and some are specific to the admin or customer.
In such situation, we will use Url Permission Based User Interface Creation using Spring Security Taglibs. We will check if the user has permission to visit the menu url then the menu url will be shown to user otherwise menu link will not be shown.


The Tutorial is assuming that you have read following tutorials before reading this:
  1. Getting Started with Spring Security
  2. Role based Spring Security
Please read those tutorial or if you have prior knowledge of setting up Spring Security JSP Taglibs to use in jsp then you can continue with the tutorial.

Tools Used:
  • Spring MVC 3.0.3
  • Spring Security 3.0.5
  • Eclipse Indigo 3.7
  • Tomcat 6
  • Jdk 1.6

Tutorial Example and Explanation:

In our example, there are two users associated with the Spring Security Configuration: “admin” and “customer”. Both of them has different roles. But, the welcome page is the shared page between both the users where they are redirected after successful login. We have also two different urls “/admin/**” and “/users/**” configured in Spring Security Configuration file. Only admin user has rights to view pages under url “/admin/**” and only customer has permission to visit the url “/users/**”.

Spring Security Configuration file


<?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 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.0.xsd">
    <http realm="Project Realm" auto-config="true" use-expressions="true">
        <intercept-url pattern="/auth/**" filters="none"/>
        <intercept-url pattern="/admin/**" access="hasRole('ROLE_ADMIN')"/>
        <intercept-url pattern="/users/**" access="hasRole('ROLE_USER')"/>
        <intercept-url pattern="/**" access="hasAnyRole('ROLE_ADMIN','ROLE_USER')"/>
        <form-login login-page="/auth/login.jsp" authentication-failure-url="/auth/login.jsp?login_error=1"/>
        <logout logout-success-url="/auth/login.jsp"/>
        <remember-me />
    </http>

    <authentication-manager>
       <authentication-provider>
           <user-service>
               <user name="admin" password="admin" authorities="ROLE_ADMIN"/>
               <user name="customer" password="customer" authorities="ROLE_USER"/>
           </user-service>
       </authentication-provider>
    </authentication-manager>

</b:beans>
 

We have modified our configuration file as specified above.


Welcome page to create url permission based jsp segments 


<!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<%@ page session="true" %>
<%@ taglib uri="http://java.sun.com/jstl/core" prefix="c"%>
<%@ taglib uri="http://www.springframework.org/security/tags" prefix="sec"%>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Spring Security 3 JSP Taglibs- This is a secure page</title>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1251">
</head>
<body>
    <h1>Welcome!</h1><br />
    <sec:authorize url="/admin/*">
        This session will be visible to an admin only.<br/>
        You are an Administrator.<br/>
    </sec:authorize>
    <sec:authorize url="/users/*">
        This session will be visible to an Customer only.<br/>
        You are an Customer.<br/>
    </sec:authorize>
        ${HelloMessage}<br />
        <a href="<c:url value="/j_spring_security_logout"/>">Logout</a>
</body>
</html>
 

<sec:authorize url=”/admin/*”> : This means the jsp segment within <sec:authorize/> tag will only show to the logged in user if she/he has permission to view the pages under the url “/admin/*”.

So, if we login with the credentials of admin user we will message specific to the the admin only and same with the customer credentials.

Source code can be downloaded from previous tutorial and could be executed after
making above changes.

That's all for Spring Security Tutorial..... 

Happy Coding.
  

Role Based Spring Security

Posted by Naveen Katiyar On 04:51 No comments

Role Based User Interface Creation Using Spring JSP Taglibs

Spring Security provides jsp taglibs for customizing User Interface according the authenticated user’s role. We can make it possible to show some ui portion to user with role admin and not to others.

This tutorial is based on the previous Spring Security Tutorials. You should first read Getting Started with Spring Security tutorial and then read this tutorial for better understanding.

Tools Used:
  • Spring MVC 3.0.3
  • Spring JDBC 3.0.5
  • Spring Security 3.0.5
  • Eclipse Indigo 3.7
  • Tomcat 6
  • Jdk 1.6
 The tutorial will illustrate you an practical example in which there will be two users with different roles, “ROLE_ADMIN” and “ROLE_USER”.In the example we will modify our Getting Started with Spring Security example to implement role based ui modification using Spring Security JSP Taglibs. We will modify our welcome page to make some portion visible to admin and some portion to user.

Including Spring Security JSP Taglib

We have to add Spring Security Taglib to our jsp file to use this feature of role based user interface modification:


<%@ taglib uri="http://www.springframework.org/security/tags" prefix="sec" %>


Authorize tag in Spring Security taglib

Authorize tag is used for role based user interface creation. For example, if we want to create a jsp portion that will be visible to user with role “ROLE_ADMIN”, it will like following code:


<sec:authorize access="hasRole('ROLE_ADMIN')">
This session will be visible to an admin only.<br/>
You are an Administrator.<br/>
</sec:authorize>


If we put this code to jsp, the message will be shown only to the users with role “ROLE_ADMIN”. access” attribute is used to specify the Spring Security EL Expression and if the expression returns true for the loged in user only then the HTML code within “<sec:authorize/>” tag will be shown to user. The expression in access attribute is send to WebSecurityExpressionHandler defined in the web context. So we have to add WebSecurityExpressionHandler to out security context. It can be done in two ways:
  1. Use default WebSecurityExpressionHandler, which will be only available if we specify use-expressions=”true” in our Spring Security Configuration file under <http/> tag.
  2. Register your WebSecurityExpressionHandler in Spring Security Configuration file.


Common built-in expressions

Following are the common expressions that can be used in access attribute of “<sec:authorize/>” tag:
  • hasRole([role]) : Returns true only if the login user has the role specified in [role].
  • hasAnyRole([role1,role2]) : Returns true only if the login user has atleast one role specified in [role1,role2]. The roles will be specified in comma separated format.
  • isAnonymous() : Returns true only is the login user is an anonymous user.
  • isAuthenticated() : Returns true if the user is not an anonymous user.
  • isFullyAuthenticated() : Returns true if the user is not an anonymous user or a remember me user.
  • isRememberMe() : Returns true if the user is  a remember me user.

Our Example:

Modifying Spring Security Configuration File (spring-security.xml)


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

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.0.xsd">

<http realm="Project Realm" auto-config="true" use-expressions="true">
    <intercept-url pattern="/auth/**" filters="none"/>
    <intercept-url pattern="/**" access="hasAnyRole('ROLE_ADMIN','ROLE_USER')"/>
    <form-login login-page="/auth/login.jsp" authentication-failure-url="/auth/login.jsp?login_error=1"/>
    <logout logout-success-url="/auth/login.jsp"/>
    <remember-me />
</http>

<authentication-manager>
    <authentication-provider>
        <user-service>
            <user name="admin" password="admin" authorities="ROLE_ADMIN"/>
            <user name="customer" password="customer" authorities="ROLE_USER"/>
        </user-service>
    </authentication-provider>
</authentication-manager>

</b:beans>



We have modified security.xml to:
  • Create two users of different roles.
  • Specify the attribute use-expressions=”true”  in <http/> tag.
  • Provide both the user access to the page url “/**”.

 Modifing welcome.jsp


<!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<%@ page session="true" %>
<%@ taglib uri="http://java.sun.com/jstl/core" prefix="c"%>
<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title>Spring Security 3 JSP Taglibs- This is a secure page</title>
        <meta http-equiv="Content-Type" content="text/html; charset=windows-1251">
    </head>
    <body>
        <h1>Welcome!</h1><br />
        <sec:authorize access="hasRole('ROLE_ADMIN')">
         This session will be visible to an admin only.<br/>
         You are an Administrator.<br/>
        </sec:authorize>
        <sec:authorize access="hasRole('ROLE_USER')">
         This session will be visible to an Customer only.<br/>
         You are an Customer.<br/>
        </sec:authorize>
        ${HelloMessage}<br />
        <a href="<c:url value="/j_spring_security_logout"/>">Logout</a>
    </body>
</html>
 

We have just added two message. One for admin user and another for customer user.

Download Source Code



Spring Security with Custom Tables

Posted by Naveen Katiyar On 03:12 22 comments

Using custom tables for spring security authentication and authorization

It is not must to use database tables specified in the Spring Security Specification. We can also use our own custom database tables to store user authentication and authorization and use those tables in Spring Security for user authentication and authorizations with some restrictions shown bellow:
  • Your database tables should have enough columns to specify user authentication and role.
  • You have to specify the sql query for which will be used to get user details from your database tables.

We will modify our User authentication and authorization in Spring Security using MySQL tables example and use our own tables instead of Spring Security Specific database tables. So, if you have not read the above tutorial, please read it or if you have prior knowledge of setting up database authentication in Spring Security, you can go ahead.

Tools used :
  • Spring MVC 3.0.3
  • Spring JDBC 3.0.5
  • Spring Security 3.0.5
  • Eclipse Indigo 3.7
  • Tomcat 6
  • Jdk 1.6
  • MySQL 5.1 Database and Driver jar
In this tutorial, we will use our own tables in Spring Security and authenticate the user.

Custom Table Definations

In this example we will use following tables in our database to authenticate the user:


create table user_deatils (
    username varchar(50) primary key,
    password varchar(50) not null,
    name varchar(300) not null,
    address varchar(1000),
    enabled boolean not null
) engine = InnoDb;

create table user_roles(
    role_id integer primary key,
    role varchar(50) not null
) engine = InnoDb;

create table users_role_map (
    username varchar(50) not null,
    role_id integer not null,
    foreign key (username) references users (username),
    foreign key (role_id) references user_roles(role_id)
) engine = InnoDb;


For creating a user detail and role of the user in the database use following MySQL DML insert command :


insert into user_deatils values('admin','admin','Jency Marker','23 Street, Washington',1);
insert into user_roles values(1,'ROLE_ADMIN');
insert into users_role_map values('admin',1);


This will create a user with username and password as “admin” and with role “ROLE_ADMIN” in the custom database tables.


Modifying Spring Security Configuration File

We have to change our Spring Security Configuration file, so that Spring Security uses our custom tables. For this we have to specify two extra attributes in <jdbc-user-service/> tag as follows:


<authentication-manager>
    <authentication-provider>
        <jdbc-user-service data-source-ref="dataSource" users-by-username-query="select username,password, enabled
        from user_deatils where username=?" authorities-by-username-query="select ud.username, ur.role
        from user_deatils ud, user_roles ur,users_role_map urm
        where ud.username = urm.username and urm.role_id = ur.role_id and ud.username = ? "/>
    </authentication-provider>
</authentication-manager>

Here, there are two attributes that we have specified in <jdbc-user-service/> tag, both of them are actually specifying SQL queries that will be used by Spring Security to authenticate the user:

  • users-by-username-query : This attribute will hold the query according to your custom tables that will select username, password and enabled properties of the user and will take username as parameter.
  • authorities-by-username-query : This attribute will hold the SQL query according to your custom tables that will select username and role of the user and accept username as parameter .
That’s all for using custom database table for user authentication and authorization.


Download Source Code


click here to download the source code


Tuesday, 11 December 2012

Spring Security with MySQL tables

Posted by Naveen Katiyar On 21:03 No comments

User authentication and authorization in Spring Security using MySQL tables

It is always being desired to protect web application on the basis of the user details stored in some database Spring Security also provides facility for authenticating an user on the basis of database tables defined by Spring Security Framework i.e. the tables defined in the previous tutorial or on the basis of custom database tables.

Tools used :
  • Spring MVC 3.0.3
  • Spring JDBC 3.0.5
  • Spring Security 3.0.5
  • Eclipse Indigo 3.7
  • Tomcat 6
  • Jdk 1.6
In this tutorial, we will use database tables defined by Spring Security Framework for authentication and authorization of users. We will modify our Customizing Spring Security web MVC Application example to implement database based user authentication on the basis of table definitions defined in Spring Security.


Creating necessary tables in database

We will use MySQL database server for authenticating users. First of all, we have to create a schema in MySQL database. For user authentication and authorization we will create two tables as specified in the previous tutorial MySQL ddl tables definitions for Spring Security. As we will not use group level authorization in this example, so we will have to create only two tables “USERS” ans “AUTHORITIES” tables.


Run the following DDL  commands in MySQL command prompt:

create table users (
    username varchar(50) not null primary key,
    password varchar(50) not null,
    enabled boolean not null
) engine = InnoDb;

create table authorities (
    username varchar(50) not null,
    authority varchar(50) not null,
    foreign key (username) references users (username),
    unique index authorities_idx_1 (username, authority)
) engine = InnoDb;


 After that we have to create a user for login. Following DML insert commands will create a user with username “admin” and password “admin”:

 INSERT INTO users(`username`,`password`,`enabled`) VALUES( 'admin','21232f297a57a5a743894a0e4a801fc3',1);
INSERT INTO authorities(`username`,`authority`) VALUES('admin','ROLE_ADMIN');


Creating DataSource bean in Spring MVC

Our next work is to configure a datasource for the MySQL database. For this, we have to change our spring-servlet.xml file to configure datasource.

We will create a properties file (jdbc.properties) that will contain all database connection related information:


# database properties
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost/javapapers_demo
jdbc.username=root
jdbc.password=pass

You have to modify jdbc.properties according to your database information. We have to put following changes to our spring-servlet.xml:


<context:property-placeholder location="/WEB-INF/jdbc.properties" />

<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">>
    <property name="driverClassName" value="${jdbc.driverClassName}" />
    <property name="url" value="${jdbc.url}" />
    <property name="username" value="${jdbc.username}" />
    <property name="password" value="${jdbc.password}" />
</bean>


<context:property-placeholder/> tag will help to import the properties defined in the jdbc.properties file. After that we have configured
org.springframework.jdbc.datasource.DriverManagerDataSource class provided by the spring jdbc to configure as dataSource. ${jdbc.driverClassName} is used to replace the property value from jdbc.properties file using Spring EL.


Changing Spring Security settings
After that, we will change Spring Security Configuration file to use database tables for user authentication:



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

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.0.xsd">

<http realm="Project Realm" auto-config="true">
    <intercept-url pattern="/auth/**" access="IS_AUTHENTICATED_ANONYMOUSLY"/>
    <intercept-url pattern="/**" access="ROLE_ADMIN"/>
    <form-login login-page="/auth/login.jsp" authentication-failure-url="/auth/login.jsp?login_error=1"/>
    <logout logout-success-url="/auth/login.jsp"/>
    <remember-me />
</http>

    <authentication-manager>
        <authentication-provider>
            <password-encoder hash="md5"/>
            <jdbc-user-service data-source-ref="dataSource"/>
        </authentication-provider>
    </authentication-manager>
</b:beans>


There is only one change in our security.xml file. Instead of using <user/> tag, we have used <jdbc-user-service/> tag and provided the reference of our configured datasource to its data-source-ref property.


That is all, now our Spring Security example will use database for user authentication.



Download Source Code with jars

Click here to download source code

 


Monday, 10 December 2012

MySQL ddl tables definitions for Spring Security

Spring Security Framework can also be used to implement web security in project using database based authentications. Spring Security will use database tables to authenticate users. We can use any custom database table form authentications using Spring Security settings but Spring itself defines default table structures that can be used for authentication.
In this tutorial will will see the table structure specified by the Spring Security for MySQL database.In our next tutorial we will learn how to use these tables for Spring Security authentication with some small change in security settings. Table definitions are categorized according to the depth of the use of Spring Security Framework facilities. If you need only basic level authentication then just create the tables that are used for authentications. Spring Security has three levels of usability, according to which tables are categorized in three levels.
Following are the three categories and their respective ddl commands for tables in MySQL server syntax :
Tables for User Schema
Following tables are needed for the user authentication and role based authorization of the users:
create table users (
    username varchar(50) not null primary key,
    password varchar(50) not null,
    enabled boolean not null
) engine = InnoDb;
 
create table authorities (
    username varchar(50) not null,
    authority varchar(50) not null,
    foreign key (username) references users (username),
    unique index authorities_idx_1 (username, authority)
) engine = InnoDb;


If you create these two tables in MySQL database and configure this database with Spring Security, it will automatically use these tables for authentication and role determination purpose.


Spring Security will use “USERS” table for authentication and “AUTHORITIES” table for determination of role of the user for role based access control.

Table for Remember me facility
For using database used “Remember Me” facility in Spring Security, you have to create following tables :
create table persistent_logins (
    username varchar(64) not null,
    series varchar(64) primary key,
    token varchar(64) not null,
    last_used timestamp not null
) engine = InnoDb;

“persistent_logins” will store entries for the users who have used remember me option during login.

Tables for Roll based Group Schema
You can also use group based authorization that is provided by Spring Security using following tables:
create table groups (
    id bigint unsigned not null auto_increment primary key,
    group_name varchar(50) not null
) engine = InnoDb;
 
create table group_authorities (
    group_id bigint unsigned not null,
    authority varchar(50) not null,
    foreign key (group_id) references groups (id)
) engine = InnoDb;
 
create table group_members (
    id bigint unsigned not null auto_increment primary key,
    username varchar(50) not null,
    group_id bigint unsigned not null,
    foreign key (group_id) references groups (id)
) engine = InnoDb;


These tables are used by the Spring to maintain role based groups for the application. Any page can be defined accessible for a particular group.






Customizing Spring Security

Posted by Naveen Katiyar On 10:04 No comments

Customize Spring Security Settings

We can customize Spring Security settings to specify our own properties to be used by Spring. In this tutorial we will learn the setting that we can provide to use:
  1. Our own Login page.
  2. Specify the page to which the Spring Security will forward the user after logout.
  3. Put logout options in secure pages.
  4. Put an extra option of remember me in login form.
  5. Making a page public.
We will take our previous example of Getting Started with Spring Security and modify the example to do the above specified customization. So, you have not read the previous tutorial of configuring spring security then read from here.

Creating own Spring Security login  form (login.jsp)



<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!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>Login Page</title>
</head>
<body>
<form name="f" action="<c:url value='/j_spring_security_check'/>" method="POST">
      <table>
<tr><td colspan='2'>
<h1>Login</h1>

<c:if test="${not empty param.login_error}">
<font color="red">
Username and Password do not match. Try again.<br/><br/>
</font>
</c:if>
</td></tr>
        <tr><td>User:</td><td><input type='text' name='j_username' value='<c:if test="${not empty param.login_error}"><c:out value="${SPRING_SECURITY_LAST_USERNAME}"/></c:if>'/></td></tr>
        <tr><td>Password:</td><td><input type='password' name='j_password'></td></tr>
        <tr><td><input type="checkbox" name="_spring_security_remember_me"></td><td>Don't ask for my password for two weeks</td></tr>

        <tr><td colspan='2'><input name="submit" type="submit" value="Login"><input name="reset" type="reset"></td></tr>
      </table>

    </form>
</body>
</html>

Our login form must have two input boxes with name “j_username” for username and “j_password” for password. Name with “_spring_security_remember_me” checkbox is used when me want to use “remember me” option in our login form. “param.login_error” is the model object to store errors if username or password provided by the user is not valid. We have used this object to show customized error message in login form. “SPRING_SECURITY_LAST_USERNAME” model object stores last username that is invalid.


Changing Spring Security Setting in spring-security.xml

<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 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.0.xsd">

    
    <http realm="Project Realm" auto-config="true">
            <intercept-url pattern="/auth/**" access="IS_AUTHENTICATED_ANONYMOUSLY"/>
        <intercept-url pattern="/**" access="ROLE_ADMIN"/>
        <form-login login-page="/auth/login.jsp" authentication-failure-url="/auth/login.jsp?login_error=1"/>
        <logout logout-success-url="/auth/login.jsp"/>
        <remember-me />
    </http>

    <authentication-manager>
        <authentication-provider>
            <password-encoder hash="md5"/>
            <user-service>
                        <user name="admin" password="21232f297a57a5a743894a0e4a801fc3" authorities="ROLE_ADMIN"/>
            </user-service>
        </authentication-provider>
    </authentication-manager>
    
</b:beans>


We have modified our spring security configuration file to do the following:
  1. Defining own login page: We have define our own login form using the tag <form-login/>. login-page attribute is used to specify the page to be show to user for login purpose. authentication-failure-url attribute is used to specify the page to be show if login credentials are invalid.
  2. Activating “remember me” option: <remember-me /> tag is used to activate the remember me option in spring security. Spring Security will remember the user for two weeks.
  3. Defining logout page: <logout/> tag is used to define the page on which Spring Security will forward the user after successful logout.
  4. Making a page public: To make the login.jsp page public we have specified the access attribute as “IS_AUTHENTICATED_ANONYMOUSLY”. That means any one can open this page without authentication.

Creating logout option in secure pages (welcome.jsp)


<a href="<c:url value="/j_spring_security_logout"/>">Logout</a>

Put the above code in any secure page. The link will make the user logout. “/j_spring_security_logout” url is mapped to Spring Security classes that make the user logout.

That’s All Folks

You may want to run the application now and see the result. I assume you have already configured Tomcat in eclipse. All you need to do:
Open Server view from Windows > Show View > Server. Right click in this view and select New > Server and add your server details.
To run the project, right click on Project name from Project Explorer and select Run as > Run on Server (Shortcut: Alt+Shift+X, R).

Enter “scote” as username and “tigger” as password. Spring Security will show the error in login page:
Then, enter “admin” as username and password. It will show the welcome page with logout option in it.








Friday, 7 December 2012

Getting Started With Spring Security

Posted by Naveen Katiyar On 10:49 No comments

Getting Started With Spring Security

Spring Security is a security framework for authentication, authorization and role based authorization of the users.Spring Security Framework provides a lot of facilities to take care of the java web enterprise security management. Its really great security framework that work with Spring IoC or DI to inject the dependencies and securing the java web application.
Following are the some of the important facilities that Spring Security Framework provides to it’s users:
  • User authentication and authorization.
  • Role based authorization control.
  • Easy to configure with database based authentication and authorization.
  • Encrypted password.
  • Form authentication.
  • File bases user authentication and authorization.
  • and a lot more.
This tutorial will show you the way to configure Spring Security with Spring MVC web application to secure mvc pages. We will take an spring mvc web application example in which, we will configure Spring Security to protect a page from outside access.
Tools used :
  • Spring MVC 3.0.3
  • Spring Security 3.0.5
  • Eclipse Indigo 3.7
  • Tomcat 6
  • Jdk 1.6
To understand the example you will need to have prior knowledge of Spring MVC. If you do not know the basics of Spring MVC the go to our Spring MVC Tutorial.

In our example, there is an example of welcome page that is managed by Spring MVC framework. We will configure Spring Security in this example and will make the welcome page secure. User have to authenticate herself to view welcome page.

Configuring web.xml for Spring Security  

<?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 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.0.xsd">
   
    <http realm="Project Realm" auto-config="true">
        <intercept-url pattern="/**" access="ROLE_ADMIN"/>
    </http>

    <authentication-manager>
        <authentication-provider>
            <password-encoder hash="md5"/>
              <user-service>
                  <user name="admin" password="21232f297a57a5a743894a0e4a801fc3" authorities="ROLE_ADMIN"/>
              </user-service>
        </authentication-provider>
    </authentication-manager>
   
</b:beans>



In web.xml, we have configured Spring MVC to manage the request came for the URL “*.htm”. For configuring Spring Security we do the following :
  1. First of all, we have to register org.springframework.web.filter.DelegatingFilterProxy filter in web.xml. This filter manages the securing of the web pages.
  2. The filter will manage the requested URL “/*”. That means all the requests will go through the filter so that it can authenticate the user of particulate web pages that we will configured as secured pages with Spring Security.
  3. Register org.springframework.web.context.ContextLoaderListener listener provided in Spring so that it can configure spring context on server startup.
Creating home page (index.jsp)

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<jsp:forward page="/welcome.htm"></jsp:forward>




Creating welcome page (welcome.jsp)


<%@ page session="true" %>
<%@ taglib uri="http://java.sun.com/jstl/core" prefix="c"%>
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title>Configuring Spring Security 3 - This is a secure page</title>
        <meta http-equiv="Content-Type" content="text/html; charset=windows-1251">
    </head>
    <body>
        <h1>Welcome!</h1><br />
        ${HelloMessage}<br />
    </body>
</html>

Our welcome page is very simple that only shows a message that is stored in model object. The message is  provided by the controller class.

Creating Welcome Controller class (WelcomeController.java)  



package com.naveen.actions;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class WelcomeController {
@RequestMapping(value="/welcome",method=RequestMethod.GET)
public ModelAndView sayHello(Model model){
ModelAndView mv = new ModelAndView();
mv.setViewName("welcome");
model.addAttribute("HelloMessage", "Hello World from Spring Security application.");
return mv;
}
}


As you can see annotation driven configuration has been used to make WelcomeController class as a controller and the sayHello method will manage the request for /welcome url.

Spring Securing Configuration file (spring-securily.xml)

After that we will have to create a Spring Security Configuration file, in which have to define the security constrains that are to be applied to our application. You will see a lot of new things in this file. I will explain all the tags one by one make the things clear to you.


<?xml version="1.0" encoding="UTF-8"?>
<!--
- Application context containing authentication, channel
- security and web URI beans.
-
- Only used by "filter" artifact.
-
-->

<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 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.0.xsd">

<http realm="Project Realm" auto-config="true">
<intercept-url pattern="/**" access="ROLE_ADMIN"/>
</http>

<authentication-manager>
<authentication-provider>
<password-encoder hash="md5"/>
<user-service>
<user name="admin" password="21232f297a57a5a743894a0e4a801fc3" authorities="ROLE_ADMIN"/>
</user-service>
</authentication-provider>
</authentication-manager>
</b:beans>


  1. <http/> tag is used to define security setting for web application for defining access constrains for pages, defining login pages, login process to use, activate remember me option, customizing session level setting etc. Here we have used only one option i.e.  <intercept-url pattern=“/**” access=“ROLE_ADMIN”/>. <intercept-url/> tag is used to define url patterns to be secure and the definition of the roles who can access them.  In our example all url patters are secured and only user with role ROLE_ADMIN can access the pages.
  2. <authentication-manager/> tag is used to define method of authentication of the user on the basis of that user will be able to access a page.
  3. <authentication-provider/> tag specifies the username and password provider. It can be also a database table. Here we have used hard coded username and password. Password is encrypted in md5 algorithm.
Spring Configuration File (spring-servlet.xml) 

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" 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
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

<context:component-scan base-package="com" />
<mvc:annotation-driven />
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>

</beans>


That’s All Folks

The application is completed now. Just run the application in eclipse by pression Alt + Shift + X, R. It will show the login page. 

You would be thinking from where this login page has come,when we have not created any.THis login pagfe is provided by spring security.

WE will learn in another example about how to customize the login form.

Download Source Code

Click here to download source code