shiro安全框架整理

一:简单介绍

Apache 的安全框架

Apache Shiro是一个Java的安全管理框架,可以用在JavaEE环境下,也可以用在JavaSE环境下。

此前我们学习了很多有关阿帕奇的东西:maven,tomcat,等等

他能做什么?

shiro架构

官方号称十分钟就可以入门:Apache Shiro | Simple. Java. Security.

gti地址:GitHub - apache/shiro: Apache Shiro

二:快速开始(传送门中内容)

1,引入依赖

    <!--核心包,没有这个包就是扯淡-->
    <dependency>
        <groupId>org.apache.shiro</groupId>
        <artifactId>shiro-core</artifactId>
        <version>1.6.0</version>
    </dependency>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>jcl-over-slf4j</artifactId>
        <version>1.7.21</version>
    </dependency>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-log4j12</artifactId>
        <version>1.7.21</version>
    </dependency>
    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.17</version>
    </dependency>
    <!--thymeleaf和shiro的整合包   类似于security和thymeleaf的整合包   有了整合包在页面中就可以
        使用一些特有的标签例如shiro:hasPermission    还有sec:authorize   这些个标签,取值都是整合包里面的-->
    <dependency>
        <groupId>com.github.theborakompanioni</groupId>
        <artifactId>thymeleaf-extras-shiro</artifactId>
        <version>2.0.0</version>
    </dependency>

2,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.config.IniSecurityManagerFactory;
//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.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
 */

/**
 * shiro 快速入门  1,导入pom依赖  ,2编写shiro.ini文件  3,编写类运行
 */
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();//三大核心对象之二
        SecurityUtils.setSecurityManager(securityManager);
        
        // get the currently executing user:
        //获取当前的用户对象  三大核心对象之一
        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 + "]");
        }

        // 判断当前用户是否被认证
        if (!currentUser.isAuthenticated()) {
            //UsernamePasswordToken令牌 通过当前用户的账号密码生成的令牌
            UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa");
            token.setRememberMe(true);//设置记住我
            try {
                currentUser.login(token);//执行登录操作
            } 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?
            }
        }

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

        //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.logout();

        System.exit(0);
    }
}

shiro.ini

[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

shiro的配置文件

log4j.rootLogger=INFO, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m %n
# General Apache libraries
log4j.logger.org.apache=WARN
# Spring
log4j.logger.org.springframework=WARN
# Default Shiro logging
log4j.logger.org.apache.shiro=INFO
# Disable verbose logging
log4j.logger.org.apache.shiro.util.ThreadContext=WARN
log4j.logger.org.apache.shiro.cache.ehcache.EhCache=WARN

三:简单demo

1,ShiroConfig

package com.kuang.config;

import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.LinkedHashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {
    /**
     *             Shiro核心三大对象
     *             1,Subject   用户
     *             2,SecurityManage  管理所有用户
     *             3,Realm  连接数据
     */
    //ShiroFilterFactoryBean  第三步
    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("defaultWebSecurityManage")DefaultWebSecurityManager defaultWebSecurityManager ){
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        //添加shiro的内置过滤器
        /**
         * anon  无需认证即可访问
         * authc  必须认证才能访问
         * user   必须拥有记住我的功能才能访问
         * perms  必须拥有某个资源的权限,才能访问该资源
         * role  必须拥有某个角色权限才能访问
         */
        //登录拦截
        Map<String, String> filterChainDefinitionMap = new LinkedHashMap<>();
        filterChainDefinitionMap.put("/user/add","authc");
        filterChainDefinitionMap.put("/user/edit","authc");//给这两个页面添加了认证,不认证就看不见
        filterChainDefinitionMap.put("/user/del","anon");//没有认证,也能看见

        filterChainDefinitionMap.put("/user/add","perms[user:add]");//add请求,登录人必须有user:add权限才能访问,没有授权会跳转到未授权页面
        filterChainDefinitionMap.put("/user/edit","perms[user:update]");//edit,登录人必须有user:update权限才能访问
        filterChainDefinitionMap.put("/user/del","perms[user:add,user:update]");//del  登录人必须有user:add,user:update权限才能访问
        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);

        //设置登录的请求
        shiroFilterFactoryBean.setLoginUrl("/toLogin");
        //访问未授权的请求,就会自动跳转到这个请求/noAuthorization,给他展示未授权页面
        shiroFilterFactoryBean.setUnauthorizedUrl("/noAuthorization");
        //设置安全管理器
        shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager);
        return shiroFilterFactoryBean;
    }

    //DefaultWebSecurityManager   第二步                         userRealm已经被spring管理了,所以可以作为参数传进方法中
    @Bean(name = "defaultWebSecurityManage")
    public DefaultWebSecurityManager getDefaultWebSecurityManage(@Qualifier("userRealm") UserRealm userRealm){
        DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();

        //关联userRealm
        defaultWebSecurityManager.setRealm(userRealm);

        return defaultWebSecurityManager;


    }

    //创建realm  需要自定义类  第一步
    @Bean(name = "userRealm")
    public UserRealm userRealm(){
        return new UserRealm();
    }

    //前端用的
    //整和shiroDialect  用来整和shiro thymeleaf   包括前面的springsecurity thymeleaf   这可以理解为是thymeleaf的不通方言
    @Bean
    public ShiroDialect getShiroDialect(){
        return new ShiroDialect();
    }

}

