Java 安全框架 - Shiro

简介

Apache Shiro 官网

Apache Shiro是一个强大且易用的Java安全框架,执行身份验证、授权、密码学和会话管理。使用Shiro的易于理解的API,您可以快速、轻松地获得任何应用程序,从最小的移动应用程序到最大的网络和企业应用程序。

  • 主要特性

主要特性

  1. Authentication(验证)
  2. Authorization(授权)
  3. Session Management(会话管理)
  4. Cryptography(加密)

身份认证(验证)

ShiroAuthenticationSequence

从配置文件获取用户密码

  • 依赖
<dependency>
    <groupId>org.apache.shiro</groupId>
    <artifactId>shiro-core</artifactId>
    <version>1.3.2</version>
    <exclusions>
        <exclusion>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
        </exclusion>
    </exclusions>
</dependency>
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-log4j12</artifactId>
    <version>1.7.23</version>
</dependency>
  • 配置文件

shiro.ini

# 此处只是演示,实际项目中用户/密码会在数据库取得
[users]
lee=123456

log4j.properties

#
# 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.
#
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=TRACE

# Disable verbose logging
log4j.logger.org.apache.shiro.util.ThreadContext=WARN
log4j.logger.org.apache.shiro.cache.ehcache.EhCache=WARN
  • HelloShiro.java
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.Factory;

public class HelloShiro {
   
    public static void main(String[] args) {
        // 读取配置文件,初始化 SecurityManager 工厂
        Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
        // 获取 SecurityManager 实例
        SecurityManager securityManager = factory.getInstance();
        // 把 SecurityManager 实例绑定到 SecurityUtils
        SecurityUtils.setSecurityManager(securityManager);
        // 得到当前执行的用户
        Subject currentUser = SecurityUtils.getSubject();

        // 创建 token 令牌,用户名/密码
        UsernamePasswordToken token = new UsernamePasswordToken("lee",
                "123456");

        try {
            // 登录
            currentUser.login(token);
            System.out.println("身份认证成功");
        } catch (AuthenticationException e) {
            e.printStackTrace();
            System.out.println("身份认证失败");
        }
        // 退出
        currentUser.logout();
    }
}
  • 执行成功

成功

  • 执行失败,即用户名或密码错误

失败

以上就是一简单的 Shiro 实例。

从数据库获取用户密码

此过程根据上述代码修改

  • 依赖
<dependency>
    <groupId>com.mchange</groupId>
    <artifactId>c3p0</artifactId>
    <version>0.9.5.2</version>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.39</version>
</dependency>
<!-- org.apache.shiro.util.AbstractFactory.getInstance需要 -->
<dependency>
    <groupId>commons-logging</groupId>
    <artifactId>commons-logging</artifactId>
    <version>1.2</version>
</dependency>
  • 配置文件

jdbcRealm.ini

[main]
# 使用数据库保存的用户密码
jdbcRealm=org.apache.shiro.realm.jdbc.JdbcRealm

# 数据源
dataSource=com.mchange.v2.c3p0.ComboPooledDataSource
dataSource.driverClass=com.mysql.jdbc.Driver
dataSource.jdbcUrl=jdbc:mysql://localhost:3306/java
dataSource.user=root
dataSource.password=root

# 设置 jdbcRealm 数据源
jdbcRealm.dataSource=$dataSource

# 设置 securityManager 的 realm,多个逗号隔开
securityManager.realms=$jdbcRealm
  • SQL 文件

在编写 SQL 时先说明下,Shiro 默认是根据提供的数据库,去寻找users,用户名和密码字段为usernamepassword。格式如下:

jdbcRealm

  • JdbcShiro.java
// 此处只需改变配置文件即可,其它代码与上述 HelloShrio 代码一致
Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:jdbcRealm.ini");

权限认证(授权)

最核心的三个要素:权限,角色和用户。

  • ShiroUtils.java
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.Factory;

public class ShiroUtils {
   

    public static Subject login(String iniResourcePath, String username, String password) {
        // 读取配置文件,初始化 SecurityManager 工厂
        Factory<SecurityManager> factory = new IniSecurityManagerFactory(iniResourcePath);
        // 获取 SecurityManager 实例
        SecurityManager securityManager = factory.getInstance();
        // 把 SecurityManager 实例绑定到 SecurityUtils
        SecurityUtils.setSecurityManager(securityManager);
        // 得到当前执行的用户
        Subject currentUser = SecurityUtils.getSubject();
        // 创建 token 令牌,用户名/密码
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        try {
            // 登录
            currentUser.login(token);
            System.out.println("身份认证成功");
        } catch (AuthenticationException e) {
            e.printStackTrace();
            System.out.println("身份认证失败");
        }
        return currentUser;
    }
}

编程式授权

基于角色的访问控制(RBAC)

  • baseRole.ini
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值