Shiro

简介: WhatApache Shiro旨在成为最全面的,但也是最容易使用的Java安全框架。文档没有比官网更好的了 https://shiro.apache.

What

Apache Shiro旨在成为最全面的,但也是最容易使用的Java安全框架。

文档

没有比官网更好的了 https://shiro.apache.org/get-started.html

简要分析

img_338f9c94867cef82b7a76edb54e46d06.png

四大基石: 认证,授权,会话管理,加密

了解术语

Authentication:认证
Authorization:授权(访问控制)
其他:https://shiro.apache.org/terminology.html

架构

Shiro的架构有三个主要概念:Subject,SecurityManager和Realms


img_6279365a119c5eaf1ebbffff38986a35.png

其他:https://shiro.apache.org/architecture.html

快速启动

获取当前用户(这里叫主题subject,代之用户,程序,上下文等,不叫user主要是防止shiro不跟其他框架重名)

Subject currentUser = SecurityUtils.getSubject();

获得会话session

Session session = currentUser.getSession();
session.setAttribute( "someKey", "aValue" );

登陆认证

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("lonestarr", "vespa");
    //this is all you have to do to support 'remember me' (no config - built in!):
    token.setRememberMe(true);
    currentUser.login(token);
}
//或者捕获异常
try {
    currentUser.login( token );
    //if no exception, that's it, we're done!
} catch ( UnknownAccountException uae ) {
    //username wasn't in the system, show them an error message?
} catch ( IncorrectCredentialsException ice ) {
    //password didn't match, try again?
} catch ( LockedAccountException lae ) {
    //account for that username is locked - can't login.  Show them a message?
}
    ... more types exceptions to check if you want ...
} catch ( AuthenticationException ae ) {
    //unexpected condition - error?
}

获得当前用户主体
currentUser.getPrincipal()

//是否有权限
if ( currentUser.hasRole( "schwartz" ) ) {
    log.info("May the Schwartz be with you!" );
} else {
    log.info( "Hello, mere mortal." );
}

//是否有权限
if ( currentUser.isPermitted( "lightsaber:weild" ) ) {
    log.info("You may use a lightsaber ring.  Use it wisely.");
} else {
    log.info("Sorry, lightsaber rings are for schwartz masters only.");
}

// 登出

currentUser.logout(); //removes all identifying information and invalidates their session too.


相关文章
|
存储 JSON 前端开发
Shiro实现记住我(十)
Shiro实现记住我(十)
375 0
Shiro实现记住我(十)
|
9月前
|
安全 测试技术 API
Shiro详解
Shiro详解
|
9月前
|
安全 Java 容器
深入理解Shiro(下)
深入理解Shiro(下)
48 0
|
9月前
|
安全 Java 测试技术
深入理解Shiro(上)
深入理解Shiro(上)
44 0
|
9月前
|
安全 Java 数据库连接
Shiro 中的 Realm
Shiro 中的 Realm
67 0
|
12月前
|
存储 缓存 安全
|
消息中间件 JavaScript 小程序
再见了 shiro
再见了 shiro
|
消息中间件 安全 JavaScript
再见了 shiro !
再见了 shiro !
|
缓存 安全 前端开发
|
Java 数据安全/隐私保护
shiro(二)shiro详解(1)
shiro(二)shiro详解
190 0
shiro(二)shiro详解(1)