Quickstart Apache Shiro with Spring

Quickstart Apache Shiro with Spring

Apache Shiro is an Authentication Authorization framework with support for cryptography and session management. You can quickly create a layer of security around your application.

I used this framework with couple of project and now it’s my first go for authentication and authorization mechanism around any application, even over Spring Security. A lot of may like Spring Security because it comes with your spring and lot of community support and documentations.

You need to create a realm that provides all the logic of Authenticating a User and Authorizing it for any access. Below is a simple realm class. (Not doing any verification, just for demonstration)

Shiro Dependency

<!-- shiro dependency -->
		<dependency>
			<groupId>org.apache.shiro</groupId>
			<artifactId>shiro-all</artifactId>
			<version>1.1.0</version>
		</dependency>

Realm

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

public class MyRealm extends AuthorizingRealm {

	public MyRealm() {
		super();
		setCredentialsMatcher(new CredentialsMatcher() {
			
			@Override
			public boolean doCredentialsMatch(AuthenticationToken arg0,
					AuthenticationInfo arg1) {
				System.out
						.println("MyRealm.MyRealm().new CredentialsMatcher() {...}.doCredentialsMatch()");
				return true;
			}
		});
		
	}
	
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection arg0) {
		System.out.println("MyRealm.doGetAuthorizationInfo()");
		AuthorizationInfo info=new SimpleAuthorizationInfo();
		return info;
	}

	

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken arg0) throws AuthenticationException {
		System.out.println("MyRealm.doGetAuthenticationInfo()");
		UsernamePasswordToken token=(UsernamePasswordToken) arg0;
		
		AuthenticationInfo info=new SimpleAuthenticationInfo(1,token.getCredentials(), getName());
		return info;
	}

}

Spring Configuration for Shiro

<?xml version="1.0" encoding="UTF-8"?>
<beans 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.xsd">


<!-- Define the realm you want to use to connect to your back-end security datasource: -->
<bean id="myRealm" class="com.realm.MyRealm"></bean>

<bean id="securityManager" class="org.apache.shiro.mgt.DefaultSecurityManager">
    <!-- Single realm app.  If you have multiple realms, use the 'realms' property instead. -->
    <property name="realm" ref="myRealm"/>
    <property name="sessionManager.sessionListeners">
    	<list>
    	<ref bean="mySessionListener" />
    	</list>
    </property>
</bean>
<bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>

<!-- For simplest integration, so that all SecurityUtils.* methods work in all cases, -->
<!-- make the securityManager bean a static singleton.  DO NOT do this in web         -->
<!-- applications - see the 'Web Applications' section below instead.                 -->
<bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
    <property name="staticMethod" value="org.apache.shiro.SecurityUtils.setSecurityManager"/>
    <property name="arguments" ref="securityManager"/>
</bean>

<bean id="mySessionListener" class="com.listner.MySessionListener" ></bean>
</beans>

Demo

public class ShiroTest {
	
	public static void main(String[] args) {
		
		AbstractApplicationContext context=new ClassPathXmlApplicationContext("spring.xml");
		context.registerShutdownHook();
		
		
		org.apache.shiro.subject.Subject subject=SecurityUtils.getSubject();
		AuthenticationToken token=new UsernamePasswordToken("username", "password");
		System.out.println("Login a user--");
 		subject.login(token);
 		System.out.println("User logged in---");
 		subject.logout();
 		System.out.println("User logged out");
 		
	}

}

A fully functional demo available on GitHub https://github.com/ankitkatiyar91/java-framework-examples/tree/master/spring-examples/SpringShiro

Check CMS application that usages Shiro for security https://github.com/ankitkatiyar91/cms-java

Leave a Reply

Your email address will not be published. Required fields are marked *