package com.aaa.lee.shiro;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.Factory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; /**
* Simple Quickstart application showing how to use Shiro's API.
*
* @since 0.9 RC2
*/
public class Quickstart { private static final transient Logger log = LoggerFactory.getLogger(Quickstart.class); public static void main(String[] args) { // The easiest way to create a Shiro SecurityManager with configured
// realms, users, roles and permissions is to use the simple INI config.
// We'll do that by using a factory that can ingest a .ini file and
// return a SecurityManager instance: // Use the shiro.ini file at the root of the classpath
// (file: and url: prefixes load from files and urls respectively):
/**
* 1.使用最简单的方式创建Shiro安全框架,需要通过配置INI配置文件进行配置realm,users,roles,permissions
* 使用Factory<SecurityManager>工厂类加载根目录下的shiro.ini文件来构建SecurityManager对象
* SecurityManager:认证,授权,加密,session管理
* 以下的所有操作都必须使用SecurityManager对象进行完整,也就是说都需要使用SecurityManager对象爱获取
*
*/
Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
SecurityManager securityManager = factory.getInstance(); // for this simple example quickstart, make the SecurityManager
// accessible as a JVM singleton. Most applications wouldn't do this
// and instead rely on their container configuration or web.xml for
// webapps. That is outside the scope of this simple quickstart, so
// we'll just do the bare minimum so you can continue to get a feel
// for things.
/**
*
* 2.已经把SecurityManager对象创建出来,这个对象在JVM中是一个单例
* 如果在真实的web环境中,需要在容器中配置web.xml/application.xml
*
*
*/
SecurityUtils.setSecurityManager(securityManager); /**
* shiro所需要的环境已经搭建完毕
*/
// Now that a simple Shiro environment is set up, let's see what you can do: /**
*
* 3.通过securityManager获取到Subject对象
* Subject中封装了表单所提交的属性(User信息:按照官方要求不能存入密码)
*
*
*/
// get the currently executing user:
Subject currentUser = SecurityUtils.getSubject(); /**
*
* 4.测试session
* 通过Subject对象获取session对象然后进行测试
*
*/
// Do some stuff with a Session (no need for a web or EJB container!!!)
Session session = currentUser.getSession();
session.setAttribute("someKey", "aValue");
String value = (String) session.getAttribute("someKey");
if (value.equals("aValue")) {
log.info("Retrieved the correct value! [" + value + "]");
} // let's login the current user so we can check against roles and permissions:
/**
*
* 5.认证阶段
* currentUser.isAuthenticated():返回true/false 查看当前对象是否已经处于认证创建
* 如果是返回true,否则返回false
*
*
*/
System.out.println("认证前-------->"+currentUser.isAuthenticated());
if (!currentUser.isAuthenticated()) {
/**
* 用户未处于登录状态
* 6.创建出UsernamePasswordToken对象,该对象拥有两个参数username,password
*/
UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa");
// token.setRememberMe(true);
try {
/**
* 7.真正的认证方法
* 调用了login方法
*/
currentUser.login(token);
} catch (UnknownAccountException uae) {
System.out.println("UnknownAccountException---->表示用户不存在");
log.info("There is no user with username of " + token.getPrincipal());
return;
} catch (IncorrectCredentialsException ice) {
System.out.println("IncorrectCredentialsException------>表示密码错误");
log.info("Password for account " + token.getPrincipal() + " was incorrect!");
return;
} catch (LockedAccountException lae) {
System.out.println("LockedAccountException------>表示所登录的账号被锁定");
log.info("The account for username " + token.getPrincipal() + " is locked. " +
"Please contact your administrator to unlock it.");
}
// ... catch more exceptions here (maybe custom ones specific to your application?
catch (AuthenticationException ae) {
/**
* AuthenticationException是以上三个异常父类
*/
//unexpected condition? error?
}
} //say who they are:
//print their identifying principal (in this case, a username):
System.out.println("用户登录成功");
System.out.println("认证成功-------->"+currentUser.isAuthenticated());
/**
* currentUser.getPrincipal():获取的是用户名
*/
log.info("User [" + currentUser.getPrincipal() + "] logged in successfully."); //test a role:
/**
* 8.测试角色
* currentUser.hasRole("schwartz"):返回值为true/false
* 如果当前登录用户拥有该角色则返回true,否则返回false
*/
if (currentUser.hasRole("book_manager")) {
System.out.println("拥有schwartz角色");
log.info("May the Schwartz be with you!");
//return;
} else {
System.out.println("没有schwartz角色");
log.info("Hello, mere mortal.");
} /**
* 9.测试权限
* currentUser.isPermitted("lightsaber:wield"):返回true/false
* 如果拥有权限返回true,否则返回false
*/
//test a typed permission (not instance-level)
if (currentUser.isPermitted("book:delete")) {
System.out.println("可以对图书进行删除操作");
log.info("You may use a lightsaber ring. Use it wisely.");
//return;
} else {
System.out.println("没有对图书操作权限");
log.info("Sorry, lightsaber rings are for schwartz masters only.");
} //a (very powerful) Instance Level permission:
if (currentUser.isPermitted("bookUser:query:book")) {
System.out.println("拥有操作!!!!");
log.info("You are permitted to 'drive' the winnebago with license plate (id) 'eagle5'. " +
"Here are the keys - have fun!");
// return;
} else {
log.info("Sorry, you aren't allowed to drive the 'eagle5' winnebago!");
} /**
* 10.Subjct主体对象调用logout()方法执行退出操作
*/
//all done - log out!
currentUser.logout();
System.out.println("退出后-------->"+currentUser.isAuthenticated()); System.exit(0);
}
}

