如何在原有的框架中集成shiro

技术如何在原有的框架中集成shiro今天就跟大家聊聊有关如何在原有的框架中集成shiro,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。今天的任务是在原有的框架中集

今天我就来和大家聊聊如何将shiro融入到原来的框架中,可能很多人都没有很好的理解。为了让大家更好地理解,边肖为大家总结了以下内容。希望你能从这篇文章中有所收获。

今天的任务是将shiro集成到原来的框架中。

1.shiro的理解。

权限框架(提供功能强大的易用API)。

1.1与Spring安全的区别。

框架| shiro | Spring安全。

– | – | –

可用性| | X

粒度|粗|细(强大)。

1.2 Shiro的四大基石。

认证、授权、加密和会话管理。

SecurityManager:核心对象realm:获取数据接口。

2.shiro的核心api。

2.1操作前获取securityManager对象。

“`

//I .创建我们自己的领域。

myrealmyrealm=new myrealm();

//二。创建一个核心对象:

DefaultSecurityManagersecurityManager=new defaultsecuritymanager();

security manager . setrealm(my realm);

//三。将安全管理员放在上下文中。

security utils . setsecuritymanager(securityManager);

“`

## 2.2我们使用的方法。

“`

//1.获取当前用户。

SubjectcurrentUser=security utils . getsubject();

//2.确定是否登录。

currentuser . isaauthenticated();

//3.登录(需要令牌)。

/**

未知帐户异常:用户名不存在。

不正确的凭据异常:密码错误。

AuthenticationException:其他错误。

*/

usernamepasswordtoktoken=new usernamepasswordtoke(‘ admin ‘,’ 123456 ‘);

currentUser.login(令牌);

//4.确定是否是该角色/权限。

CurrentUser.hasRole(‘角色名’)

CurrentUser.isPermitted(‘权限名称’)

“`

# 3.密码加密功能。

“`

/**

* StringalgorithmName,Objectsource,Objectsalt,inthashIterations)

*第一个参数algorithmName:加密算法名称。

*第二个参数source:加密原始密码。

*第三个参数salt:盐值。

*第四个参数hashIterations:加密次数。

*/

SimpleHashhash=newSimpleHash(‘ MD5 ‘,’ 123456 ‘,’ itsource ‘,10);

system . out . println(hash . Tohex());

“`

#4.自定义领域

正在继承AuthorizingRealm。

实现两种方法:doGetAuthorizationInfo(授权)/doGetAuthenticationInfo(登录验证)。

“`

//身份验证。

@覆盖

protected authenticationinfodogetauthenticationinfo(Authent

icationToken authenticationToken) throws AuthenticationException {
    //1.拿用户名与密码
    UsernamePasswordToken token = (UsernamePasswordToken)authenticationToken;
    String username = token.getUsername();
    //2.根据用户名拿对应的密码
    String password = getByName(username);
    if(password==null){
        return null; //返回空代表用户名有问题
    }
    //返回认证信息
    //准备盐值
    ByteSource salt = ByteSource.Util.bytes("asdf");
    //密码是shiro自己进行判断
    SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(username,password,salt,getName());
    return authenticationInfo;
}
//授权
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
    //拿到用户名  Principal:主体(用户对象/用户名)
    String username = (String)principalCollection.getPrimaryPrincipal();
    //拿到角色
    Set<String> roles = findRolesBy(username);
    //拿到权限
    Set<String> permis = findPermsBy(username);
    //把角色权限交给用户
    SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
    authorizationInfo.setRoles(roles);
    authorizationInfo.setStringPermissions(permis);
    return authorizationInfo;
}

> 注意:如果我们的密码加密,应该怎么判断(匹配器)

//一.创建我们自己的Realm
MyRealm myRealm = new MyRealm();
//创建一个凭证匹配器(无法设置盐值)
HashedCredentialsMatcher matcher = new HashedCredentialsMatcher();
//  使用MD5的方式比较密码
matcher.setHashAlgorithmName("md5");
// 设置编码的迭代次数
matcher.setHashIterations(10);
//设置凭证匹配器(加密方式匹配)
myRealm.setCredentialsMatcher(matcher);

“`

# 5.集成Spring
> 去找:shiro-root-1.4.0-RC2\samples\spring

