SpringMVC集成shiro权限(附源码)

springMVC框架这里就不多说了,下面是在springMVC框架上面直接集成shiro代码步骤

下面是我项目结构:

1、web.xml添加Shiro Filter

<filter>
		<filter-name>shiroFilter</filter-name>
		<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
		<init-param>
			<param-name>targetFilterLifecycle</param-name>
			<param-value>true</param-value>
		</init-param>
</filter>
<filter-mapping>
		<filter-name>shiroFilter</filter-name>
		<url-pattern>/*</url-pattern>
</filter-mapping>

2、添加applicationContext-shiro.xml文件

applicationContext-shiro.xml

<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
        http://www.springframework.org/schema/context  http://www.springframework.org/schema/context/spring-context-4.0.xsd"
       default-lazy-init="true">

    <description>Shiro Configuration</description>

    <!-- shiroFilter工厂 -->
    <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
        <!-- 构建securityManager环境 -->
        <property name="securityManager" ref="securityManager" />
        <!-- 要求登录时的链接(可根据项目的URL进行替换),非必须的属性,默认会自动寻找Web工程根目录下的"/login.jsp"页面 -->
        <property name="loginUrl" value="/sys/auth/logon"/>
        <!-- 登录成功后要跳转的连接 -->
        <property name="successUrl" value="/sys/main"/>
        <!-- 没有权限返回的地址 (拒绝访问路径)-->
        <property name="unauthorizedUrl" value="/sys/auth/refused" />
        <property name="filterChainDefinitions">
            <value>
                /static/**=anon
                /sys/auth/login=anon
                /sys/auth/logout=anon
                /**=authc
            </value>
        </property>
    </bean>
    <!-- securityManager -->
    <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
        <!--调用自定义realm -->
        <property name="realm" ref="realm" />
    </bean>
    <bean id="realm" class="com.qianxunclub.admin.sys.shiro.Realm"></bean>

    <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>

    <!-- AOP式方法级权限检查  -->
    <bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator" depends-on="lifecycleBeanPostProcessor">
        <property name="proxyTargetClass" value="true" />
    </bean>
    <bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
        <property name="securityManager" ref="securityManager"/>
    </bean>

</beans>

realm这里主要是设置自定义的单Realm应用,若有多个Realm,可使用'realms'属性代替,改配置也是主要的校验逻辑

3、添加Realm类

package com.qianxunclub.admin.sys.shiro;

import com.qianxunclub.admin.sys.constant.SysConstant;
import com.qianxunclub.admin.sys.model.domain.SysResource;
import com.qianxunclub.admin.sys.model.domain.SysRole;
import com.qianxunclub.admin.sys.model.domain.SysUser;
import com.qianxunclub.admin.sys.model.request.SysResourceParam;
import com.qianxunclub.admin.sys.model.request.SysRoleParam;
import com.qianxunclub.admin.sys.service.SysResourceService;
import com.qianxunclub.admin.sys.service.SysRoleService;
import com.qianxunclub.admin.sys.service.SysUserService;
import com.qianxunclub.util.Encodes;
import com.qianxunclub.util.StringUtil;
import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.ArrayList;
import java.util.List;

import static com.qianxunclub.util.Encodes.encodeToMD5;

public class Realm extends AuthorizingRealm {
    private Logger logger = Logger.getLogger(getClass());
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysRoleService sysRoleService;
    @Autowired
    private SysResourceService sysResourceService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        String username = (String)super.getAvailablePrincipal(principalCollection);
        if(StringUtil.isNotEmpty(username)){
            //从数据库中获取当前登录用户的详细信息
            SysUser sysUser = sysUserService.getByUsername(username).getDataInfo();
            if(sysUser == null){
                throw new AuthorizationException();
            }
            //为当前用户设置角色和权限
            SimpleAuthorizationInfo simpleAuthorInfo = new SimpleAuthorizationInfo();
            List<String> roleList = new ArrayList<String>();
            SysRoleParam sysRoleParam = new SysRoleParam();
            sysRoleParam.setUserId(sysUser.getId());
            sysRoleParam.setOrgId(sysUser.getOrgId());
            List<SysRole> sysRoles = sysRoleService.roleListByUser(sysRoleParam);
            for(SysRole sysRole : sysRoles){
                roleList.add(sysRole.getId());
            }
            List<String> permissionList = new ArrayList<String>();
            SysResourceParam param = new SysResourceParam();
            param.setRoleList(roleList);
            List<SysResource> sysResourceList = sysResourceService.resourceListByRole(param);
            for(SysResource sysResource : sysResourceList){
                permissionList.add(sysResource.getId());
            }
            simpleAuthorInfo.addRoles(roleList);
            simpleAuthorInfo.addStringPermissions(permissionList);
            return simpleAuthorInfo;
        } else {
            return null;
        }
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        SysUser sysUser = sysUserService.getByUsername(token.getUsername()).getDataInfo();
        if (null != sysUser) {
            String password = Encodes.encodeToMD5(new String(token.getPassword()) + sysUser.getSalt());
            token.setPassword(password.toCharArray());
            AuthenticationInfo authcInfo = new SimpleAuthenticationInfo(sysUser.getUsername(), sysUser.getPassword(), sysUser.getName());
            this.setSession(SysConstant.USER_SESSION, sysUser);
            return authcInfo;
        } else {
            return null;
        }
        //没有返回登录用户名对应的SimpleAuthenticationInfo对象时,就会在LoginController中抛出UnknownAccountException异常
    }

    /**
     * 将一些数据放到ShiroSession中,以便于其它地方使用
     * 比如Controller,使用时直接用HttpSession.getAttribute(key)就可以取到
     */
    private void setSession(String key, Object value){
        Subject currentUser = SecurityUtils.getSubject();
        if(null != currentUser){
            Session session = currentUser.getSession();
            if(null != session){
                session.setAttribute(key, value);
            }
        }
    }
}

