×

shiro框架配置文件 配置

shiro框架配置文件(shiro记住我cookie无法添加 按照网上的说法 把配置文件中所有的配置都写了 javabea)

admin admin 发表于2023-12-24 13:53:40 浏览31 评论0

抢沙发发表评论

本篇文章给大家谈谈shiro框架配置文件,以及shiro记住我cookie无法添加 按照网上的说法 把配置文件中所有的配置都写了 javabea对应的知识点,文章可能有点长,但是希望大家可以阅读完,增长自己的知识,最重要的是希望对各位有所帮助,可以解决了您的问题,不要忘了收藏本站喔。

本文目录

shiro记住我cookie无法添加 按照网上的说法 把配置文件中所有的配置都写了 javabea

ie11下查看cookie:1:IE11=》F12打开开发人员工具2:开发人员工具=》网络F5启用网络流量捕获3:IE11=》输入和访问相关网址4:开发人员工具=》网络=》详细信息=》Cookie如果你只在java后台写的cookie,前端浏览器当然看不到

springMvc+shiro做权限管理,页面上的静态资源,样式图片等没有出现,用几种方式过滤试过,还是不行

正常情况是不会出现这样的,shiro对于静态资源的处理,不用特殊配置。

只需要在shiroFilter过滤器filterChainDefinitions项中增加一个静态资源处理规则就可以,例如允许/css/开头的资源匿名访问,只需要这样一句配置就足矣。