shiro 快速入门详解。的更多相关文章

  1. Redis快速入门详解

    Redis入门详解 Redis简介 Redis安装 Redis配置 Redis数据类型 Redis功能 持久化 主从复制 事务支持 发布订阅 管道 虚拟内存 Redis性能 Redis部署 Redis ...

  2. 跨浏览器复制神器 ZeroClipboard 2.x快速入门详解

    有些时候,我们希望让用户在网页上完成某个操作就能自动将指定的内容复制到用户计算机的剪贴板中.但是出于安全原因,大多数现代浏览器都未提供通用的剪贴板复制接口(或即便有,也默认被禁用).只有IE浏览器可以 ...

  3. 转:JAVAWEB开发之权限管理(二)——shiro入门详解以及使用方法、shiro认证与shiro授权

    原文地址:JAVAWEB开发之权限管理(二)——shiro入门详解以及使用方法.shiro认证与shiro授权 以下是部分内容,具体见原文. shiro介绍 什么是shiro shiro是Apache ...

  4. Shiro 安全框架详解一(概念+登录案例实现)

    shiro 安全框架详细教程 总结内容 一.RBAC 的概念 二.两种常用的权限管理框架 1. Apache Shiro 2. Spring Security 3. Shiro 和 Spring Se ...

  5. Cisco思科模拟器 交换机IP地址的配置 入门详解 - 精简归纳

    Cisco思科模拟器 交换机IP地址的配置 入门详解 - 精简归纳 JERRY_Z. ~ 2020 / 10 / 10 转载请注明出处!️ 目录 Cisco思科模拟器 交换机IP地址的配置 入门详解 ...

  6. 学会Git玩转GitHub(第二篇) 入门详解 - 精简归纳

    学会Git玩转GitHub(第二篇) 入门详解 - 精简归纳 JERRY_Z. ~ 2020 / 10 / 25 转载请注明出处!️ 目录 学会Git玩转GitHub(第二篇) 入门详解 - 精简归纳 ...

  7. Shiro 安全框架详解二(概念+权限案例实现)

    Shiro 安全框架详解二 总结内容 一.登录认证 二.Shiro 授权 1. 概念 2. 授权流程图 三.基于 ini 的授权认证案例实现 1. 实现原理图 2. 实现代码 2.1 添加 maven ...

  8. Linq之旅:Linq入门详解(Linq to Objects)

    示例代码下载:Linq之旅:Linq入门详解(Linq to Objects) 本博文详细介绍 .NET 3.5 中引入的重要功能:Language Integrated Query(LINQ,语言集 ...

  9. SQL注入攻防入门详解

    =============安全性篇目录============== 本文转载 毕业开始从事winfrm到今年转到 web ,在码农届已经足足混了快接近3年了,但是对安全方面的知识依旧薄弱,事实上是没机 ...

随机推荐

  1. 第九届河南理工大学算法程序设计大赛 正式赛L:最优规划(最小生成树)

    单测试点时限: 1.0 秒 内存限制: 512 MB 有很多城市之间已经建立了路径,但是有些城市之间没有路径联通.为了联通所有的城市,现在需要添加一些路径,为了节约,需要满足添加总路径是最短的. 输入 ...

  2. Defending Adversarial Attacks by Correcting logits

    目录 概 主要内容 实验 Li Y., Xie L., Zhang Y., Zhang R., Wang Y., Tian Q., Defending Adversarial Attacks by C ...

  3. [C/C++]linux下c-c++语法知识点归纳和总结

    1.c/c++申请动态内存 在c++中,申请动态内存是使用new和delete,这两个关键字实际上是运算符,并不是函数. 而在c中,申请动态内存则是使用malloc和free,这两个函数是c的标准库函 ...

  4. Canvas原生API(纯CPU)计算并渲染三维图

    Canvas原生API(纯CPU)计算并渲染三维图 前端工程师学图形学:Games101 第三次作业 利用Canvas画三维中的三角形并使用超采样实现抗锯齿 最终完成功能 Canvas 原生API实现 ...

  5. 初识python 之 爬虫:BeautifulSoup 的 find、find_all、select 方法

    from bs4 import BeautifulSoup lxml 以lxml形式解析html,例:BeautifulSoup(html,'lxml') #  注:html5lib 容错率最高fin ...

  6. 责任链模式(python)

    rom abc import ABCMeta, abstractmethod class Handler(metaclass=ABCMeta): @abstractmethod def handle_ ...

  7. Bash 取字符串的最后 N 个字符 - ${str:0-N:LENGTH}

    Bash 取字符串的最后 N 个字符: ${str:0-N:LENGTH} or ${str:0-N} https://tldp.org/LDP/abs/html/string-manipulatio ...

  8. 怎样在 CentOS/RHEL 7/6 上安装和配置 Sendmail 服务器

    在 CentOS 上,可以通过 mailx 命令 或 sendmail 命令来给因特网发送电子邮件. 关于前者的文章比较多,关于后者的文章比较少. 这里记录了我在 CentOS 7 上安装和配置 se ...

  9. [vscode] os.getcwd(),调试和命令行运行的结果不一致

    问题描述: 调试和命令行运行的时候工作目录不一致 这会导致一个问题,我想从上级目录导入模块的话,F5调试就会找不到模块,而命令行则没问题 那么我该如何调试呢? 目录结构: top  └ folder_ ...

  10. vue组件中的.sync修饰符使用

    在vue的组件通信props中,一般情况下,数据都是单向的,子组件不会更改父组件的值,那么vue提供.sync作为双向传递的关键字,实现了父组件的变动会传递给子组件,而子组件的carts改变时,通过事 ...