4、下面就是授权的controller和service了

我这里登陆的逻辑都写在service里面,controller只做了一个接受参数的步骤
AuthController.java

package com.qianxunclub.admin.sys.controller;


import com.qianxunclub.admin.sys.model.request.SysUserParam;
import com.qianxunclub.admin.sys.service.AuthService;
import com.qianxunclub.context.controller.BaseController;
import com.qianxunclub.util.BaseResponse;
import com.qianxunclub.util.HttpResponseUtil;
import com.qianxunclub.util.JsonUtil;
import com.qianxunclub.util.ReturnCode;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@Controller
@RequestMapping(value = "/sys/auth")
public class AuthController extends BaseController {

    private Logger logger = Logger.getLogger(getClass());

    @Autowired
    private AuthService authService;

    @RequestMapping(value = "/logon", method = {RequestMethod.POST,RequestMethod.GET})
    public String logon(HttpServletResponse resp) {
        return "login";
    }

    @ResponseBody
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public void login(HttpServletRequest request, HttpServletResponse resp, SysUserParam param) {

        BaseResponse baseResponse;
        baseResponse = param.validate();
        if(!baseResponse.isSuccess()){
            String responseStr = JsonUtil.objectToJson(baseResponse);
            HttpResponseUtil.setResponseJsonBody(resp, responseStr);
            return;
        }
        baseResponse = authService.login(request,param);
        String responseStr = JsonUtil.objectToJson(baseResponse);
        HttpResponseUtil.setResponseJsonBody(resp, responseStr);
    }

    @ResponseBody
    @RequestMapping(value = "/relogin", method = {RequestMethod.POST,RequestMethod.GET})
    public void relogin(HttpServletResponse resp) {
        BaseResponse baseResponse = new BaseResponse();
        baseResponse.setReturn(ReturnCode.CODE_1008);
        String responseStr = JsonUtil.objectToJson(baseResponse);
        HttpResponseUtil.setResponseJsonBody(resp, responseStr);
    }

    @ResponseBody
    @RequestMapping(value = "/refused", method = {RequestMethod.POST,RequestMethod.GET})
    public void refused(HttpServletResponse resp) {
        BaseResponse baseResponse = new BaseResponse();
        baseResponse.setReturn(ReturnCode.CODE_1001);
        String responseStr = JsonUtil.objectToJson(baseResponse);
        HttpResponseUtil.setResponseJsonBody(resp, responseStr);
    }

