Shiro | 实现权限验证完整版

写在前面的话

提及权限,就会想到安全,是一个十分棘手的话题。这里只是作为学校Shiro的一个记录,而不是,权限就应该这样设计之类的。

Shiro框架

1、Shiro是基于Apache开源的强大灵活的开源安全框架。

2、Shiro提供了 认证授权企业会话管理安全加密缓存管理

3、Shiro与Security对比

Shiro与Security对比

4、Shiro整体架构

Shiro整体架构图

5、特性

Shiro特性

6、认证流程

Shiro认证流程

认证

当我们理解Shiro之后,我们就能比较容易梳理出认证流程,大概就是下面这样子。

Shiro认证流程

我们来看一段测试代码:

// 1.构建SecurityManager环境
DefaultSecurityManager defaultSecurityManager = new DefaultSecurityManager();
defaultSecurityManager.setRealm(simpleAccountRealm);

// 2.主体提交认证请求
SecurityUtils.setSecurityManager(defaultSecurityManager);
Subject subject = SecurityUtils.getSubject();

// 3.认证
UsernamePasswordToken token = new UsernamePasswordToken("admin", "admin");
subject.login(token);
System.out.println("是否认证:" + subject.isAuthenticated());

// 4.退出
subject.logout();
System.out.println("是否认证:" + subject.isAuthenticated());

我们发现Shiro真正帮我们做的就是认证这一步,那他到底是如何去认证的呢?

Shiro登录过程

我们把我们登录的代码完善一下:

/**
 * 登录操作,返回登录认证信息
 * @return 登录结果
 */
public String login() {
    try {
        DefaultSecurityManager defaultSecurityManager = new DefaultSecurityManager();
        defaultSecurityManager.setRealm(simpleAccountRealm);

        SecurityUtils.setSecurityManager(defaultSecurityManager);
        Subject subject = SecurityUtils.getSubject();

        UsernamePasswordToken token = new UsernamePasswordToken("admin", "admin");
        
        subject.login(token);
        if (subject.isAuthenticated())
            return  "登录成功";
    } catch (IncorrectCredentialsException e1) {
        e1.printStackTrace();
        return "密码错误";
    } catch (LockedAccountException e2) {
        e2.printStackTrace();
        return "登录失败,该用户已被冻结";
    } catch (AuthenticationException e3) {
        e3.printStackTrace();
        return "该用户不存在";
    } catch (Exception e) {
        e.printStackTrace();
    }
    return "登录失败";
}

Realm

1、IniReam

配置文件 user.ini

[users]
Mark=admin,admin
[roles]
admin=user:add,user:delete,user:update,user:select

测试代码

// IniRealm 测试
@Test
public void testAuthenticationIniRealm () {

    IniRealm iniRealm = new IniRealm("classpath:user.ini");

    DefaultSecurityManager defaultSecurityManager = new DefaultSecurityManager();
    defaultSecurityManager.setRealm(iniRealm);

    SecurityUtils.setSecurityManager(defaultSecurityManager);
    Subject subject = SecurityUtils.getSubject();

    UsernamePasswordToken token = new UsernamePasswordToken("admin", "123456");
    subject.login(token);

    System.out.println("是否认证:" + subject.isAuthenticated());

    subject.checkRole("admin");
    subject.checkPermission("user:delete");

}

2、JdbcRealm

这里有两种方案,使用Shiro为我们提供了SQL语句,或者我们自己写SQL语句。

第一种:

// JdbcRealm 测试 Shiro SQL
@Test
public void testAuthenticationShiroSQL() {

    JdbcRealm jdbcRealm = new JdbcRealm();
    jdbcRealm.setDataSource(druidDataSource);
    jdbcRealm.setPermissionsLookupEnabled(true);

    DefaultSecurityManager defaultSecurityManager = new DefaultSecurityManager();
    defaultSecurityManager.setRealm(jdbcRealm);

    SecurityUtils.setSecurityManager(defaultSecurityManager);
    Subject subject = SecurityUtils.getSubject();

    UsernamePasswordToken token = new UsernamePasswordToken("xfsy", "xfsy2018");
    subject.login(token);

    System.out.println("是否认证:" + subject.isAuthenticated());

    subject.checkRole("user");
    subject.checkPermission("user:select");

}

