Shiro官方QuickStart.java文档注释版
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.ini.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.lang.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 {
/*通过LoggerFactory 工厂类,创建log4j对象,
加上transient就不会被序列化,不会被持久化生命周期仅为内存中
*/
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):
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.
SecurityUtils.setSecurityManager(securityManager);
// Now that a simple Shiro environment is set up, let's see what you can do:
// get the currently executing user:
//1 获取当前执行的用户 (也不能叫用户,就是个Subject,类似于用户)
//2 会自动获取与当前线程所匹配的相关基于用户的数据参数
// -----获取原因详解-----
/*
*通过SebjectUtils类调用getSubject()方法
*
* 通过ThreadContext直接获取到当前的Subject 有三种情况
* 1 如果能获取,则return Subject对象
* 2 如果没能获取到,调用buildSubject 创建Subject
* 再进行尝试绑定,如果subject仍未空,则清空
* 3 如果操作失败则抛出UnavaiLableSecurityManagerException异常
* 这时候就需要检查配置或者Realm里出问题了
*/
Subject currentUser = SecurityUtils.getSubject();
// Do some stuff with a Session (no need for a web or EJB container!!!)
//3 可以在其中插入获取session的事务,获取当前的会话
// 此session是Shiro的特有的,提供了常规HttpSession的大部分功能
Session session = currentUser.getSession();
session.setAttribute("someKey", "aValue");
//4 获取<K,V>的Value值,通过session.getAttribute,这就是角色 我们的用户(Subject)
String value = (String) session.getAttribute("someKey");
if (value.equals("aValue")) {
log.info("Retrieved the correct value! [" + value + "]");
}
//5 OK.现在获取成功了,我们有一个角色了
// let's login the current user so we can check against roles and permissions:
/*6 接下来,就可以添加用Subject Session 做角色和权限检查之类的功能
但是,现在只能对Shiro已知用户进行操作,虽然Subject是我们当前的用户,
但是,一个很严重的问题,这个用户对于我们来说是一个匿名用户
什么是匿名用户,我们知道有这么一个角色,但是我们不知道他是谁,他有什么权限
直到他至少登录一次进行操作,我们才能得到用户具体对象权限
isAuthenticated 收集Subject和凭证/令牌 并进行一个认证机制
这里只是进行判断是否为第一次登陆或者没有设置RememberMe=true,即RememberMe=false
如果为true则跳过login ,这里isAuthenticated原值为false
在处理的时候会由login进行角色验证,并赋予authenticated true值*/
if (!currentUser.isAuthenticated()) {
/*实际上就是一个普通的字符串没有特殊意义,只是为了将令牌变成char[]数组来存储
以及其他信息也赋予进去变成一个token*/
UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa");
/*设置,RememberMe缓存,后面直接可以通过subject.getPrincipal来获取用户信息,
但是,仅仅针对于非匿名用户且非敏感网页(如会员管理,后台和个人信息等),由我们来设置*/
token.setRememberMe(true);
//7 第一个分叉,尝试去登录
try {
currentUser.login(token);
//会发生多种异常,从小往大排序,这期间,我们可以在login里加一些其他信息
//为Subject异常,不对应等问题
} catch (UnknownAccountException uae) {
log.info("There is no user with username of " + token.getPrincipal());
//令牌不对应等问题
} catch (IncorrectCredentialsException ice) {
log.info("Password for account " + token.getPrincipal() + " was incorrect!");
//账号被锁定问题,登陆次数过多等
} catch (LockedAccountException lae) {
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) {
//unexpected condition? error?
}
}//输出Subject信息
//say who they are:
//print their identifying principal (in this case, a username):
log.info("User [" + currentUser.getPrincipal() + "] logged in successfully.");
//如果角色拥有权限,则输出权限信息
//test a role:
if (currentUser.hasRole("schwartz")) {
log.info("May the Schwartz be with you!");
//很有意思的翻译:愿施瓦茨和你在一起
} else {
log.info("Hello, mere mortal.");
//很有意思的翻译:你好,凡人(意思,你是个凡人,普通人)
}
/*isPermitted查看是否有权限,是否有其他特定的相关权限
即判断已登陆用户是否具有某权限
查看普通实例用户,这里不查看强大的用户(功能强大的实例级权限管理)
翻译: 权限名:光剑使用权
*/
//test a typed permission (not instance-level)
if (currentUser.isPermitted("lightsaber:wield")) {
log.info("You may use a lightsaber ring. Use it wisely.");
//很有意思的翻译:你可以使用光剑。明智地使用它
} else {
log.info("Sorry, lightsaber rings are for schwartz masters only.");
//很有意思的翻译:抱歉,光剑只供施瓦兹大师使用
}
//权限再判断,判断是否有更细粒度的权限
//a (very powerful) Instance Level permission:
if (currentUser.isPermitted("winnebago:drive:eagle5")) {
log.info("You are permitted to 'drive' the winnebago with license plate (id) 'eagle5'. " +
"Here are the keys - have fun!");
} else {
log.info("Sorry, you aren't allowed to drive the 'eagle5' winnebago!");
}
//all done - log out!
/*获取currentUser.login(),登出
//查看源码分析,
// 登出的底层实际上是清除session
//最后再将
this.session = null;
this.principals = null;
//将authenticated初始化即赋值false
this.authenticated = false*/
currentUser.logout();
System.exit(0);
}
}