Shiro之入门(一)

基本知识

Apache Shiro是Java的一个安全(权限)框架,不仅支持JavaEE 而且支持Java SE
在这里插入图片描述

Application Core----->Subject-------->SecurityManager
在这里插入图片描述

HelloWorld

1、新建一个Java项目(Shiro)

2、新建一个普通文件夹lib,导入jar包,add to build path

log4j-1.2.15.jar
shiro-core-1.2.1.jar
shiro-ehcache-1.2.1.jar
shiro-spring-1.2.1.jar
shiro-web-1.2.1.jar
slf4j-api-1.7.2.jar
slf4j-log4j12-1.7.2.jar

3、新建一个源码文件夹(config),导入配置文件shiro.ini

#
# 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.
#
# =============================================================================
# Quickstart INI Realm configuration
#
# For those that might not understand the references in this file, the
# definitions are all based on the classic Mel Brooks' film "Spaceballs". ;)
# =============================================================================

# -----------------------------------------------------------------------------
# Users and their assigned roles
#
# Each line conforms to the format defined in the
# org.apache.shiro.realm.text.TextConfigurationRealm#setUserDefinitions JavaDoc
# -----------------------------------------------------------------------------
[users]
# user 'root' with password 'secret' and the 'admin' role
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 with assigned permissions
# 
# Each line conforms to the format defined in the
# org.apache.shiro.realm.text.TextConfigurationRealm#setRoleDefinitions JavaDoc
# -----------------------------------------------------------------------------
[roles]
# 'admin' role has all permissions, indicated by the wildcard '*'
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

4、新建一个包,放入一个Java文件

package com.example;
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;

public class Quickstart {
    
    

    private static final transient Logger log = LoggerFactory.getLogger(Quickstart.class);


    public static void main(String[] args) {
    
    

    	//获取配置文件
        Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
        SecurityManager securityManager = factory.getInstance();

       
        //获取当前的subject
        SecurityUtils.setSecurityManager(securityManager);
       
        Subject currentUser = SecurityUtils.getSubject();

        //测试使用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 + "]");
        }

        // 测试当前的用户是否登录,也就是是否被认证
        if (!currentUser.isAuthenticated()) {
    
    
        	//把用户名和密码封装为UsernamePasswordToken对象
            UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa");
            //RememberMe
            token.setRememberMe(true);
            try {
    
    
            	//执行登录
                currentUser.login(token);
            } 
            //若没有指定的用户,shiro抛出UnknownAccountException异常
            catch (UnknownAccountException uae) {
    
    
                log.info("There is no user with username of " + token.getPrincipal());
            } 
            //若用户存在密码不匹配,shiro抛出IncorrectCredentialsException
            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 (AuthenticationException ae) {
    
    
            }
        }

        //若登录成功
        log.info("User [" + currentUser.getPrincipal() + "] logged in successfully.");

        //是否有一个角色,利用hasRole方法
        if (currentUser.hasRole("schwartz")) {
    
    
            log.info("May the Schwartz be with you!");
        } else {
    
    
            log.info("Hello, mere mortal.");
        }

        //测试用户是否具备某一个行为,isPermitted方法
        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.");
        }

        //测试用户是否具备某一个行为,isPermitted方法
        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!");
        }
        //执行登出
        currentUser.logout();

        System.exit(0);
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_42272869/article/details/113136016
今日推荐