/css/**  = anon 

配置完成后,未登录就可以在浏览器中直接访问css下的资源,新项目用的shiro,简单而又实用的权限框架。

在shiroFilter 和 mvc:resources中都需要配置,如:

shiroFilter中:

《property name="filterChainDefinitions"》

《value》

/css/** = anon

/js/** = anon

/img/** = anon

《/value》

《/property》在spring-mvc.xml中:

《mvc:resources mapping="/css/**" location="/css/" cache-period="2592000"/》 

《mvc:resources mapping="/img/**" location="/img/" cache-period="2592000"/》 

《mvc:resources mapping="/js/**" location="/js/" cache-period="2592000"/》

【Shiro】一步步的看Shiro 【Shiro与Spring Security区别】

Apache Shiro 是 Java 的一个安全框架。目前,使用 Apache Shiro 的人越来越多,因为它相 当简单,Shiro 可以非常容易的开发出足够好的应用,其不仅可以用在 JavaSE 环境,也可以用在 JavaEE 环境。Shiro 可以帮助我们完成:认证、授权、加密、会话管理、与 Web 集成、缓 存等

Spring Security是一个提供身份验证、授权和防范常见攻击的框架。它对命令式应用程序和响应式应用程序都提供了一流的支持,是保护基于spring的应用程序的事实上的标准

OAuth for Spring Security为Spring Security提供了一个OAuth实现。支持OAuth提供者和OAuth消费者的实现。支持OAuth 2.0

完美撒花~,下面我会根据Shiro的具体内容结合不同场景的进行讲述以及配置。

有需要讨论Shiro和Spring Security有什么区别或者有什么不同看法的,欢迎留言 大家共同学习

ssm框架访问控制应该怎么做

这个就在在人员表了添加一个身份的字段 user_rank ,用这个来控制。用户登录到时候就会用登录信息,把这个 user_rank 字段带出来,在页面或者链接时候加上判断,哈这是简单的,看下官方的。

shiro安全框架是目前为止作为登录注册最常用的框架,因为它十分的强大简单,提供了认证、授权、加密和会话管理等功能 。

shiro能做什么?

认证:验证用户的身份

授权:对用户执行访问控制:判断用户是否被允许做某事

会话管理:在任何环境下使用 Session API,即使没有 Web 或EJB 容器。

加密:以更简洁易用的方式使用加密功能,保护或隐藏数据防止被偷窥

Realms:聚集一个或多个用户安全数据的数据源

单点登录(SSO)功能。

为没有关联到登录的用户启用 "Remember Me“ 服务

Shiro 的四大核心部分

Authentication(身份验证):简称为“登录”,即证明用户是谁。

Authorization(授权):访问控制的过程,即决定是否有权限去访问受保护的资源。

Session Management(会话管理):管理用户特定的会话,即使在非 Web 或 EJB 应用程序。

Cryptography(加密):通过使用加密算法保持数据安全

shiro的三个核心组件:     

Subject :正与系统进行交互的人,或某一个第三方服务。所有 Subject 实例都被绑定到(且这是必须的)一个SecurityManager 上。

SecurityManager:Shiro 架构的心脏,用来协调内部各安全组件,管理内部组件实例,并通过它来提供安全管理的各种服务。当 Shiro 与一个 Subject 进行交互时,实质上是幕后的 SecurityManager 处理所有繁重的 Subject 安全操作。

Realms :本质上是一个特定安全的 DAO。当配置 Shiro 时,必须指定至少一个 Realm 用来进行身份验证和/或授权。Shiro 提供了多种可用的 Realms 来获取安全相关的数据。如关系数据库(JDBC),INI 及属性文件等。可以定义自己 Realm 实现来代表自定义的数据源。

shiro整合SSM框架:

1.加入 jar 包:以下jar包自行百度下载

2.配置 web.xml 文件

在web.xml中加入以下代码—shiro过滤器。

《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》 

3.在 Spring 的配置文件中配置 Shiro

Springmvc配置文件中:《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》

Spring配置文件中导入shiro配置文件:

《!-- 包含shiro的配置文件 --》《import resource="classpath:applicationContext-shiro.xml"/》

新建applicationContext-shiro.xml

***隐藏网址******隐藏网址******隐藏网址***《!-- 配置缓存管理器 --》《bean id="cacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager"》《!-- 指定 ehcache 的配置文件,下面会给到 --》《property name="cacheManagerConfigFile" value="classpath:ehcache-shiro.xml"/》《/bean》《!-- 配置进行授权和认证的 Realm,要新增一个java类来实现,下面会有,class=包名.类名,init-methood是初始化的方法 --》《bean id="myRealm"class="shiro.MyRealm"init-method="setCredentialMatcher"》《/bean》《!-- 配置 Shiro 的 SecurityManager Bean. --》《bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager"》《property name="cacheManager" ref="cacheManager"/》《property name="realm" ref="myRealm"/》《/bean》《!-- 配置 Bean 后置处理器: 会自动的调用和 Spring 整合后各个组件的生命周期方法. --》《bean id="lifecycleBeanPostProcessor"class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/》《!-- 配置 ShiroFilter bean: 该 bean 的 id 必须和 web.xml 文件中配置的 shiro filter 的 name 一致  --》《bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean"》《!-- 装配 securityManager --》《property name="securityManager" ref="securityManager"/》《!-- 配置登陆页面 --》《property name="loginUrl" value="/index.jsp"/》《!-- 登陆成功后的一面 --》《property name="successUrl" value="/shiro-success.jsp"/》《property name="unauthorizedUrl" value="/shiro-unauthorized.jsp"/》《!-- 具体配置需要拦截哪些 URL, 以及访问对应的 URL 时使用 Shiro 的什么 Filter 进行拦截.  --》《property name="filterChainDefinitions"》《value》《!-- 配置登出: 使用 logout 过滤器 --》/shiro-logout = logout/shiro-* = anon/user.jsp = roles/admin.jsp = roles/** = authc            《/value》《/property》《/bean》《/beans》

导入ehcache-shiro.xml配置文件:

《!--~ 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~***隐藏网址***~~ 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.  --》《!-- EhCache XML configuration file used for Shiro spring sample application --》《ehcache》《!-- Sets the path to the directory where cache .data files are created.If the path is a Java System Property it is replaced byits value in the running VM.The following properties are translated:user.home - User’s home directoryuser.dir - User’s current working directoryjava.io.tmpdir - Default temp file path --》《diskStore path="java.io.tmpdir/shiro-spring-sample"/》《!--Default Cache configuration. These will applied to caches programmatically created throughthe CacheManager.The following attributes are required:maxElementsInMemory            - Sets the maximum number of objects that will be created in memoryeternal                        - Sets whether elements are eternal. If eternal,  timeouts are ignored and theelement is never expired.overflowToDisk                 - Sets whether elements can overflow to disk when the in-memory cachehas reached the maxInMemory limit.The following attributes are optional:timeToIdleSeconds              - Sets the time to idle for an element before it expires.i.e. The maximum amount of time between accesses before an element expiresIs only used if the element is not eternal.Optional attribute. A value of 0 means that an Element can idle for infinity.The default value is 0.timeToLiveSeconds              - Sets the time to live for an element before it expires.i.e. The maximum time between creation time and when an element expires.Is only used if the element is not eternal.Optional attribute. A value of 0 means that and Element can live for infinity.The default value is 0.diskPersistent                 - Whether the disk store persists between restarts of the Virtual Machine.The default value is false.diskExpiryThreadIntervalSeconds- The number of seconds between runs of the disk expiry thread. The default valueis 120 seconds.memoryStoreEvictionPolicy      - Policy would be enforced upon reaching the maxElementsInMemory limit. Defaultpolicy is Least Recently Used (specified as LRU). Other policies available -First In First Out (specified as FIFO) and Less Frequently Used(specified as LFU)    --》《defaultCache            maxElementsInMemory="10000"eternal="false"timeToIdleSeconds="120"timeToLiveSeconds="120"overflowToDisk="false"diskPersistent="false"diskExpiryThreadIntervalSeconds="120"/》《!-- We want eternal="true" (with no timeToIdle or timeToLive settings) because Shiro manages sessionexpirations explicitly.  If we set it to false and then set corresponding timeToIdle and timeToLive properties,ehcache would evict sessions without Shiro’s knowledge, which would cause many problems(e.g. "My Shiro session timeout is 30 minutes - why isn’t a session available after 2 minutes?"Answer - ehcache expired it due to the timeToIdle property set to 120 seconds.)diskPersistent=true since we want an enterprise session management feature - ability to use sessions aftereven after a JVM restart.  --》《cache name="shiro-activeSessionCache"maxElementsInMemory="10000"eternal="true"overflowToDisk="true"diskPersistent="true"diskExpiryThreadIntervalSeconds="600"/》《cache name="org.apache.shiro.realm.SimpleAccountRealm.authorization"maxElementsInMemory="100"eternal="false"timeToLiveSeconds="600"overflowToDisk="false"/》《/ehcache》

准备好了,接下来要写Realm方法了,新建shiro包,在包下新建MyRealm.java文件继承AuthorizingRealm

package shiro;import org.apache.shiro.authc.AuthenticationException;import org.apache.shiro.authc.AuthenticationInfo;import org.apache.shiro.authc.AuthenticationToken;import org.apache.shiro.authc.SimpleAuthenticationInfo;import org.apache.shiro.authc.credential.HashedCredentialsMatcher;import org.apache.shiro.authz.AuthorizationInfo;import org.apache.shiro.authz.SimpleAuthorizationInfo;import org.apache.shiro.crypto.hash.Md5Hash;import org.apache.shiro.crypto.hash.SimpleHash;import org.apache.shiro.realm.AuthorizingRealm;import org.apache.shiro.subject.PrincipalCollection;import org.apache.shiro.util.ByteSource;import org.springframework.beans.factory.annotation.Autowired;import bean.user;import dao.userdao;public class MyRealm extends AuthorizingRealm {@Autowired    private userdao userdao;String pass;    /*** 授权:**/@Override    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();Object principal = principalCollection.getPrimaryPrincipal();//获取登录的用户名if("admin".equals(principal)){               //两个if根据判断赋予登录用户权限info.addRole("admin");}        if("user".equals(principal)){info.addRole("list");}info.addRole("user");return info;}    /** 用户验证**/@Override    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {//1. token 中获取登录的 username! 注意不需要获取password.Object principal = token.getPrincipal();//2. 利用 username 查询数据库得到用户的信息.user user=userdao.findbyname((String) principal);        if(user!=null){pass=user.getPass();}String credentials = pass;        //3.设置盐值 ,(加密的调料,让加密出来的东西更具安全性,一般是通过数据库查询出来的。 简单的说,就是把密码根据特定的东西而进行动态加密,如果别人不知道你的盐值,就解不出你的密码)String source = "abcdefg";ByteSource credentialsSalt = new Md5Hash(source);//当前 Realm 的nameString realmName = getName();        //返回值实例化SimpleAuthenticationInfo info =new SimpleAuthenticationInfo(principal, credentials,credentialsSalt, realmName);return info;}    //init-method 配置.public void setCredentialMatcher(){HashedCredentialsMatcher  credentialsMatcher = new HashedCredentialsMatcher();credentialsMatcher.setHashAlgorithmName("MD5");//MD5算法加密credentialsMatcher.setHashIterations(1024);//1024次循环加密setCredentialsMatcher(credentialsMatcher);}//用来测试的算出密码password盐值加密后的结果,下面方法用于新增用户添加到数据库操作的,我这里就直接用main获得,直接数据库添加了,省时间public static void main(String args) {String saltSource = "abcdef";String hashAlgorithmName = "MD5";String credentials = "passwor";Object salt = new Md5Hash(saltSource);        int hashIterations = 1024;Object result = new SimpleHash(hashAlgorithmName, credentials, salt, hashIterations);System.out.println(result);}}

