首页 > Web开发 > 详细

Apache Shiro

时间:2019-08-09 09:16:32      阅读:87      评论:0      收藏:0      [点我收藏+]

10 Minute Tutorial on Apache Shiro:http://shiro.apache.org/10-minute-tutorial.html

1、What is Apache Shiro?

  Apache Shiro is a powerful and easy to use Java security framework that offers developers an intuitive yet comprehensive solution to authentication, authorization, cryptography, and session management.

  Shiro:java安全框架,提供认证、授权、加密和回话管理。

  获取当前用户:

Subject currentUser = SecurityUtils.getSubject();

  获取用户session:

Session session = currentUser.getSession();
session.setAttribute( "someKey", "aValue" );

  用户认证:

if ( !currentUser.isAuthenticated() ) {
    //collect user principals and credentials in a gui specific manner
    //such as username/password html form, X509 certificate, OpenID, etc.
    //We‘ll use the username/password example here since it is the most common.
    UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa");
    //this is all you have to do to support ‘remember me‘ (no config - built in!):
    token.setRememberMe(true);
    currentUser.login(token);
}

  登陆失败的处理:

try {
    currentUser.login( token );
    //if no exception, that‘s it, we‘re done!
} catch ( UnknownAccountException uae ) {
    //username wasn‘t in the system, show them an error message?
} catch ( IncorrectCredentialsException ice ) {
    //password didn‘t match, try again?
} catch ( LockedAccountException lae ) {
    //account for that username is locked - can‘t login.  Show them a message?
}
    ... more types exceptions to check if you want ...
} catch ( AuthenticationException ae ) {
    //unexpected condition - error?
}

  获取登陆用户的信息,比如用户名:

currentUser.getPrincipal()

  判断登陆用户是否有指定角色或权限:

if ( currentUser.hasRole( "schwartz" ) ) {
    log.info("May the Schwartz be with you!" );
} else {
    log.info( "Hello, mere mortal." );
}

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

  用户退出:

currentUser.logout();

 

2、shiro demo: 身份认证使用textRealm

  依赖:

<dependency>
    <groupId>org.apache.shiro</groupId>
    <artifactId>shiro-core</artifactId>
    <version>1.2.4</version>
</dependency>

<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-log4j12</artifactId>
    <version>1.7.12</version>
</dependency>

  

  在classpath新建配置文件shiro.ini

[users]
java=123456

 

  测试类

package com.oy;

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 HelleWorld {

    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("java", "123456");
        try{
            // 身份认证
            currentUser.login(token);    
            System.out.println("身份认证成功!");
        }catch(AuthenticationException e){
            e.printStackTrace();
            System.out.println("身份认证失败!");
        }
        // 退出
        currentUser.logout();
    }
}

 

3、身份认证使用jdbcRealm

  依赖:

<dependency>
    <groupId>org.apache.shiro</groupId>
    <artifactId>shiro-core</artifactId>
    <version>1.2.4</version>
</dependency>

<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-log4j12</artifactId>
    <version>1.7.12</version>
</dependency>

<dependency>
    <groupId>c3p0</groupId>
    <artifactId>c3p0</artifactId>
    <version>0.9.1.2</version>
</dependency>

<dependency>
    <groupId>commons-logging</groupId>
    <artifactId>commons-logging</artifactId>
    <version>1.2</version>
</dependency>

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.37</version>
</dependency>

 

  数据库:

CREATE DATABASE IF NOT EXISTS `db_shiro` DEFAULT CHARACTER SET utf8;
USE `db_shiro`;
DROP TABLE IF EXISTS `users`;

CREATE TABLE `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `userName` varchar(20) DEFAULT NULL,
  `password` varchar(20) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;

insert  into `users`(`id`,`userName`,`password`) values (1,‘java‘,‘123456‘);

 

  在classpath新建配置文件jdbc_shiro.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/db_shiro
dataSource.user=root
dataSource.password=123456
jdbcRealm.dataSource=$dataSource
securityManager.realms=$jdbcRealm

 

  测试代码:

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

    // 退出
    currentUser.logout();
}

 

4、编程式授权

  shiro_role.ini

[users]
java=123456,role1,role2
jack=123456,role1

  角色

@Test
public void testHasRole() {
    Subject currentUser = ShiroUtils.login("classpath:shiro_role.ini", "java", "123456");
    
    System.out.println(currentUser.hasRole("role1") ? "有role1这个角色" : "没有role1这个角色");
    
    boolean[] results = currentUser.hasRoles(Arrays.asList("role1", "role2", "role3"));
    System.out.println(results[0] ? "有role1这个角色" : "没有role1这个角色");
    System.out.println(results[1] ? "有role2这个角色" : "没有role2这个角色");
    System.out.println(results[2] ? "有role3这个角色" : "没有role3这个角色");
    
    System.out.println(currentUser.hasAllRoles(Arrays.asList("role1", "role2")) ? "role1,role2这两个角色都有"
            : "role1,role2这个两个角色不全有");

    currentUser.logout();
}

@Test
public void testCheckRole() {
    Subject currentUser = ShiroUtils.login("classpath:shiro_role.ini", "java", "123456");
    
    // checkRole,没有该角色报UnauthorizedException
    currentUser.checkRole("role1");
    currentUser.checkRoles(Arrays.asList("role1", "role2"));
    currentUser.checkRoles("role1", "role2", "role3");

    currentUser.logout();
}

 

  shiro_permission.ini

[users]
java=123456,role1,role2
jack=123,role1
[roles]
role1=user:select
role2=user:add,user:update,user:delete

  权限

@Test
public void testIsPermitted() {
    Subject currentUser = ShiroUtils.login("classpath:shiro_permission.ini", "java", "123456");

    System.out.println(currentUser.isPermitted("user:select") ? "有user:select这个权限" : "没有user:select这个权限");
    System.out.println(currentUser.isPermitted("user:update") ? "有user:update这个权限" : "没有user:update这个权限");
    boolean results[] = currentUser.isPermitted("user:select", "user:update", "user:delete");
    System.out.println(results[0] ? "有user:select这个权限" : "没有user:select这个权限");
    System.out.println(results[1] ? "有user:update这个权限" : "没有user:update这个权限");
    System.out.println(results[2] ? "有user:delete这个权限" : "没有user:delete这个权限");
    
    System.out.println(currentUser.isPermittedAll("user:select", "user:update") ? "有user:select,update这两个权限"
            : "user:select,update这两个权限不全有");

    currentUser.logout();
}

@Test
public void testCheckPermitted() {
    Subject currentUser = ShiroUtils.login("classpath:shiro_permission.ini", "java", "123456");
    
    currentUser.checkPermission("user:select");
    currentUser.checkPermissions("user:select", "user:update", "user:delete");
    currentUser.logout();
}

 

  ShiroUtils

package com.oy.common;

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 configFile, String userName, String password) {
        // 读取配置文件,初始化SecurityManager工厂
        Factory<SecurityManager> factory = new IniSecurityManagerFactory(configFile);
        // 获取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;
    }
}

 

Apache Shiro

原文:https://www.cnblogs.com/xy-ouyang/p/11324657.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!