Shiro权限相关配置文件

Stella981
• 阅读 533

Shiro权限框架

开发系统中,少不了权限,目前java里的权限框架有SpringSecurity和Shiro(以前叫做jsecurity),对于SpringSecurity:功能太过强大以至于功能比较分散,使用起来也比较复杂,跟Spring结合的比较好。对于初学Spring Security者来说,曲线还是较大,需要深入学习其源码和框架,配置起来也需要费比较大的力气,扩展性也不是特别强。

对于新秀Shiro来说,好评还是比较多的,使用起来比较简单,功能也足够强大,扩展性也较好。听说连Spring的官方都不用Spring Security,用的是Shiro,足见Shiro的优秀。

网上找到两篇介绍:

http://www.infoq.com/cn/articles/apache-shiro

http://www.ibm.com/developerworks/cn/opensource/os-cn-shiro/,

官网:http://shiro.apache.org/

使用和配置起来还是比较简单。下面只是简单介绍下我们是如何配置和使用Shiro的(暂时只用到了Shiro的一部分,没有配置shiro.ini文件)。

首先是添加过滤器,在web.xml中:

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

权限的认证类:

public class ShiroDbRealm extends AuthorizingRealm {
    @Inject
    private UserService userService ;
    
    /**
     * 认证回调函数,登录时调用.
     */
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) 
    throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
        User user= userService.getUserByUserId(token.getUsername());
        if (user!= null) {  
            return new SimpleAuthenticationInfo(user.getUserName()
                                                ,user.getPassWord()
                                                ,getName());
        } else {
            return null;
        }
    }
    /**
     * 授权查询回调函数, 进行鉴权但缓存中无用户的授权信息时调用.
     */
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        String loginName = (String) principals.fromRealm(getName()).iterator().next();
        User user= userService.getUserByUserId(loginName);
        if (user != null) {
            SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
            info.addStringPermission("common-user");
            return info;
        } else {
            return null;
        }
    }
}

Spring的配置文件:

<?xml version="1.0" encoding="UTF-8"?>
<beans >
    <description>Shiro Configuration</description>
    <bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor"/>
    <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
        <property name="realm" ref="shiroDbRealm" />
    </bean>
    <bean id="shiroDbRealm" class="com.company.service.common.shiro.ShiroDbRealm" />
    <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
        <property name="securityManager" ref="securityManager"/>
        <property name="loginUrl" value="/common/security/login" />
        <property name="successUrl" value="/common/security/welcome" />
        <property name="unauthorizedUrl" value="/common/security/unauthorized"/>
        <property name="filterChainDefinitions">
            <value>
                /resources/** = anon
                /manageUsers = perms[user:manage]
            </value>
        </property>
    </bean>
    <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor" />
    <bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator" depends-on="lifecycleBeanPostProcessor"/>
    <bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
        <property name="securityManager" ref="securityManager"/>
    </bean>
</beans>

登录的Controller:

@Controller
@RequestMapping(value = "/common/security/*")
public class SecurityController {
    @Inject
    private UserService userService;
    @RequestMapping(value = "/login")
    public String login(String loginName, String password,
                        HttpServletResponse response, 
                        HttpServletRequest request) throws Exception {
            User user = userService.getUserByLogin(loginName);
            if (null != user) {
                setLogin(loginInfoVO.getuserName(), loginInfoVO.getUserId());
                return "redirect:/common/security/welcome";
            } else {
                return "redirect:/common/path?path=showLogin";
            }
    };
    public static final void setLogin(String userName, String password) {
        Subject currentUser = SecurityUtils.getSubject();
        if (!currentUser.isAuthenticated()) {
            //collect user principals and credentials in a gui specific manner 
            //such as username/password html form, X509 certificate, OpenID, etc.
            //We'll use the username/password example here since it is the most common.
            //(do you know what movie this is from? ;)
            UsernamePasswordToken token = new UsernamePasswordToken(userName, password);
            //this is all you have to do to support 'remember me' (no config - built in!):
            token.setRememberMe(true);
            currentUser.login(token);
        }
    };
    
    @RequestMapping(value="/logout")
    @ResponseBody
    public void logout(HttpServletRequest request){
        Subject subject = SecurityUtils.getSubject();
        if (subject != null) {           
            subject.logout();
        }
        request.getSession().invalidate();
    };
}

注册和获取当前登录用户:

public static final void setCurrentUser(User user) {
   Subject currentUser = SecurityUtils.getSubject();
   if (null != currentUser) {
       Session session = currentUser.getSession();
       if (null != session) {
           session.setAttribute(Constants.CURRENT_USER, user);
       }
   }
 }
public static final User getCurrentUser() {
    Subject currentUser = SecurityUtils.getSubject();
    if (null != currentUser) {
        Session session = currentUser.getSession();
        if (null != session) {
            User user = (User) session.getAttribute(Constants.CURRENT_USER);
            if(null != user){
                return user;
            }
        }
    }
}
/**
 * 清除所有用户授权信息缓存.    
 */    
public void clearAllCachedAuthorizationInfo() {    
    Cache<Object, AuthorizationInfo> cache = getAuthorizationCache();    
    if (cache != null) {    
        for (Object key : cache.keys()) {    
            cache.remove(key);    
        }    
    }    
}

需要的jar包有3个:shiro-core.jar,shiro-spring.jar,shiro-web.jar。感觉shiro用起来比SpringSecurity简单很多。

点赞
收藏
评论区
推荐文章
blmius blmius
3年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
Jacquelyn38 Jacquelyn38
3年前
2020年前端实用代码段,为你的工作保驾护航
有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )
待兔 待兔
2个月前
手写Java HashMap源码
HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22
kenx kenx
3年前
轻松上手SpringBoot+SpringSecurity+JWT实RESTfulAPI权限控制实战
前言我们知道在项目开发中,后台开发权限认证是非常重要的,springboot中常用熟悉的权限认证框架有,shiro,还有就是springboot全家桶的security当然他们各有各的好处,但是我比较喜欢springboot自带的权限认证框架xmlorg.springframework.bootspr
Stella981 Stella981
2年前
Spring Security使用详解1(基本用法 )
一般项目都会有严格的认证和授权操作,而在Java开发领域常见的安全框架有Shiro和SpringSecurity。本文首先介绍下后者。一、基本用法1、什么是SpringSecurity?SpringSecurity是一个相对复杂的安全管理框架,功能比Shiro更加强大,权限控制细粒度更高,对O
Stella981 Stella981
2年前
Shiro 核心功能案例讲解 基于SpringBoot 有源码
Shiro核心功能案例讲解基于SpringBoot有源码从实战中学习Shiro的用法。本章使用SpringBoot快速搭建项目。整合SiteMesh框架布局页面。整合Shiro框架实现用身份认证,授权,数据加密功能。通过本章内容,你将学会用户权限的分配规则,SpringBoot整合Sh
Wesley13 Wesley13
2年前
00:Java简单了解
浅谈Java之概述Java是SUN(StanfordUniversityNetwork),斯坦福大学网络公司)1995年推出的一门高级编程语言。Java是一种面向Internet的编程语言。随着Java技术在web方面的不断成熟,已经成为Web应用程序的首选开发语言。Java是简单易学,完全面向对象,安全可靠,与平台无关的编程语言。
Wesley13 Wesley13
2年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
Python进阶者 Python进阶者
8个月前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这