第二种:

// JdbcRealm 测试 Custom SQL
@Test
public void testAuthenticationCustomSQL() {

    JdbcRealm jdbcRealm = new JdbcRealm();
    jdbcRealm.setDataSource(druidDataSource);
    jdbcRealm.setPermissionsLookupEnabled(true);

    /**
     * @see org.apache.shiro.realm.jdbc.JdbcRealm
     */
    String sql = "select pwd from t_user where user_name = ?";
    jdbcRealm.setAuthenticationQuery(sql);

    DefaultSecurityManager defaultSecurityManager = new DefaultSecurityManager();
    defaultSecurityManager.setRealm(jdbcRealm);

    SecurityUtils.setSecurityManager(defaultSecurityManager);
    Subject subject = SecurityUtils.getSubject();

    UsernamePasswordToken token = new UsernamePasswordToken("test", "123");
    subject.login(token);

    System.out.println("是否认证:" + subject.isAuthenticated());
}

3、自定义Realm

在上面我们已经看过了 JdbcRealm,所以我们也可以依葫芦画瓢自定义Ramlm。

第一步:继承 AuthorizingRealm

第二步:实现认证方法

第三步:实现授权方法

通过AuthorizingRealm,我们完全按照自己的需求实现自己的业务逻辑。

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

/**
 * @author Wenyi Feng
 * @since 2018-10-22
 */
public class CustomRealmTest extends AuthorizingRealm {

    /**
     * Retrieves the AuthorizationInfo for the given principals from the underlying data store.  When returning
     * an instance from this method, you might want to consider using an instance of
     * {@link org.apache.shiro.authz.SimpleAuthorizationInfo SimpleAuthorizationInfo}, as it is suitable in most cases.
     *
     * @param principals the primary identifying principals of the AuthorizationInfo that should be retrieved.
     * @return the AuthorizationInfo associated with this principals.
     * @see org.apache.shiro.authz.SimpleAuthorizationInfo
     */
    // 授权
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        return null;
    }

    /**
     * Returns {@code true} if authentication caching should be utilized based on the specified
     * {@link AuthenticationToken} and/or {@link AuthenticationInfo}, {@code false} otherwise.
     * <p/>
     * The default implementation simply delegates to {@link #isAuthenticationCachingEnabled()}, the general-case
     * authentication caching setting.  Subclasses can override this to turn on or off caching at runtime
     * based on the specific submitted runtime values.
     *
     * @param token the submitted authentication token
     * @param info  the {@code AuthenticationInfo} acquired from data source lookup via
     *              {@link #doGetAuthenticationInfo(org.apache.shiro.authc.AuthenticationToken)}
     * @return {@code true} if authentication caching should be utilized based on the specified
     *         {@link AuthenticationToken} and/or {@link AuthenticationInfo}, {@code false} otherwise.
     * @since 1.2
     */
    // 认证
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token)
            throws AuthenticationException {
        return null;
    }
}

可能Shiro提供的Realm并不能满足我们的实际开发需求,所以真正弄明白自定义Realm还是有很大帮助的,你觉得呢?

4、安全加密

明文密码?

好吧,我们看看Shiro为我们提供的加密方法。

//  Md5Hash md5Hash = new Md5Hash("123456");

Md5Hash md5Hash = new Md5Hash("123456", "admin");
System.out.println(md5Hash.toString());

那我们该怎么使用了?

在Realm认证中设置盐值

// 使用admin对密码进行加密
authenticationInfo.setCredentialsSalt(ByteSource.Util.bytes("admin"));

我们只需要告诉我们的Realm,需要对密码进行加密就可以了。

CustomRealm customRealm = new CustomRealm();
HashedCredentialsMatcher matcher = new HashedCredentialsMatcher();
// 加密类型
matcher.setHashAlgorithmName("md5"); 
// 加密次数
matcher.setHashIterations(1); 
customRealm.setCredentialsMatcher(matcher);