好了,接下来我们写一个简单的action来通过shiro登录验证。

//登录认证    @RequestMapping("/shiro-login")    public String login(@RequestParam("username") String username,            @RequestParam("password") String password){        Subject subject = SecurityUtils.getSubject();        UsernamePasswordToken token = new UsernamePasswordToken(username, password);                try {            //执行认证操作.             subject.login(token);        }catch (AuthenticationException ae) {            System.out.println("登陆失败: " + ae.getMessage());            return "/index";        }                return "/shiro-success";    }

//温馨提示:记得在注册中密码存入数据库前也记得加密哦,提供一个utils方法//进行shiro加密,返回加密后的结果public static String md5(String pass){String saltSource = "blog";    String hashAlgorithmName = "MD5";Object salt = new Md5Hash(saltSource);int hashIterations = 1024;    Object result = new SimpleHash(hashAlgorithmName, pass, salt, hashIterations);String password = result.toString();return password;}

好了,shiro登录验证到这里完了

若依 权限框架 Shiro

1. shiro中的重要概念

要理解shiro,先要理解框架的几个概念:

1) Subject : 代表当前登陆或者访问的用户;

2) Principals :一般指用户名等,唯一表明Subject身份也就是当前用户身份的东西;

3) Credentials :凭证,一般指密码,对当前登陆用户进行验证;

