Search This Blog

Wednesday, 8 June 2011

Custom Roles in Spring Security

By default, Spring Security accepts roles like 'ROLE_ADMIN', 'ROLE_USER'.
We can change this default behavior by changing the Role Prefix from "Role_" to "".
In order to achieve this, we will add following code in the applicationContext-security.xml of our Login Example.
    <beans:bean id="roleVoter"
        class="org.springframework.security.vote.RoleVoter ">
        <beans:property name="rolePrefix" value="" />
    </beans:bean>
    <beans:bean id="authenticatedVoter"  class="org.springframework.security.vote.AuthenticatedVoter" />
    <beans:bean id="accessDecisionManager"  class="org.springframework.security.vote.AffirmativeBased">
    <beans:property name="decisionVoters">
        <beans:list>
            <beans:ref bean="roleVoter" />
            <beans:ref bean="authenticatedVoter" />
        </beans:list>
    </beans:property>
    </beans:bean>
After this, we can use our custom roles like 'admin' and 'user' instead of 'ROLE_ADMIN' and 'ROLE_USER'.
<authentication-provider>
        <password-encoder hash="md5"/>
        <user-service>
            <user name="sandeep" password="00f1de4e151ccfc1fc9ff735a5efc479" authorities="admin,user" />
            <user name="vijay" password="e555f863fb09593119fe2f3459e9783a" authorities="user" />
        </user-service>
 </authentication-provider> 

Configuring Logout in Spring Security

We will change the applicationContext-security.xml of our login example, to configure logout.
we will add logout tag in the http Section.
<http auto-config="true" access-denied-page="/deniedPage.jsp">
    <intercept-url pattern="/securePage**" access="ROLE_ADMIN" />
    <intercept-url pattern="/**" access="IS_AUTHENTICATED_ANONYMOUSLY" />
    <form-login login-processing-url="/j_spring_security_check"
                login-page="/login.jsp"
                default-target-url="/securePage.jsp"
                authentication-failure-url="/login.jsp" />
    <logout    logout-url="/j_spring_security_logout" invalidate-session="true" logout-success-url="/login.jsp" />
</http>
It is obvious from the configuration that session will be invalidated and login page will be displayed after logout.    

Using Spring Security with JDBC

First we need two tables.We will execute the following queries to create the tables.
create table users (username varchar(50) not null primary key,password varchar(50) not null,enabled boolean not null);

create table authorities (
    username varchar(50) not null,
    authority varchar(50) not null,
    foreign key (username) references users (username),
    unique index ix_auth_username (username, authority)
);
Then, we will insert some data into the tables.
INSERT INTO users VALUES ('sandeep', '00f1de4e151ccfc1fc9ff735a5efc479', true);
INSERT INTO users VALUES ('vijay',   'e555f863fb09593119fe2f3459e9783a', true);
INSERT INTO authorities VALUES ('sandeep', 'ROLE_ADMIN');
INSERT INTO authorities VALUES ('sandeep', 'ROLE_USER');
INSERT INTO authorities VALUES ('vijay',   'ROLE_USER');
Now we will change the applicationContext-security.xml of our login example, to configure JDBC.

    
        
         
         
    
Finally,we need the 'datasource.xml'. This is based on MySQL.


    
        
            com.mysql.jdbc.Driver
        
        
            jdbc:mysql://localhost:3306/test
        
        
            root
        
        
            sandeep
        
    

Using MD5 Encrypted Password in Spring Security

We need following changes in the applicationContext-security.xml of our login example,
<authentication-provider>
<password-encoder hash="md5"/>
        <user-service>
            <user name="sandeep" password="00f1de4e151ccfc1fc9ff735a5efc479" authorities="ROLE_ADMIN, ROLE_USER"/>
            <user name="vijay" password="e555f863fb09593119fe2f3459e9783a" authorities="ROLE_USER"/>
        </user-service>
</authentication-provider>
Here,"00f1de4e151ccfc1fc9ff735a5efc479" is the MD5 encryption for "swastik"
We can use http://md5encrypter.com/ to encrypt the password.

Friday, 13 May 2011

Spring Security Login Example

In this example, we will create a simple application to understand the basics of Spring Security.First we will understand the flow of the application.We will access our application using the link, http://localhost:8080/SimpleSpringSecurity.It will display the following page:















We will enter 'sandeep' and 'swastik' in username and password fields respectively.After hitting the Login button, we will see the secure page.(Sandeep is an Admin, so he is allowed to see the secure Page)







We will login again, this time with 'vijay' and 'yadav' in the username/password field.This time we will see the Denied Page.(Vijay is a normal User, therefore he can't see the Secure Page)









Step1 : Login Page
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Login Page</title>
</head>
<body>
<h1>Login</h1>
<form action="/SimpleSpringSecurity/j_spring_security_check" method="post">
    <label for="j_username">Username</label>
    <input id="j_username" name="j_username" type="text" /> <br />
    <label for="j_password">Password</label>
    <input id="j_password" name="j_password" type="password" /> <br/>
    <input type="submit" value="Login" />
</form>
</body>
</html>

This is ia simple login page (login.jsp) with Usename,password fields and Login button.

Step2 : Spring Security Configuration
<?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/beans
                         http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
                        http://www.springframework.org/schema/security
                         http://www.springframework.org/schema/security/spring-security-2.0.1.xsd">
    <global-method-security
  secured-annotations="enabled">
    </global-method-security>
    <http auto-config="true" access-denied-page="/deniedPage.jsp">
    <intercept-url pattern="/securePage**" access="ROLE_ADMIN" />
    <intercept-url pattern="/**" access="IS_AUTHENTICATED_ANONYMOUSLY" />
    <form-login login-processing-url="/j_spring_security_check"
       login-page="/login.jsp"
       default-target-url="/securePage.jsp"
       authentication-failure-url="/login.jsp" />    
    </http> 
 <!--
    Use These Usernames/Passwords
    sandeep/swastik
    vijay/yadav
    -->
    <authentication-provider>    
        <user-service>
            <user name="sandeep" password="swastik" authorities="ROLE_ADMIN, ROLE_USER" />
            <user name="vijay" password="yadav" authorities="ROLE_USER" />
        </user-service>
    </authentication-provider>
</beans:beans>

Keep this file(applicationContext-security.xml) in WEB-INF folder.

Step3 : Edit web.xml
<?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"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="springsecurity"    version="2.5">   
<welcome-file-list>
<welcome-file>/login.jsp</welcome-file>
</welcome-file-list>
<session-config>
<session-timeout>10</session-timeout>
</session-config>
<!-- Spring Config -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/applicationContext-security.xml
</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<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>
<dispatcher>FORWARD</dispatcher>
<dispatcher>REQUEST</dispatcher>
</filter-mapping>
</web-app>
Step4 : securePage.jsp
<html>
<head>
<title>Secure Page</title>
</head>
<body>
<h2>Welcome to the Secure Page</h2>
</body>
</html>
Step 5: deniedPage.jsp
<html>
<head>
<title>Denied Page</title>
</head>
<body>
<h2>Access Denied</h2>
</body>
</html>