Based on the framework of the spring Apache Shiro simple integration

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

Safety protection about the project, I have been looking for a simple configuration can achieve the purpose of the method, since the contact Shiro, this goal was reached, the combining our experience using Shiro, talk about more portable integrated the function.

First, we first understand what is Shiro.

Apache Shiro is a powerful and easy-to-use Java security framework, for the developers to provide an intuitive and comprehensive solution for the authentication, authorization, encryption, session management.

In fact, according to my understanding, is a filter, according to the configuration (or notes) Rules for authorization.

The project management of Maven dependent jar package based on Apache Shiro, first of all need to use the jar introduction:

<!-- shiro -->


The shiro-web and shiro-spring must be, if you want to cache rights, the introduction of shiro-ehcache, using shiro-ehcache with said will be back.

Look at login.action is how to implement user login write access to the user, form information and query the database authentication is not to say, directly on the key code:

            //Verify that the user information by token write, here for simplicity, I and your ID name as token username and password
            UsernamePasswordToken token = new UsernamePasswordToken(m.getId()
                    .toString(), m.getUsername());
            Subject subject1 = SecurityUtils.getSubject();

Since it is a filter, then we will look at this filter method:



import javax.annotation.Resource;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;


public class shiroFilter implements Filter {

//Administrator user service @Resource private ManagerService managerService; @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { Subject subjects = SecurityUtils.getSubject(); HttpServletRequest requestHttp = (HttpServletRequest) request; HttpServletResponse responseHttp = (HttpServletResponse) response; Principal principal = requestHttp.getUserPrincipal(); if (null != principal) {

//principal.getName()The user ID is preserved in the, Is the login at the above information in token System.out.println(principal.getName()); Manager m = managerService.findOne(Long.parseLong(principal .getName())); if (null != m && 1 == m.getAudit()) { UsernamePasswordToken token = new UsernamePasswordToken( m.getId(), m.getId());//As an example, I just put the user ID into token, You can change into other complex point information Subject subject1 = SecurityUtils.getSubject(); subject1.login(token); subject1.getSession(); } else { if (subjects != null) { subjects.logout(); } } } chain.doFilter(requestHttp, responseHttp); } @Override public void destroy() { } }

At this point, can be said to login and filter has been completed. Then the web.xml and spring files as well as the realization of authentication.

1,The filter configuration with Shiro in web.xml:


This filter precedes all filter.

 2,Authorization code, we write a class realm integrated Shiro AuthorizingRealm


import javax.annotation.Resource;

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.authz.AuthorizationException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.SimplePrincipalCollection;

public class ShiroRealm extends AuthorizingRealm {

    protected AuthorizationInfo doGetAuthorizationInfo(
            PrincipalCollection principals) {
        if (principals == null) {
            throw new AuthorizationException(
                    "PrincipalCollection method argument cannot be null.");
        String username = (String) getAvailablePrincipal(principals);
        System.out.println("-------------------" + username);//The output is the user ID

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        // To increase the default role

/*The following users can access from the database roles and permissions information, Access to information can be added into info, Access to database specific code I omitted * ///// add a custom role// if (null != userInfo.getRoleList()) { // for (RoleInfo roleInfo : userInfo.getRoleList()) { // if (null != roleInfo.getName() // && !"".equals(roleInfo.getName())) { // info.addRole(roleInfo.getName()); // } // } // } // if (null != userInfo.getModuleInfo()) { // for (ModuleInfo moduleInfo : userInfo.getModuleInfo()) { // if (null != moduleInfo.getGuid() // && !"".equals(moduleInfo.getGuid())) { // info.addStringPermission(moduleInfo.getGuid()); // } // } // } return info; } @Override protected AuthenticationInfo doGetAuthenticationInfo( AuthenticationToken authcToken) throws AuthenticationException { UsernamePasswordToken token = (UsernamePasswordToken) authcToken; String userName = token.getUsername(); if (userName != null && !"".equals(userName)) { return new SimpleAuthenticationInfo(token.getPrincipal(), Token.getPassword (), token.getUsername()); } return null; } /* * * empty User Association certification authority, The next use reload. * * @Param principal / public void clearCachedAuthorizationInfo (String principal) {SimplePrincipalCollection principals = new SimplePrincipalCollection (principal, getName()); clearCachedAuthorizationInfo(principals); } /* * * clear all related certification */ public void clearAllCachedAuthorizationInfo() { Cache<Object, AuthorizationInfo> cache = getAuthorizationCache(); if (cache != null) { for (Object key : cache.keys()) { cache.remove(key); } } } }

3,The applicationContext.xml configuration (here only retains the Shiro related information)

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=""
    xmlns:aop="" xmlns:xsi=""
    xmlns:context="" xmlns:tx=""
    xsi:schemaLocation="              ">
<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
        <property name="securityManager" ref="securityManager" />
        <property name="successUrl" value="/manage/" />
        <property name="loginUrl" value="/manage/" />
        <property name="unauthorizedUrl" value="/manage/401.html" />
        <property name="filters">
                <entry key="authc" value-ref="shiro"></entry>
        <property name="filterChainDefinitions">
                /manage/admin.html = authc,perms[shiro_admin:view]



/manage/kindeditor/**=anon /manage/**=authc,roles["ROLE_USER"] /**=anon </value> </property> </bean> <bean id="shiro" class=""> </bean> <bean id="shiroRealm" class="" /> <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager"> <property name="realm" ref="shiroRealm" /> <property name="cacheManager" ref="shiroEhcacheManager" /> </bean> <!-- the user authorization information Cache, use EhCache, you need to configure the information --> <bean id="shiroEhcacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager"> <property name="cacheManagerConfigFile" value="classpath:ehcache-shiro.xml" /> </bean> <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor" /> <bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator" depends-on="lifecycleBeanPostProcessor"> <property name="proxyTargetClass" value="true" /> </bean> <bean class=""> <property name="securityManager" ref="securityManager" /> </bean> </beans>

Validation rules are static files such as JS to img directory configuration anon

/manage/admin.html = authc,perms[shiro_admin:view]









The end of day. Long time no write long articles, knocked up really difficult. The original article, this paper is an omission or mistake, please.

Author: blood and sand


The copyright belongs to the author and blog park there, welcome to reprint, but without the permission of the author must keep this statement, and the connection in the article page is the obvious position, or retain the right to pursue legal responsibilities.

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

Posted by Tracy at September 03, 2014 - 5:58 PM