shiro入门案例

shiro简介
shiro是一个功能强大、易于使用的Java安全框架,可以执行身份验证,授权、加密和会话管理。通过Shiro易于理解的API,您可以做到这一点快速、轻松地保护任何应用程序——从最小的移动应用程序到最大的we和企业应用程序。
shiro架构
在这里插入图片描述
Subject:主体,代表当前用户,与当前应用交互的任何东西都是subject,如网络爬虫,机器人等;即是一个抽象概念;所有的Subject都绑定到SecurityManager,与Subjectd的所有交互都委托给SecurityManager,把Subject认为是一个门面,SecurityMabager才是实际执行者。
SecurityManager:安全管理器,即所有与安全相关的操作都与SecurityNanager交互,它管理者所有的Subject,是shiro的核心,它负责与其他组件交互。
Realm:域,Subjec从Realm中获取安全数据(如用户,角色,权限),SecurityManager要验证用户身份,就需要从Realm中获取相应的用户进行比较以确定用户身份是否合法,也需要从Realm中得到用户相应的角色、权限进行验证用户是否能进行操作。

项目结构
在这里插入图片描述

shiro认证

1.新建maven工程导入以下依赖
<dependencies>
        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-core</artifactId>
            <version>1.4.1</version>
        </dependency>

        <!-- configure logging -->
        <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>
    </dependencies>

2.在resource文件夹下加入日志(可以省略)

#
# 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=INFO

# Disable verbose logging
log4j.logger.org.apache.shiro.util.ThreadContext=WARN
log4j.logger.org.apache.shiro.cache.ehcache.EhCache=WARN

3.在resource文件夹下创建shiro.ini

#用户  用户名=密码,角色1,角色2...
[users]
root=123456,boss
xiaoming=123123,manager
#角色
[roles]
boss=*
#goods:add goods是资源   add是对资源的操作
manager=goods:add,goods:delete,goods:update

4.新建测试类

package com.aaa.test;

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.subject.Subject;

public class ShiroTest {
    public static void main(String[] args) {
        //读取配置文件,通过IniSecurityManagerFactory 工厂加载shiro.ini  获取 SecurityManager实列
       /* IniSecurityManagerFactory factory=new
                IniSecurityManagerFactory("classpath:shiro2.ini");
        IniSecurityManagerFactory factory=new
                IniSecurityManagerFactory("classpath:shiro1.ini");*/
       //自定义认证加授权
        IniSecurityManagerFactory factory=new
                IniSecurityManagerFactory("classpath:shiro2.ini");
        //获取secyrityManager,安全管理器
        SecurityManager securityManager=factory.getInstance();
        // 将SecurityUtils 与 securityManager绑定
        SecurityUtils.setSecurityManager(securityManager);
        //获取当前用户,获取Subject 主体
        Subject subject = SecurityUtils.getSubject();
            AuthenticationToken token=new UsernamePasswordToken("root","123456");
       try{
           //登录认证
           subject.login(token);
       } catch (UnknownAccountException uae) {
           // 找不到用户名
           System.out.println("There is no user with username of " + token.getPrincipal());
       } catch (IncorrectCredentialsException ice) {
           // 密码错误
           System.out.println("Password for account " + token.getPrincipal() + " was incorrect!");
       } catch (LockedAccountException lae) {
           // 用户已被锁定
           System.out.println("The account for username " + token.getPrincipal() + " is locked.  " +
                   "Please contact your administrator to unlock it.");
       } catch (AuthenticationException ae) {
           //unexpected condition?  error?
           System.out.println("其他异常");
       }
        if (subject.isAuthenticated()){
            System.out.println("认证成功");
           String username = (String) subject.getPrincipal();
            System.out.println("username:"+username);
            if (subject.isPermitted("goods:add")){
                System.out.println("当前用户是否拥有权限:"+"goods:add");
            }
            if (subject.hasRole("boss")){
                System.out.println("当前用户拥有boss角色");
            }
        }else {
            System.out.println("认证失败");
        }
        //退出当前用户,退出登录无法认证
        subject.logout();
        if (subject.isAuthenticated()){
            System.out.println("认证成功222");
        }
    }
}

shiro自定义认证
1.新建Realm文件夹,创建CustomerRealm类,继承 AuthenticatingRealm

package com.aaa.realm;

import org.apache.shiro.authc.*;
import org.apache.shiro.realm.AuthenticatingRealm;

/**
 * 自定义用户认证
 */
public class CustomerRealm extends AuthenticatingRealm {
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String username = (String) authenticationToken.getPrincipal();
        System.out.println("username:"+username);
        //根据用户名去数据库查密码
        //自定义密码
        String passwordFromDB="123456";
        //得到用户  真实的数据库用户名密码
        SimpleAuthenticationInfo simpleAuthenticationInfo=new SimpleAuthenticationInfo(username,passwordFromDB,this.getName());
        return simpleAuthenticationInfo;
    }
}

2.2.创建 shiro1.ini,将CustomerRealm全包名配置在myRealm 参数中

[main]
myRealm=com.aaa.realm.CustomerRealm



3.修改 测试类中加载 的配置文件 shiro1.ini

public class ShiroTest {
    public static void main(String[] args) {
        //读取配置文件,通过IniSecurityManagerFactory 工厂加载shiro.ini  获取 SecurityManager实列
       /* IniSecurityManagerFactory factory=new
                IniSecurityManagerFactory("classpath:shiro1.ini");

shiro自定义认证加授权
1.新建CustomerRealm2

package com.aaa.realm;

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

/**
 * 自定义用户认证 +授权
 * AuthenticatingRealm:认证
 * AuthorizingRealm:认证加授权
 */
public class CustomerRealm1 extends AuthorizingRealm {
    //获取认证信息
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String username = (String) authenticationToken.getPrincipal();
        System.out.println("username:"+username);
        //需要自己去数据库校验用户名是否存在,如果不存在,需要手动抛出异常
        if (!username.equals("root")){
            throw  new UnknownAccountException();
        }
        //根据用户名去数据库查密码
        //自定义密码
        String passwordFromDB="123456";
        //得到用户  真实的数据库用户名密码
        SimpleAuthenticationInfo simpleAuthenticationInfo=new SimpleAuthenticationInfo(username,passwordFromDB,this.getName());
        return simpleAuthenticationInfo;
    }
        //授权
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
      String username = (String) principalCollection.getPrimaryPrincipal();
        System.out.println("username:"+username);

        SimpleAuthorizationInfo simpleAuthorizationInfo=new SimpleAuthorizationInfo();
        //去数据库查询root相关的角色和权限
        if (username.endsWith("root")){
            //设置当前用户角色
            simpleAuthorizationInfo.addRole("boss");
            //设置权限
            simpleAuthorizationInfo.addStringPermission("goods:add");
            simpleAuthorizationInfo.addStringPermission("goods:delete");
        }
        //返回给SimpleAuthorizationInfo  当前用户权限角色
        return simpleAuthorizationInfo;
    }
}

2.新建配置文件shiro2.ini

[main]
myRealm=com.aaa.realm.CustomerRealm1

3.修改 测试类中加载 的配置文件 shiro2.ini

            IniSecurityManagerFactory("classpath:shiro1.ini");*/
       //自定义认证加授权
        IniSecurityManagerFactory factory=new
                IniSecurityManagerFactory("classpath:shiro2.ini");
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值