分享在SSM框架中用第三方登录分享怎么绕过shiro

shiro 瞅完就会用(ssm+shiro) - 简书
shiro 瞅完就会用(ssm+shiro)
一 shiro 是什么
shiro 是一个功能强大和易于使用的Java安全框架,为开发人员提供一个直观而全面的解决方案的认证,授权,加密,会话管理。
二 shiro 能干什么
shiro 四个主要的功能
Authentication:身份认证/登录,验证用户是不是拥有相应的身份;
Authorization:授权,即权限验证,判断某个已经认证过的用户是否拥有某些权限访问某些资源,一般授权会有角色授权和权限授权;
SessionManager:会话管理,即用户登录后就是一次会话,在没有退出之前,它的所有信息都在会话中;会话可以是普通JavaSE环境的,也可以是如Web环境的,web 环境中作用是和 HttpSession 是一样的;
Cryptography:加密,保护数据的安全性,如密码加密存储到数据库,而不是明文存储;
shiro 的其它几个特点
Web Support:Web支持,可以非常容易的集成到Web环境;
Caching:缓存,比如用户登录后,其用户信息、拥有的角色/权限不必每次去查,这样可以提高效率;
Concurrency:shiro支持多线程应用的并发验证,即如在一个线程中开启另一个线程,能把权限自动传播过去;
Testing:提供测试支持;
Run As:允许一个用户假装为另一个用户(如果他们允许)的身份进行访问;
Remember Me:记住我,这个是非常常见的功能,即一次登录后,下次再来的话不用登录了。
三 shiro 架构
从图中我们可以看到不管是任何请求都会经过 SecurityManager 拦截并进行相应的处理,shiro 几乎所有的功能都是由 SecurityManager 来管理。
Subject:主体,相当与是请求过来的"用户"
SecurityManager: 是 Shiro 的心脏;所有具体的交互都通过 SecurityManager 进行拦截并控制;它管理着所有 Subject、且负责进行认证和授权、及会话、缓存的管理
Authenticator:认证器,负责主体认证的,即确定用户是否登录成功,我们可以使用  Shiro 提供的方法来认证,有可以自定义去实现,自己判断什么时候算是用户登录成功
Authrizer:授权器,即权限授权,给 Subject 分配权限,以此很好的控制用户可访问的资源
Realm:一般我们都需要去实现自己的 Realm
,可以有1个或多个 Realm,即当我们进行登录认证时所获取的安全数据来源(帐号/密码)
SessionManager:为了可以在不同的环境下使用 session 功能,shiro 实现了自己的 sessionManager ,可以用在非 web 环境下和分布式环境下使用
SessionDAO:对 session 的 CURD 操作
CacheManager:缓存控制器,来管理如用户、角色、权限等的缓存的;
Cryptography:密码模块,Shiro提高了一些常见的加密组件用于如密码加密/解密的。
四 shiro 的主要功能 - 身份认证
1 Subject 认证
身份认证就是在应用中谁能证明他就是他本人,一般会使用用户名和密码作为认证信息。
2 Subject 认证主体
Subject 认证主体包含两个信息:
Principals:身份,即用户名
Credentials:凭证,即密码
** 3 认证流程**
用户发送请求进行 Subject 认证(调用 subject.login(token))
SecurityManager 会去 Authenticator(认证器)中查找相应的 Realms(可能不止一个)源
Realms 可以根据不同类型的 Realm 中去查找用户信息,并进行判断是否认证成功
4 快速搭建 helloWorld
&dependencies&
&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&
&/dependencies&
创建 Realm /resources/shiro.ini
acey=123456
进行身份验证
public class HelloWorld {
public static void main(String[] args) {
加载配置文件,初始化 SecurityManager 工厂
Factory&SecurityManager& factory = new IniSecurityManagerFactory
("classpath:shiro.shiro.ini");
获取 SecurityManager 实例
SecurityManager securityManager = factory.getInstance();
把 SecurityManager 绑定到 SecurityUtils 中
SecurityUtils.setSecurityManager(securityManager);
得到当前执行的用户
Subject currentUser = SecurityUtils.getSubject();
创建 token 令牌,用户名/密码
UsernamePasswordToken token = new UsernamePasswordToken("acey", "123456");
currentUser.login(token);
System.out.println("登录成功");
} catch (Exception e) {
e.printStackTrace();
System.out.println("登录失败");
四 shiro 的主要功能 - 授权
权限授权就是访问控制,在应用中控制谁能访问哪些资源
1 权限认证中的几个元素
权限:即操作某个资源的权限,这些资源可以是某个链接,也可以是某个图片,也可以是对某个模块的数据的 CURL
角色:即权限的集合,一个角色可以有多个权限
用户:代表访问的用户,即  Subject
2 授权的流程
当用户访问应用中的某个资源时,会被 SecurityManager 拦截.
SecurityManager 会去调用 Authorizer(授权器)
Authorizer 会根据 Subject 的身份去相应的 Realm 中去查找该 Subject 是否有权限去访问该资源
3 授权实现
配置 permission(权限) resources/shiro_permission.ini
authc.loginUrl=/login
//表示用户登录失败跳转到 /login
roles.unauthorrizedUrl=/unauthorrized.jsp //表示用户没有对应的访问角色跳转到/unauthorrized.jsp
perms.unauthorrizedUrl=/unauthorrized.jsp
//表示用户没有对应的访问权限跳转到/unauthorrized.jsp
acey=123456,role1,role2
jack=123,role1
role1=user:select // role1 角色有访问 user:select 的权限
role2=user:add,/delete //role2 角色有访问 user:add 和 /delete 的权限
/login=anon
//表示任何用户都可以访问 /login
/index=authc //表示只有身份认证通过的用户才可以访问 /index
/index=roles[role1,role2...] //表示只有用户含有 role1 role2 ... 角色才可以访问 /index
/index=perms["user:create","/update"]
//表示只有用户含有 "user:create"
和"/update"权限才可以访问 /index
/index?=authc //`?`通配符,表示一个字符,如/index1 /indexa /index- (不能匹配/index) ,
将符合这种规则的请求进行`authc`拦截
/index*=authc
`*`通配符,表示零个或一个或多个字符,如/index1213asd /index /index2 ,
将符合这种规则的请求进行`authc`拦截
/index/**=authc
`**`表示匹配零个或一个或多个路径,如/index/create /index/create/update/...
将符合这种规则的请求进行`authc`拦截
/index*/**authc
可以匹配 /index12/create/update/...
3)配置 roles (角色) resources/shiro_role.ini
acey=123456,role1,role2 //表示有一个用户,用户名是acey,密码为123456,有role1和role2角色
jack=123,role1
验证用户角色是否足够
public class RoleTest {
使用 checkRole 来检验角色时,若权限不足会返回 false
public void testHasRole() {
Subject currentUser= ShiroUtil.login("classpath:shiro_role.ini", "acey", "123456");
// Subject currentUser=ShiroUtil.login("classpath:shiro_role.ini", "jack", "123");
System.out.println(currentUser.hasRole("role1")?"has role1":"has not role1");
currentUser.logout();
使用 checkRole 来检验角色时,若权限不足会抛出异常
public void testCheckRole() {
Subject currentUser=ShiroUtil.login("classpath:shiro_role.ini", "acey", "123456");
// Subject currentUser=ShiroUtil.login("classpath:shiro_role.ini", "jack", "123");
currentUser.checkRole("role1");
currentUser.logout();
验证用户权限是否足够
public class PermissionTest {
使用 checkPermission 来检验权限时,若权限不足会返回 false
public void testIsPermitted() {
Subject currentUser= ShiroUtil.login("classpath:shiro_permission.ini", "acey", "123456");
System.out.println(currentUser.isPermitted("user:select")?"has user:select":"hsa not user:select");
currentUser.logout();
使用 checkPermission 来检验权限时,若权限不足会抛出异常
public void testCheckPermitted() {
Subject currentUser=ShiroUtil.login("classpath:shiro_permission.ini", "acey", "123456");
// Subject currentUser=ShiroUtil.login("classpath:shiro_permission.ini", "jack", "123");
currentUser.checkPermission("user:select");
currentUser.logout();
五 ssm 和 shiro 整合
2)配置 web.xml(shiro过滤器)
&!-- shiro过滤器定义 --&
&filter-name&shiroFilter&/filter-name&
&filter-class&org.springframework.web.filter.DelegatingFilterProxy&/filter-class&
&init-param&
&!-- 该值缺省为false,表示生命周期由SpringApplicationContext管理,设置为true则表示由ServletContainer管理 --&
&param-name&targetFilterLifecycle&/param-name&
&param-value&true&/param-value&
&/init-param&
&filter-mapping&
&filter-name&shiroFilter&/filter-name&
&url-pattern&/*&/url-pattern&
&/filter-mapping&
3)编写自己的 Realm(一般权限都是从数据库中查找,所以需要自定义)
public class MyRealm extends AuthorizingRealm{
private UserService userS
* 为当前登录的用户授予角色和权限
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
//获取用户名
String userName=(String)principals.getPrimaryPrincipal();
SimpleAuthorizationInfo authorizationInfo=new SimpleAuthorizationInfo();
//进行授权角色
authorizationInfo.setRoles(userService.getRoles(userName));
//进行授权权限
authorizationInfo.setStringPermissions(userService.getPermissions(userName));
return authorizationI
*验证当前登录的用户
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
String userName=(String)token.getPrincipal();
//根据用户名查找用户信息
User user=userService.getByUserName(userName);
if(user!=null){
AuthenticationInfo authcInfo=new SimpleAuthenticationInfo(user.getUserName(),user.getPassword(),getName());
return authcI
spring 和 shiro 配置整合
&!-- 自定义Realm --&
&bean id="myRealm" class="com.acey.realm.MyRealm"/&
&!-- 安全管理器 --&
&bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager"&
&property name="realm" ref="myRealm"/&
&!-- Shiro过滤器 --&
&bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean"&
&!-- Shiro的核心安全接口,这个属性是必须的 --&
&property name="securityManager" ref="securityManager"/&
&!-- 身份认证失败,则跳转到登录页面的配置 --&
&property name="loginUrl" value="/index.jsp"/&
&!-- 权限认证失败,则跳转到指定页面 --&
&property name="unauthorizedUrl" value="/unauthor.jsp"/&
&!-- Shiro连接约束配置,即过滤链的定义 --&
&property name="filterChainDefinitions"&
/login=anon
/admin*=authc
/student=roles[teacher]
/teacher=perms["user:create"]
&/property&
&!-- 保证实现了Shiro内部lifecycle函数的bean执行 --&
&bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/&
&!-- 开启Shiro注解 --&
&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"/&
一般角色和权限都存在数据库中,所以我们还可以自定义一个 filter 去自己验证每一个请求的 Subject 是否有权限去访问,这样我们就可以减少对过滤链的维护.比如
&!-- Shiro过滤器 --&
&bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean"&
&!-- Shiro的核心安全接口,这个属性是必须的 --&
&property name="securityManager" ref="securityManager"/&
&!-- 身份认证失败,则跳转到登录页面的配置 --&
&property name="loginUrl" value="/index.jsp"/&
&!-- 权限认证失败,则跳转到指定页面 --&
&property name="unauthorizedUrl" value="/unauthor.jsp"/&
&!-- Shiro连接约束配置,即过滤链的定义 --&
&property name="filterChainDefinitions"&
/login=anon
/admin*=authc
/student=roles[teacher]
/teacher=perms["user:create"]
&/property&
&!-- Shiro过滤器 --&
&bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean"&
&!-- Shiro的核心安全接口,这个属性是必须的 --&
&property name="securityManager" ref="securityManager"/&
&!-- 身份认证失败,则跳转到登录页面的配置 --&
&property name="loginUrl" value="/index.jsp"/&
&!-- 权限认证失败,则跳转到指定页面 --&
&property name="unauthorizedUrl" value="/unauthor.jsp"/&
&property name="ownFilter" class="ownFilter.class"&
&!-- Shiro连接约束配置,即过滤链的定义 --&
&property name="filterChainDefinitions"&
/login=anon
/**=ownFilter
&/property&
欢迎大家拍砖
终身学习实践者
前言 Spring boot 是什么,网上的很多介绍,这里博客就不多介绍了。如果不明白Spring boot是什么。推荐几篇文章,你可以了解下。 Spring boot官网 初识Spring Boot框架相似题材文章太多了,这里就不列举多了。还有一点就是篇幅有点长,请结合例...
构建一个互联网应用,权限校验管理是很重要的安全措施,这其中主要包含: 认证 - 用户身份识别,即登录 授权 - 访问控制 密码加密 - 加密敏感数据防止被偷窥 会话管理 - 与用户相关的时间敏感的状态信息 Shiro对以上功能都进行了很好的支持,而且十分易于使用,且可运行在...
一:基础概念 什么是权限管理 权限管理包括用户身份认证和授权两部分,简称认证授权。对于需要访问控制的资源用户首先经过身份认证,认证通过后用户具有该资源的访问权限方可访问。 用户身份认证 就是判断一个用户是否为合法用户的处理过程。最简单的身份认证方式是系统通过核对用户输入的用...
Shiro(代码) 1.1 简介 Apache Shiro是Java的一个安全框架。目前,使用Apache Shiro的人越来越多,因为它相当简单,对比Spring Security,可能没有Spring Security做的功能强大,但是在实际工作时可能并不需要那么复杂的...
1.简介 Apache Shiro是Java的一个安全框架。功能强大,使用简单的Java安全框架,它为开发人员提供一个直观而全面的认证,授权,加密及会话管理的解决方案。 实际上,Shiro的主要功能是管理应用程序中与安全相关的全部,同时尽可能支持多种实现方法。Shiro是建...
孙维法,字子清(曾用子美),1964年9月出生,大学本科,中共党员,浙江诸暨市人。现任甘肃浙江企业联合会常务理事、兰州市民间组织联合会常务副会长、兰州工程机械行业协会会长兼党支部书记、兰州育园英语学校校长等职。 孙维法作品赏析 幼承家教随父如灿学习楷书,在大学就学与国营企业...
尽管妈妈更爱弟弟一些,可妈妈对我的那一点点爱是我在这个世上接受到的唯一的全部的爱,倘若我不要这点爱,那我就没有别人爱了。我缺爱,我分外稀罕这少的可怜的爱。大家都说,我是一个好女孩,会有人爱的,所以大家都不爱我。然而那个爱我的人也没有出现。这个世界本来就是不公平的。上天赋予了...
今天是日,我发现简书的第二天。现处于大一暑假,闲来无事刷微博时,看到了关注人推送的app。本身喜欢文字的我搜索了简书,看了第一眼便爱上了。我不是个爱写字的人但偏偏热爱除写字之外的其它与文字有关的一切,比如读文,比如摘抄…当看到小编推送的:你关注简书这么久,...
杂谈 每次上班必辗转2个公交,周而复始。一辆公交有空调干净感觉坐着很舒服,假如有时间就想从始发站做到终点站,另一辆公交破旧脏,唯一值得庆幸的是,沿路可以看到美景,赏心悦目,偶尔看司机心情再给来点音乐,畅然!今天就说说音乐 今天司机心情好放音乐了。 第一首歌 王力宏和seli...shiro登录认证出错
[问题点数:40分,结帖人Troyturk]
shiro登录认证出错
[问题点数:40分,结帖人Troyturk]
只显示楼主
取消只显示楼主
匿名用户不能发表回复!|  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-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-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"/&
      Spring配置文件中导入shiro配置文件:
&!-- 包含shiro的配置文件 --&
&import resource="classpath:applicationContext-shiro.xml"/&
      新建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.xsd"&
&!-- 配置緩存管理器 --&
&bean id="cacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager"&
&!-- 指定 ehcache 的配置文件,下面会给到 --&
&property name="cacheManagerConfigFile" value="classpath:ehcache-shiro.xml"/&
&!-- 配置进行授权和认证的 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 后置处理器: 会自动的调用和 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"&
&!-- 配置登出: 使用 logout 过滤器 --&
/shiro-logout = logout
/shiro-* = anon
/user.jsp = roles[user]
/admin.jsp = roles[admin]
/** = authc
&/property&
&    导入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
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.
&!-- EhCache XML configuration file used for Shiro spring sample application --&
&!-- Sets the path to the directory where cache .data files are created.
If the path is a Java System Property it is replaced by
its value in the running VM.
The following properties are translated:
user.home - User's home directory
user.dir - User's current working directory
java.io.tmpdir - Default temp file path --&
&diskStore path="java.io.tmpdir/shiro-spring-sample"/&
&!--Default Cache configuration. These will applied to caches programmatically created through
the CacheManager.
The following attributes are required:
maxElementsInMemory
- Sets the maximum number of objects that will be created in memory
- Sets whether elements are eternal. If eternal,
timeouts are ignored and the
element is never expired.
overflowToDisk
- Sets whether elements can overflow to disk when the in-memory cache
has 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 expires
Is 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 value
is 120 seconds.
memoryStoreEvictionPolicy
- Policy would be enforced upon reaching the maxElementsInMemory limit. Default
policy 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 session
expirations 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 after
even 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
import org.apache.shiro.authc.AuthenticationE
import org.apache.shiro.authc.AuthenticationI
import org.apache.shiro.authc.AuthenticationT
import org.apache.shiro.authc.SimpleAuthenticationI
import org.apache.shiro.authc.credential.HashedCredentialsM
import org.apache.shiro.authz.AuthorizationI
import org.apache.shiro.authz.SimpleAuthorizationI
import org.apache.shiro.crypto.hash.Md5H
import org.apache.shiro.crypto.hash.SimpleH
import org.apache.shiro.realm.AuthorizingR
import org.apache.shiro.subject.PrincipalC
import org.apache.shiro.util.ByteS
import org.springframework.beans.factory.annotation.A
import bean.
import dao.
public class MyRealm extends AuthorizingRealm {
@Autowired
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");
* 用户验证
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
//<span style="color: #. token 中获取登录的 username! 注意不需要获取password.
Object principal = token.getPrincipal();
//<span style="color: #. 利用 username 查询数据库得到用户的信息.
user user=userdao.findbyname((String) principal);
if(user!=null){
pass=user.getPass();
String credentials =
//<span style="color: #.设置盐值 ,(加密的调料,让加密出来的东西更具安全性,一般是通过数据库查询出来的。 简单的说,就是把密码根据特定的东西而进行动态加密,如果别人不知道你的盐值,就解不出你的密码)
String source = "abcdefg";
ByteSource credentialsSalt = new Md5Hash(source);
//当前 Realm 的name
String realmName = getName();
//返回值实例化
SimpleAuthenticationInfo info =
new SimpleAuthenticationInfo(principal, credentials,
credentialsSalt, realmName);
//init-method 配置.
public void setCredentialMatcher(){
HashedCredentialsMatcher
credentialsMatcher = new HashedCredentialsMatcher();
credentialsMatcher.setHashAlgorithmName("MD5");//MD5算法加密
credentialsMatcher.setHashIterations(1024);//<span style="color: #24次循环加密
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);
//执行认证操作.
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();
好了,shiro登录验证到这里完了,这个简单的实例也应该能让大家初步了解了
阅读(...) 评论()

我要回帖

更多关于 绕过shiro 第三方登录 的文章

 

随机推荐