2,RealmUser

package com.kuang.config;


import com.kuang.pojo.User;
import com.kuang.service.UserService;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * 自定义的realm  用来学习测试
 */
public class UserRealm extends AuthorizingRealm {

    @Autowired
    UserService userService;

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行了授权author");

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //info.addStringPermission("user:add");//给登录的用户进行了user:add授权,这样的话,就给了所有登录用户都授权,没有达到权限过滤,代码不够灵活,写死了
        
        //为了避免给所有人都进行权限分配,所以需要改变设计思路将,权限存在数据库中,来查询
        //获取权限,此刻又出现了新问题,用户信息都是在认证中,我现在是在授权中,该怎么获取这个用户呢?,通过Subject
        
        //拿到当前登录的subject对象
        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipal();//认证的时候塞进来的
        String perms = user.getPerms();
        //多个权限
        String[] split = perms.split(",");
        for (String s : split) {
            info.addStringPermission(s);
        }
        return info;
    }


    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("执行了认证authentic");
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        //连接数据库   手动验证用户名
        User user = userService.queryByName(token.getUsername());
        if(user == null){
            return null;
        }

        //shiro可以加密  MD5加密  MD5盐值加密
        //密码认证shiro会帮我们做~,不用编码来判断
//        return new SimpleAuthenticationInfo("",user.getPwd(),"");
        return new SimpleAuthenticationInfo(user,user.getPwd(),"");//第一个参数是为了将user存放在principal中,这样在授权中就可以取出来
    }
}

//添加shiro的内置过滤器
/**
* anon 无需认证即可查看
* authc 必须认证才能查看
* user 必须拥有记住我的功能才能访问
* perms 必须拥有某个资源的权限,才能访问该资源
* role 必须拥有某个角色权限才能访问
*/

a,认证查看,首页有些功能,需要登录认证了才会展示出来 anon/authc

b,登录人员认证,用户登录时账号密码验证

subject.login(token);//执行了登录方法,验证了账号密码,封装起来的,走了很多层

c,登录人员进行授权,UserRealm中进行的授权 perms

3,后端的代码省略,无非是处理前段的请求,进行页面跳转,查询数据库验证数据。

4,前端权限控制的核心部分

<div shiro:hasPermission="user:add">
    <a th:href="@{/user/add}">添加</a>
</div>

<div shiro:hasPermission="user:update">
    <a th:href="@{/user/edit}">修改</a>
</div>

<!--无需权限就可以查看-->
<div >
    <a th:href="@{/user/del}">删除</a>
</div>

<hr>

<div shiro:notAuthenticated>
<a th:href="@{/toLogin}">登录</a>
</div>

<a th:href="@{/logout}">注销</a>

shiro:hasPermission=“user:add” 有user:add才能看见

shiro:notAuthenticated 未登录才能看见

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值