4) Realms: 域,一般是指存储用户信息(用户名,密码,权限,角色)的数据库,也就是保存用户权限等信息的数据源

5) SecurityManager :shiro安全管理的顶级对象。它集合或者说调用所有其它相关组件,负责所有安全和权限相关处理过程,就像一个中央集权政府;

2. shiro的子系统

上面我们说到shiro的主要功能有:认证,授权,加密,session管理等。而每一个主要功能对应于shiro的一个子系统, 下面分别介绍。

3. Authentication认证子系统

认证子系统,就是处理用户登录,验证用户登录。

一般我们new一个UsernamePasswordToken的对象:UsernamePasswordToken token = new UsernamePasswordToken("xxxusername", "xxxpassword");,

然后 subject.login(token); 就前去登录。相关代码一般如下:

Authentication 子系统会将password加密,然后使用username和加密之后的password和从Realm(一般是数据库)中根据usename获得的密码进行比较,相同就登录成功,不相同同就登录失败,或者用户名不存在也登录失败。就怎么简单。当然从Realm中根据用户名查找用户的过程是需要我们自己编码实现的。该功能的实现代码如下 。

4. Authorization 授权子系统(访问控制,权限控制)

在需要判断用户是否有某权限或者角色时,代码如下:

我们看到 doGetAuthorizationInfo 方法中使用了 SimpleAuthorizationInfo 类封装 Role 和 Permission.roles 和 stringPermissions 都是 String 类型的 Set, 也就是说,它们都是使用字符串来表示你拥有某个角色或者拥有某个权限的。

1) 两种访问控制方式:

SimpleAuthorizationInfo 封装了角色和权限,其实这也说明了实现“访问控制”两种方式:一是 “ 基于角色的访问控制 ” ;而是“ 基于资源的访问控制 ”。所谓的访问控制, 是指对于某个资源,当前用户是否有访问的权限。基于角色的访问控制是一种比较粗粒度的访问控制方式,只要你具有了某个或某几个角色,那么你就可以访问某资源。而基于资源的访问控制,是判断你针对该资源是否有某权限,有才能访问,粒度更细,你是否有某权限,可以根据你有哪些角色,然后改角色有哪些权限来判断的,当然也可以不引入角色的概念,直接判断你是否拥有某些权限。当然两种访问方式可以单独使用,也可以混合使用。比如对于比较简单的权限控制,你可以仅仅只使用基于角色的访问控制,仅仅引入角色表,不需要权限表都可以。混合使用是指,你可以同时要求用户具有某角色并且具有某些权限,才能访问某资源。所以shiro的权限控制时极其灵活的(当然也可以不引入角色表,仅仅引入权限表)。

2)权限的字符串表示方式

上面说到 角色 和 权限 都是使用字符串来表示的,其实 shiro 提供了一套比较强大有点复杂的权限字符串表示格式(分为:分割的三个部分):“ 资源:操作:对象实例ID ” 表示:对那个资源的哪个实例可以进行哪些操作,支持通配符。多个操作需要使用 “,” 逗号分割,而 “*” 放在三个位置上,分别表示:任意资源,任意操作,任意实例。比如:"user:delete:1" 就表示 对user表的id等于1对应的数据或者对象,可以进行删除操作。其实资源表现实现可以是对象,其实最终是对应到数据库表中的记录。再比如:"user:update,delete" 就表示 对user表(的任意实例)进行更新和删除操作。"user:update,delete" 其实就等价于 “user:update,delete:*”所以 shiro 的访问控制可以控制到具体实例,或者说具体哪条数据库记录,也可以在表级别控制。如果省略掉 对象实例ID部分,就是在表级别控制。

3)权限相关表的设计