    @ResponseBody
    @RequestMapping(value = "/logout", method = {RequestMethod.POST,RequestMethod.GET})
    public void logout(HttpServletResponse resp) {
        BaseResponse baseResponse = new BaseResponse();
        authService.logout();
        baseResponse.setReturn(ReturnCode.CODE_1000);
        String responseStr = JsonUtil.objectToJson(baseResponse);
        HttpResponseUtil.setResponseJsonBody(resp, responseStr);
    }

}

AuthService.java

package com.qianxunclub.admin.sys.service;

import com.qianxunclub.admin.sys.constant.MassageConstant;
import com.qianxunclub.admin.sys.constant.SysConstant;
import com.qianxunclub.admin.sys.model.domain.SysUser;
import com.qianxunclub.admin.sys.model.request.SysUserParam;
import com.qianxunclub.context.service.MessageService;
import com.qianxunclub.util.BaseResponse;
import com.qianxunclub.util.ReturnCode;
import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;


/**
 * Created by zhangbin on 2017/3/10.
 */
@Component
public class AuthService {

    private Logger logger = Logger.getLogger(getClass());

    @Autowired
    private MessageService messageService;
    @Autowired
    private SysUserRoleService sysUserRoleService;

    public BaseResponse login(HttpServletRequest request,SysUserParam param){
        BaseResponse baseResponse;
        baseResponse = this.validateUser(param);
        if(!baseResponse.isSuccess()){
            return baseResponse;
        }
        SysUser sysUser = (SysUser)request.getSession().getAttribute(SysConstant.USER_SESSION);



        return baseResponse;
    }

    public void logout() {
        SecurityUtils.getSubject().logout();
    }

    private BaseResponse validateUser(SysUserParam param){
        BaseResponse baseResponse = new BaseResponse();
        String message = null;
        Integer code = ReturnCode.CODE_1000.code();
        String username = param.getUsername();
        String password = param.getPassword();
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        token.setRememberMe(param.isRememberMe());
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(token);
        } catch (UnknownAccountException uae) {
            message = messageService.message(MassageConstant.LOGIN_USER_REEOE);
            logger.error(message,uae);
        } catch (IncorrectCredentialsException ice) {
            message = messageService.message(MassageConstant.LOGIN_USER_REEOE);
            logger.error(message,ice);
        } catch (LockedAccountException lae) {
            message = messageService.message(MassageConstant.LOGIN_USER_LOCK);
            logger.error(message,lae);
        } catch (ExcessiveAttemptsException eae) {
            message = messageService.message(MassageConstant.LOGIN_USER_MORE);
            logger.error(message,eae);
        } catch (AuthenticationException ae) {
            //通过处理Shiro的运行时AuthenticationException就可以控制用户登录失败或密码错误时的情景
            message = messageService.message(MassageConstant.LOGIN_USER_REEOE);
            logger.error(message,ae);
        }
        //验证是否登录成功
        if (!subject.isAuthenticated()) {
            code = ReturnCode.CODE_1006.code();
            token.clear();
        }
        baseResponse.setReturnCode(code);
        baseResponse.setMessage(message);
        return baseResponse;
    }


}

下面是定义的常量提示语

    /**
     *用户名或密码错误
     */
    public static final String LOGIN_USER_REEOE = "LOGIN_USER_REEOE";
    /**
     *用户被锁定
     */
    public static final String LOGIN_USER_LOCK = "LOGIN_USER_LOCK";
    /**
     *密码错误次数已达上限
     */
    public static final String LOGIN_USER_MORE = "LOGIN_USER_MORE";

到这里就已经完成了shiro的添加了,启动程序,体验一把吧!

附件

代码是使用maven构建的,maven就不多说了

主程序:https://git.oschina.net/qianxunclub/asone.git

改程序依赖了我的另一个jar包,也需要下载编译的

https://git.oschina.net/qianxunclub/asone-core.git

下载完成后,在asone-core根目录执行

mvn clean install -Dmaven.test.skip=true

完成后,打开asone项目,启动就可以成功启动了

下面是我已经部署好的项目,可以预览一下:
http://asone.qianxunclub.com/





原文地址:http://qianxunclub.com/springmvcji-cheng-shiroquan-xian-fu-yuan-ma/
本文由 千寻啊千寻创作。可自由转载、引用,但需署名作者且注明文章出处。

上一篇 :   Ghost 开源博客使用七牛、又拍云、阿里云OSS云储存

下一篇 :   基于HTML5 SVG可互动的3D标签云jQuery插件

热门评论