权限

1、Shiro为我们提供的权限

名称 说明
anon 不校验
authc 作校验
roles 需要具有指定角色(一个或多个)才能访问
perms 需要具有指定角色(一个或多个)才能访问

2、配置

<!-- 从上往下开始匹配 -->
/login.html = anon
/subLogin = anon
<!--/testRole = roles["admin"]-->
<!--/testRole1 = roles["admin", "admin1"]-->
<!--/testPerms = perms["user:delete"]-->
<!--/testPerms1 = perms["user:delete", "user:update"]-->

3、自定义权限认证

import org.apache.shiro.web.filter.authz.AuthorizationFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

/**
 * @author Wenyi Feng
 * @since 2018-10-22
 */
public class CustomAuthorizationFilter extends AuthorizationFilter {
    
    protected boolean isAccessAllowed(ServletRequest request, 
                                      ServletResponse response, 
                                      Object mappedValue) throws Exception {
        return false;
    }
}

另外,看一下 Shiro Filter

Shiro Filter

会话管理(Session)

会话管理,就是拿到Session之后,我们怎么处理。什么意思?分布式系统,需要共享Session。

import org.apache.shiro.session.Session;
import org.apache.shiro.session.UnknownSessionException;
import org.apache.shiro.session.mgt.eis.AbstractSessionDAO;

import java.io.Serializable;
import java.util.Collection;

/**
 * 自定义Session操作接口
 * @author Wenyi Feng
 * @since 2018-10-22
 */
public class CustomSessionDAO extends AbstractSessionDAO {
    
    // 创建Session
    protected Serializable doCreate(Session session) {
        return null;
    }

    // 读session
    protected Session doReadSession(Serializable sessionId) {
        return null;
    }

    // 修改session
    public void update(Session session) throws UnknownSessionException {

    }

    // 删除session
    public void delete(Session session) {

    }

    // 获取当前活动的session
    public Collection<Session> getActiveSessions() {
        return null;
    }
}

缓存管理(Cache)

缓存管理同Session管理,可以这样说,session是一套系统的基础,缓存决定系统的优化级别,很重要。

缓存设计

另外,我们看一下,Shiro为我们设计的缓存接口。

package org.apache.shiro.cache;

import java.util.Collection;
import java.util.Set;

public interface Cache<K, V> {
    V get(K var1) throws CacheException;

    V put(K var1, V var2) throws CacheException;

    V remove(K var1) throws CacheException;

    void clear() throws CacheException;

    int size();

    Set<K> keys();

    Collection<V> values();
}

自动登录

我们只需要为token设置RememberMe就可以了。

token.setRememberMe(user.getRememberMe());

链接

[1] Shiro安全框架入门

[2] 本次测试代码:ShiroLearn

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 218,284评论 6 506
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,115评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,614评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,671评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,699评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,562评论 1 305
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,309评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,223评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,668评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,859评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,981评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,705评论 5 347
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,310评论 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,904评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,023评论 1 270
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,146评论 3 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,933评论 2 355

推荐阅读更多精彩内容

  • 说明:本文很多观点和内容来自互联网以及各种资料,如果侵犯了您的权益,请及时联系我,我会删除相关内容。 权限管理 基...
    寇寇寇先森阅读 7,593评论 8 76
  • title: Shiro整合Web项目及整合后的开发tags: shirocategories: shiro 将S...
    codingXiaxw阅读 3,530评论 3 24
  • title: 初识Shirotags: shirocategories: shiro 若图片无法显示,请前往我的博...
    codingXiaxw阅读 575评论 1 0
  • 跳动的头像,停止了跳动。 留下的仅剩最后一点温存。 他,离开的是那样的决绝。 她,撕开的是不可言说的伤口。 都说好...
    玫瑰花的梦阅读 306评论 0 0
  • 这两天下雨,气温低,有点冷,上午出门的时候,一瞬间感觉,飘雪花了?很快想到,不对,是柳絮?可是路两边没有垂柳,全是...
    笑笑8阅读 443评论 0 2