## 5.1 导包
“`

<!-- shiro的支持包 -->
 <dependency>
    <groupId>org.apache.shiro</groupId>
    <artifactId>shiro-all</artifactId>
    <version>1.4.0</version>
    <type>pom</type>
</dependency>
  <!-- shiro与Spring的集成包 -->
  <dependency>
    <groupId>org.apache.shiro</groupId>
    <artifactId>shiro-spring</artifactId>
    <version>1.4.0</version>
  </dependency>

## 5.2 web.xml> 这个过滤器是一个代码(只关注它的名称)
 

 <filter>
    <filter-name>shiroFilter</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    <init-param>
      <param-name>targetFilterLifecycle</param-name>
      <param-value>true</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>shiroFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

## 5.3 application-shiro.xml

> 在咱们的application引入

`<import resource="classpath:applicationContext-shiro.xml" />`

> 是从案例中拷备过来,进行了相应的修改“`

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="
       http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
    <!-- 创建securityManager这个核心对象 -->
    <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
        <!-- 设置一个realm进去 -->
        <property name="realm" ref="jpaRealm"/>
    </bean>
    <!-- 被引用的realm(一定会写一个自定义realm) -->
    <bean id="jpaRealm" class="cn.xxx.aisell.shiro.JpaRealm">
        <!-- 为这个realm设置相应的匹配器 -->
        <property name="credentialsMatcher">
            <bean class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
                <!-- 设置加密方式 -->
                <property name="hashAlgorithmName" value="md5"/>
                <!-- 设置加密次数 -->
                <property name="hashIterations" value="10" />
            </bean>
        </property>
    </bean>
    <!--  可以让咱们的权限判断支持【注解】方法 -->
    <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>
    <bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"
          depends-on="lifecycleBeanPostProcessor"/>
    <bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
        <property name="securityManager" ref="securityManager"/>
    </bean>
    <!--  真正实现权限的过滤器 它的id名称和web.xml中的过滤器名称一样 -->
    <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
        <property name="securityManager" ref="securityManager"/>
        <!-- 登录路径:如果没有登录,就会跳到这里来 -->
        <property name="loginUrl" value="/s/login.jsp"/>
        <!-- 登录成功后的跳转路径 -->
        <property name="successUrl" value="/s/main.jsp"/>
        <!-- 没有权限跳转的路径 -->
        <property name="unauthorizedUrl" value="/s/unauthorized.jsp"/>
        <!--
            anon:这个路径不需要登录也可以访问
            authc:需要登录才可以访问
            perms[depts:index]:做权限拦截
                咱们以后哪些访问有权限拦截,需要从数据库中读取
        -->
        <!--
        <property name="filterChainDefinitions">
            <value>
                /s/login.jsp = anon
                /login = anon
                /s/permission.jsp = perms[user:index]
                /depts/index = perms[depts:index]
                /** = authc
            </value>
        </property>
        -->
        <property name="filterChainDefinitionMap" ref="filterChainDefinitionMap" />
    </bean>
    <!-- 实例工厂设置 -->
    <bean id="filterChainDefinitionMap"
          factory-bean="filterChainDefinitionMapFactory"
          factory-method="createFilterChainDefinitionMap" />
    <!-- 创建可以拿到权限map的bean -->
    <bean id="filterChainDefinitionMapFactory" class="cn.itsource.aisell.shiro.FilterChainDefinitionMapFactory" />
</beans>

“`

5.4 获取Map过滤

> 注意,返回的Map必需是有序的(LinkedHashMap)“`

public class FilterChainDefinitionMapFactory {
    /**
     * 后面这个值会从数据库中来拿
     * /s/login.jsp = anon
     * /login = anon
     * /s/permission.jsp = perms[user:index]
     * /depts/index = perms[depts:index]
     * /** = authc
     */
    public Map<String,String> createFilterChainDefinitionMap(){
        //注:LinkedHashMap是有序的
        Map<String,String> filterChainDefinitionMap = new LinkedHashMap<>();
        filterChainDefinitionMap.put("/s/login.jsp", "anon");
        filterChainDefinitionMap.put("/login", "anon");
        filterChainDefinitionMap.put("/s/permission.jsp", "perms[user:index]");
        filterChainDefinitionMap.put("/depts/index", "perms[depts:index]");
        filterChainDefinitionMap.put("/**", "authc");
        return filterChainDefinitionMap;
    }
}

今日重点 : 对securityManage 对象的获取,在权限认证步骤中需要的信息传递(用户,角色,权限)

细节 : 对于在设置权限列表时需要注意顺序,—–放行在前->权限在后->最后同一拦截  /** = authc

看完上述内容,你们对如何在原有的框架中集成shiro有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注行业资讯频道,感谢大家的支持。

内容来源网络,如有侵权,联系删除,本文地址:https://www.230890.com/zhan/36811.html

(0)

相关推荐

  • 如何进行java在hashmap初始化时赋初值过程的解析

    技术如何进行java在hashmap初始化时赋初值过程的解析如何进行java在hashmap初始化时赋初值过程的解析,很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习

    攻略 2021年12月8日
  • 真丝裙,真丝裙贱上水就有痕迹怎么办

    技术真丝裙,真丝裙贱上水就有痕迹怎么办真丝绸的一个特性就是局部沾水后容易形成水渍痕迹。这是真丝纤维本身亲水性太强、局部在沾水后真丝裙,纤维大分子沾到水的部位,水分子跟纤维上的亲水性基团比如羟基(-OH)、氨基(-NH)发

    生活 2021年10月30日
  • http协议无状态中的 "状态" 指的是什么

    技术http协议无状态中的 “状态” 指的是什么这篇文章主要介绍“http协议无状态中的 “状态” 指的是什么”,在日常操作中,相信很多人在http协议无状态中的 “状态” 指的是什么问题上存在疑惑,小编查阅了各式资料,

    攻略 2021年10月22日
  • 常用Perl命令行参数应用的分析

    技术常用Perl命令行参数应用的分析本篇文章为大家展示了常用Perl命令行参数应用的分析,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。Perl命令行应用介绍Perl有很多Perl

    攻略 2021年11月12日
  • zookeeper和eureka使用场景(eureka与zookeeper差别)

    技术如何进行ZooKeeper与Eureka的比较如何进行ZooKeeper与Eureka的比较,很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获

    攻略 2021年12月24日
  • 腊肠炒饭,什么食物搭配蛋炒饭会好吃到爆

    技术腊肠炒饭,什么食物搭配蛋炒饭会好吃到爆来个高逼格的什锦芝士焗饭吧腊肠炒饭,简单地说就是蛋炒饭上铺一层芝士,然后微波炉一加热,丝丝香甜的芝士焗饭就做好了哦所需材料:米饭,香肠,白玉菇(可放可不放),土豆,玉米粒少许,马

    生活 2021年10月30日