1》 如果对于简单的情况,可以只使用“基于角色的访问控制”粗粒度方式,不涉及到权限,仅仅只通过判断是否有某角色来判断访问控制,那么就只需要增加一个角色表(roles) 和 一个角色(roles)和用户(user)的多对多的一个中间表——用户角色表(user_role)。

2》 如果仅仅使用权限来控制访问,那么就可以仅仅只增加一个权限表(priv)和一个用户和权限的多对多的一个中间表——用户权限表(user_priv).

3》 如果既要用到角色,又要用到权限(权限根据角色推算出来),那么就要增加:角色表,用户角色表,权限表,角色权限表。

4》 其实还有一种情况:就是角色和权限没有关系,那么就可以增加:角色表,用户角色表,权限表,用户权限表。不过这种方式不同符合常规。

其他的 如 Cryptography 加密子系统 和 Session Management会话管理子系统 这里不做介绍。

如何正确的使用shiro

从来没接触过shiro Java安全框架,突然有一天需要要用用户登陆验证和用户角色权限的任务,而且是针对shiro 进行整合,开始收到任务,心都有点凉凉的。经过一轮的搜索,感觉没多大的收获。很多用户的角色都是写在xml配置文件中。觉得太不人性化了,想换个用户角色还得改xml?我觉得这么强大的框架应该不可能这么狗血的存在。然后认真的看文档,发现真的是可以直接读取数据库的。我把我搭建的流程发布在此。有问题的可以交流交流。我写的也并不是正确的,只能参考参考。1.web.xml的配置《listener》《listener-class》org.apache.shiro.web.env.EnvironmentLoaderListener《/listener-class》《/listener》《filter》《filter-name》shiroFilter《/filter-name》《filter-class》org.apache.shiro.web.servlet.ShiroFilter《/filter-class》《/filter》《filter-mapping》《filter-name》shiroFilter《/filter-name》《url-pattern》/*《/url-pattern》《/filter-mapping》2.shiro.ini配置#自定义realmshiroAuthorizingRealm = com.frame.security.ShiroAuthorizingRealmsecurityManager.realm = $shiroAuthorizingRealm# 声明一个自定义的用户校验拦截器customFormAuthenticationFilter = com.frame.security.CustomFormAuthenticationFilter# 声明一个自定义的用户角色权限拦截器customPermissionsAuthorizationFilter = com.frame.security.CustomPermissionsAuthorizationFilter#cacheshiroCacheManager = org.apache.shiro.cache.ehcache.EhCacheManagershiroCacheManager.cacheManagerConfigFile = classpath:ehcache.xmlsecurityManager.cacheManager = $shiroCacheManager#sessionsessionDAO = org.apache.shiro.session.mgt.eis.EnterpriseCacheSessionDAOsessionManager = org.apache.shiro.web.session.mgt.DefaultWebSessionManagersessionManager.sessionDAO = $sessionDAOsecurityManager.sessionManager = $sessionManagersecurityManager.sessionManager.globalSessionTimeout = 1800000securityManager = org.apache.shiro.web.mgt.DefaultWebSecurityManager/admin/user/login = anon/admin/user/logout = anon/admin/user/registered = anon/admin/** = customFormAuthenticationFilter,customPermissionsAuthorizationFilter从shiro.ini配置中可以看出,需要三个文件,分别为ShiroAuthorizingRealm.java(realm文件),CustomFormAuthenticationFilter.java(自定义用户登陆验证文件),CustomPermissionsAuthorizationFilter(自定义用户角色权限文件);在urls配置中可以看出不需要拦截的url后面加上anon便可,但有先后顺序。缓存是使用ehcache3.ehcache.xml配置《cache name="defaultCache" maxElementsInMemory="500"maxElementsOnDisk="10000000" eternal="true" overflowToDisk="true"diskSpoolBufferSizeMB="50" /》《cache name="shiro-activeSessionCache" maxElementsInMemory="500"maxElementsOnDisk="10000000" eternal="true" overflowToDisk="true"diskSpoolBufferSizeMB="50" /》《cache name="jdbcRealm.authorizationCache" maxElementsInMemory="500"maxElementsOnDisk="10000000" eternal="true" overflowToDisk="true"diskSpoolBufferSizeMB="50" /》《cache name="authorization" maxElementsInMemory="500"timeToLiveSeconds="3600" eternal="false" overflowToDisk="false" /》4.ShiroAuthorizingRealm.javapublic class ShiroAuthorizingRealm extends AuthorizingRealm {private AuthorityService authorityService = FrameContext.getBean(AuthorityService.class);@Overrideprotected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {System.out.println("=======doGetAuthenticationInfo=======");UsernamePasswordToken userToken = (UsernamePasswordToken) token;String username = userToken.getUsername();String password = String.valueOf(userToken.getPassword());User user = User.dao.findFirst("select * from m_user where account = ?", username);if (user != null) {//下面可以做一些登陆的操作,密码错误,用户状态等等if(MD5Encoder.validPassword(password, user.getPassword())==false){throw new UnknownAccountException();}SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, password, getName());return info;} else {return null;}}@Overrideprotected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {System.out.println("=======doGetAuthorizationInfo=======");User user = (User) principals.getPrimaryPrincipal();if(user!=null){//从数据库中读取用户的角色权限,SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();List《String》 perms = authorityService.getUrlByUser(user);if(perms!=null&&perms.size()》0){//调用addStringPermissions方法把用户的权限信息添加到info中,可以addRoles方法把用户的角色添加到了info中info.addStringPermissions(perms);}return info;}return null;}}5.CustomFormAuthenticationFilter.javapublic class CustomFormAuthenticationFilter extends FormAuthenticationFilter {private final static Logger log = Logger.getLogger(CustomFormAuthenticationFilter.class);private static final String contentType = "application/json; charset=UTF-8";protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {***隐藏网址******隐藏网址***if (isLoginRequest(request, response)) {if (isLoginSubmission(request, response)) {if (log.isTraceEnabled()) {log.trace("Login submission detected. Attempting to execute login.");}return executeLogin(request, response);} else {if (log.isTraceEnabled()) {log.trace("Login page view.");}return true;}} else {Result《Object》 result = new Result《Object》(false, "401", "没有授权,请先登录", null);***隐藏网址***return false;} }private void renderJson(HttpServletResponse response, Object object) {String jsonText = JsonKit.toJson(object);PrintWriter writer = null;try {response.setHeader("Pragma", "no-cache"); // HTTP/1.0 caches might not implement Cache-Control and might only implement Pragma: no-cacheresponse.setHeader("Cache-Control", "no-cache");response.setDateHeader("Expires", 0);response.setContentType(contentType);writer = response.getWriter();writer.write(jsonText);writer.flush();} catch (IOException e) {throw new RenderException(e);}finally {if (writer != null) {writer.close();}}}}6.CustomPermissionsAuthorizationFilter.javapublic class CustomPermissionsAuthorizationFilter extends PermissionsAuthorizationFilter {private static final String contentType = "application/json; charset=UTF-8";private AuthorityService authorityService = McmsContext.getBean(AuthorityService.class);@Overridepublic boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws IOException {if(getMappedValue(request)!=null){return super.isAccessAllowed(request, response, getMappedValue(request));}return false;}@Overrideprotected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws IOException {// TODO Auto-generated method stub***隐藏网址******隐藏网址******隐藏网址***Subject subject = getSubject(request, response);if (subject.isPermitted(path)) {return true;} else {Result《Object》 result = new Result《Object》(false, "401", "抱歉,您没有该权限!", null);***隐藏网址***return false;}}/*** 得到mappedValue,相当于perms中的“user:add”* @param path* @return*/public String getMappedValue(ServletRequest request) {HttpServletRequest req = (HttpServletRequest) request;String path = req.getServletPath();String code = getCodesByPath(path);if(null == code) {return null;}return new String{code};}/*** 根据访问路径获取权限代码* @param path* @return*/public String getCodesByPath(String path) {User user = (User) SecurityUtils.getSubject().getPrincipal();String pers = authorityService.getUrlByUserPath(path,user);return Optional.ofNullable(pers).orElse(null);}private void renderJson(HttpServletResponse response, Object object) {String jsonText = JsonKit.toJson(object);PrintWriter writer = null;try {response.setHeader("Pragma", "no-cache"); // HTTP/1.0 caches might not implement Cache-Control and might only implement Pragma: no-cacheresponse.setHeader("Cache-Control", "no-cache");response.setDateHeader("Expires", 0);response.setContentType(contentType);writer = response.getWriter();writer.write(jsonText);writer.flush();} catch (IOException e) {throw new RenderException(e);}finally {if (writer != null) {writer.close();}}}}7.用户登陆入口public void login() {String account = getPara("account");String password = getPara("password");Subject subject = SecurityUtils.getSubject();UsernamePasswordToken tokens = new UsernamePasswordToken(account, password);tokens.setRememberMe(false);try {subject.login(tokens);User user = (User) subject.getPrincipal();loginSuccess(user);UserVo userVo = convertToUserVO(user);renderSucessResult(userVo);} catch (UnknownAccountException ue) {tokens.clear();renderFailedResult("登录失败!无效的账号或密码!");} catch (IncorrectCredentialsException ie) {tokens.clear();renderFailedResult("用户已注销!");} catch(LockedAccountException le){tokens.clear();renderFailedResult("账号被锁定!");} catch (RuntimeException re) {re.printStackTrace();tokens.clear();renderFailedResult("登录失败!");}}数据库可以自己去设计,这里就不提供了。参照上面的去整合框架,便可以使用了,这样搭建适合多种框架的整合。

spring mvc整合shiro无法访问控制器是什么问题

  1.概述  现在的项目使用的权限控制系统是spring security 3.因为项目的框架使用spring,就顺便使用了。最近研究了一下spring side4,推荐使用shiro。照着示例做了一遍。在原有的spring web工程中。步骤如下。  2.引进包,maven设置   view plaincopy  org.apache.shiro  shiro-all  1.2.1  jar  compile  3.实现Controller层  主要是登陆url和几个掩饰url   view plaincopy  @Controller  public class AdminController {  @RequestMapping(value = "/admin/index", method = RequestMethod.GET)  public String index(Model model) {  return "admin/index";  }  @RequestMapping(value = "/admin/login", method = RequestMethod.GET)  public String login(Model model) {  logger.info("login get");  return "admin/login";  }  @RequestMapping(value = "/admin/login", method = RequestMethod.POST)  public String doLogin(Model model) {  logger.info("login post");  return "admin/login";  }  @RequiresRoles("user")  @RequestMapping(value = "/admin/user", method = RequestMethod.GET)  public String shiroUser(Model model) {  return "admin/index";  }  @RequiresRoles("admin")  @RequestMapping(value = "/admin/admin", method = RequestMethod.GET)  public String shiroAdmin(Model model) {  return "admin/index";  }  Logger logger = LoggerFactory.getLogger(AdminController.class);  }  4.实现权限验证  继承shiro的AuthorizingRealm   view plaincopy  public class ShiroDbRealm extends AuthorizingRealm {  protected AccountService accountService;  @Autowired  public void setAccountService(AccountService accountService) {  this.accountService = accountService;  }  /**  * 授权查询回调函数, 进行鉴权但缓存中无用户的授权信息时调用.  */  @SuppressWarnings("unused")  @Override  protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection p) {  logger.info("授权认证:" + p.getRealmNames());  ShiroUser shiroUser = (ShiroUser) p.getPrimaryPrincipal();  &nbsnbspUser user = accountService.findUserByLoginName(shiroUser.loginName);  SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();  for (Role role : user.getRoleList()) {  //基于Role的权限信息  info.addRole(role.getName());  //基于Permission的权限信息  info.addStringPermission(role.getPermissions());  }  return info;  }  /**  * 认证回调函数,登录时调用.  */  @Override  protected AuthenticationInfo doGetAuthenticationInfo(  AuthenticationToken authcToken) throws AuthenticationException {  logger.info("authc pass:");  UsernamePasswordToken token = (UsernamePasswordToken) authcToken;  logger.info("authc name:" + token.getUsername());  User user = accountService.findUserByLoginName(token.getUsername());  if (user != null) {  if (user.getStatus().equals("disabled")) {  throw new DisabledAccountException();  }  logger.info("authc name:" + token.getUsername() + " user:"  + user.getLoginName() + " pwd:" + user.getPassword()  + "getname:" + getName());  // byte salt = Encodes.decodeHex(user.getSalt());  return new SimpleAuthenticationInfo(new ShiroUser(user.getLoginName(), user.getName()),  user.getPassword(), getName());  }  return null;  }  /**  * 自定义Authentication对象,使得Subject除了携带用户的登录名外还可以携带更多信息.  */  public static class ShiroUser implements Serializable {  private static final long serialVersionUID = -1373760761780840081L;  public String loginName;  public String name;  public ShiroUser(String loginName, String name) {  this.loginName = loginName;  this.name = name;  }  public String getName() {  return loginName;  }  /**  * 本函数输出将作为默认的输出.  */  @Override  public String toString() {  return loginName;  }  /**  * 重载hashCode,只计算loginName;  */  @Override  public int hashCode() {  return Objects.hashCode(loginName);  }  /**  * 重载equals,只计算loginName;  */  @Override  public boolean equals(Object obj) {  if (this == obj)  return true;  if (obj == null)  return false;  if (getClass() != obj.getClass())  return false;  ShiroUser other = (ShiroUser) obj;  if (loginName == null) {  if (other.loginName != null)  return false;  } else if (!loginName.equals(other.loginName))  return false;  return true;  }  }  Logger logger = LoggerFactory.getLogger(ShiroDbRealm.class);  }  自定义的类ShiroUser是为了,可以多传输一些内容,供后面验证时使用,例子中只用了一个loginName,一般可以用String 传输就够了。  登陆时用doGetAuthenticationInfo()函数获得相关信息。  登陆后访问url 使用doGetAuthorizationInfo()获得用户的权限。  5.配置文件shiro部分  将controller的url纳入权限验证范围。   view plaincopy***隐藏网址******隐藏网址******隐藏网址******隐藏网址***  default-lazy-init="true"》  Shiro安全配置  /admin/login = authc  /admin/logout = logout  /static/** = anon  /admin/** = authc  主要内容是shiroFilter的定义。  loginUrl:登陆页面,用户登陆不成功,自动返回此页面。  successUrl:登陆成功后跳转此页面  unauthorizedUrl:用户访问无权限的链接时跳转此页面  filterChainDefinitions:设置url的访问权限。anon表示不用验证,都可以访问。anthc:authc filter 监听,不登陆不能访问。logout:logout filter监听。没有列出的常用配置:perms :需要角色romote 和权限invoke才能访问。roles需要角色admin才能访问。设置可用“,”隔开,如:  /admin/test = authc,roles  关于filter的列表:  Filter NameClass  anonorg.apache.shiro.web.filter.authc.AnonymousFilter  authcorg.apache.shiro.web.filter.authc.FormAuthenticationFilter  authcBasicorg.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter  permsorg.apache.shiro.web.filter.authz.PermissionsAuthorizationFilter  portorg.apache.shiro.web.filter.authz.PortFilter  restorg.apache.shiro.web.filter.authz.HttpMethodPermissionFilter  rolesorg.apache.shiro.web.filter.authz.RolesAuthorizationFilter  sslorg.apache.shiro.web.filter.authz.SslFilter  userorg.apache.shiro.web.filter.authc.UserFilter

shiro 如何配置到tomcat应用上

1 、 首先 创建一个项目名(mail)的文件夹, 在项目文件夹下创建一个存放JS脚本的文件夹,创建一个存放images(图片)的文件夹,创建一个存放CSS样式的文件夹等。 2、 然后在项目文件夹下创建一个WEB-INF的目录文件,JAVA类、jar包、WEB应用的配置文件都存在这个目录下。WEB-INF目录下存放了一些文件,有classes目录(编译好的类库)、lib目录, 每一个WEB应用程序的访问都需要一个配置文件,基于WEB.xml文件,所以在WEB-INF 文件目录下应该创建一个WEB.xml文件。 3、 在所创建的项目mail文件夹下创建一个HTML文件,名为index.html。在HTML文件中一些内容。 4、 在tomcat目录文件夹下的conf文件的Catalina\Localhost文件夹下新建一个名为mail.xml的项目文件,在这个文件中代码,写一个Context的配置的路径 如: 《?xml version=’1.0’ encoding=’utf-8’?》 《Context docBase=”C:\mail”/》 5、 最后重新启动Comcat就可以了。

shiro框架 配置文件log4j.properties shiro在哪

log4j.properties和shiro没关系哦。

推荐一套完整的Shiro Demo,免费的。

***隐藏网址******隐藏网址***

管理员帐号:admin,密码:sojson.com 如果密码错误,请用sojson。PS:你可以注册自己的帐号,然后用管理员赋权限给你自己的帐号,但是,每20分钟会把数据初始化一次。建议自己下载源码,让Demo跑起来,然后跑的更快。

spring中如何配置shiro和quartz的问题

楼主我给你发下我配置的qurzte吧 《!-- 要调用的工作类 --》《bean id="quartzJob" class="com.ush.dao.AutoUpdate"》 《property name="udao" ref="ushDao"》《/property》《/bean》《!-- 定义调用对象和调用对象的方法 --》《bean id="jobtask"class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean"》《!-- 调用的类 --》《property name="targetObject"》《ref bean="quartzJob" /》《/property》《!-- 调用类中的方法 --》《property name="targetMethod"》《value》AutoUpdateByTime《/value》《/property》《/bean》《!-- 定义触发时间 --》《bean id="doTime"class="org.springframework.scheduling.quartz.CronTriggerBean"》《property name="jobDetail"》《ref bean="jobtask" /》《/property》《!-- cron表达式 --》《property name="cronExpression"》《value》0 0 */1 * * ?《/value》《/property》《/bean》《!-- 总管理类如果将lazy-init=’false’那么容器启动就会执行调度程序 --》《bean id="startQuertz" lazy-init="false"class="org.springframework.scheduling.quartz.SchedulerFactoryBean"》《property name="triggers"》《list》《ref bean="doTime" /》《/list》《/property》《/bean》

如果你还想了解更多这方面的信息,记得收藏关注本站。