Shiro 基础入门(二)

使用maven来搭建工程 New|Other|Maven|Maven Project


在pom.xml中引入相关的包


去官网下载源文件: http://shiro.apache.org/download.html#latestSource


解压之后在samples|quickstart|src|main下拷贝相应的文件到shiro-1工程中哦!


       

说明: Quickstart是类文件; log4j.properties是日志配置文件; shiro.ini存放的账户和角色.

shiro.ini

[users]
# user 'root' with password 'secret' and the 'admin' role
# root=secret 分别表示账号和密码,admin表示逗号前边的账号拥有 admin 这个角色。
root = secret, admin
# user 'guest' with the password 'guest' and the 'guest' role
guest = guest, guest
# user 'presidentskroob' with password '12345' ("That's the same combination on
# my luggage!!!" ;)), and role 'president'
presidentskroob = 12345, president
# user 'darkhelmet' with password 'ludicrousspeed' and roles 'darklord' and 'schwartz'
darkhelmet = ludicrousspeed, darklord, schwartz
# user 'lonestarr' with password 'vespa' and roles 'goodguy' and 'schwartz'
lonestarr = vespa, goodguy, schwartz

[roles]
# 'admin' role has all permissions, indicated by the wildcard '*'
# admin 表示角色名称,* 表示这个角色拥有所有权限
admin = *
# The 'schwartz' role can do anything (*) with any lightsaber:
schwartz = lightsaber:*
# The 'goodguy' role is allowed to 'drive' (action) the winnebago (type) with
# license plate 'eagle5' (instance specific id)
goodguy = winnebago:drive:eagle5

Quickstart类

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>获得工厂对象
        Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
		//2>通过工程对象获得securityManager对象
        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.
		//3>SecurityUtils设置securityManager对象
        SecurityUtils.setSecurityManager(securityManager);

        // Now that a simple Shiro environment is set up, let's see what you can do:

        // get the currently executing user:
		//4>获得当前执行的用户
        Subject currentUser = SecurityUtils.getSubject();

        // Do some stuff with a Session (no need for a web or EJB container!!!)
		//测试使用session
        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>测试当前用户是否被认证,是否登录了!
        if (!currentUser.isAuthenticated()) {
			//把用户名和密码封装在令牌中UsernamePasswordToken
            UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa");
//			UsernamePasswordToken token = new UsernamePasswordToken("lonestarr22", "vespa");
             //记住我
			token.setRememberMe(true);
            try {
				//执行登录
                currentUser.login(token);
            } 
			 //如果没有指定的用户,则shiro抛出UnknownAccountException异常
			catch (UnknownAccountException uae) {
                log.info("==>There is no user with username of " + token.getPrincipal());
				return;
            } 
			//如果用户存在,密码不匹配,则shiro抛出IncorrectCredentialsException异常
			catch (IncorrectCredentialsException ice) {  
                log.info("==>Password for account " + token.getPrincipal() + " was incorrect!");
				return;
            }
			//用户被锁定异常LockedAccountException
			catch (LockedAccountException lae) {
                log.info("The account for username " + token.getPrincipal() + " is locked.  " +
                        "Please contact your administrator to unlock it.");
				return;
            }
            // ... catch more exceptions here (maybe custom ones specific to your application?
			//所有异常认证的父类
            catch (AuthenticationException ae) {
                //unexpected condition?  error?
            }
        }

        //say who they are:
        //print their identifying principal (in this case, a username):
		//输出登录成功!
        log.info("User [" + currentUser.getPrincipal() + "] logged in successfully.");

        //test a role:
		//测试是否有某一个角色,调用subject的 hasRole方法
        if (currentUser.hasRole("schwartz")) {
            log.info("May the Schwartz be with you!");
        } else {
            log.info("===>Hello, mere mortal.");
			return;
        }

        //test a typed permission (not instance-level)
		//测试用户具备某一个行为,调用subject的isPermitted方法
        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.");
        }

        //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!");
        }

		System.out.println("认证前====>"+currentUser.isAuthenticated());
        //all done - log out!
		//用户退出
        currentUser.logout();

		System.out.println("认证退出后====>"+currentUser.isAuthenticated());
        System.exit(0);
    }
}

运行效果如下:

(1)账号和密码正确登录





(2)账号不正确!




(2)账号存在,密码不正确!




(4)退出登录




 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值