本文地址:http://blog.csdn.net/sushengmiyan/article/details/39933993

shiro官网: http://shiro.apache.org/

shiro中文手冊:http://wenku.baidu.com/link?url=ZnnwOHFP20LTyX5ILKpd_P94hICe9Ga154KLj_3cCDXpJWhw5Evxt7sfr0B5QSZYXOKqG_FtHeD-RwQvI5ozyTBrMAalhH8nfxNzyoOW21K

本文作者:sushengmiyan

------------------------------------------------------------------------------------------------------------------------------------

一。新建java webproject 这里取名为shirodemo

二。加入依赖的jar包。例如以下:

三。加入web对shiro的支持

如第一篇文章所述,在此基础上添加webs.xml部署描写叙述:

  <listener><listener-class>org.apache.shiro.web.env.EnvironmentLoaderListener</listener-class></listener><filter><filter-name>shiro</filter-name><filter-class>org.apache.shiro.web.servlet.ShiroFilter</filter-class></filter><filter-mapping><filter-name>shiro</filter-name><url-pattern>/*</url-pattern></filter-mapping>

四。加入jsp页面登陆button以及标签支持:

<%String user = request.getParameter("username");String pwd = request.getParameter("password");
if(user != null && pwd != null){Subject sub = SecurityUtils.getSubject();String context = request.getContextPath();try{sub.login(new UsernamePasswordToken(user.toUpperCase(),pwd));out.println("登录成功");}catch(IncorrectCredentialsException e){out.println("{success:false,msg:'username和password不对!'}");}catch(UnknownAccountException e){out.println("{success:false,msg:'用户名不存在。'}");}return;
}
%>

在jsp页面中添加username与password登陆框。

五。新建realm实现

package com.susheng.shiro;import javax.annotation.PostConstruct;import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.cache.CacheManager;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;//认证数据库存储
public class ShiroRealm extends AuthorizingRealm {public Logger logger = LoggerFactory.getLogger(getClass());final static String AUTHCACHENAME = "AUTHCACHENAME";public static final String HASH_ALGORITHM = "MD5";public static final int HASH_INTERATIONS = 1;public ShiroDbRealm() {// 认证super.setAuthenticationCachingEnabled(false);// 授权super.setAuthorizationCacheName(AUTHCACHENAME);}// 授权@Overrideprotected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {if (!SecurityUtils.getSubject().isAuthenticated()) {doClearCache(principalCollection);SecurityUtils.getSubject().logout();return null;}// 加入角色及权限信息SimpleAuthorizationInfo sazi = new SimpleAuthorizationInfo();return sazi;}// 认证@Overrideprotected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {UsernamePasswordToken upToken = (UsernamePasswordToken) token;String userName = upToken.getUsername();String passWord = new String(upToken.getPassword());AuthenticationInfo authinfo = new SimpleAuthenticationInfo(userName, passWord, getName());return authinfo;}/*** 设定Password校验的Hash算法与迭代次数.*/@PostConstructpublic void initCredentialsMatcher() {HashedCredentialsMatcher matcher = new HashedCredentialsMatcher(HASH_ALGORITHM);matcher.setHashIterations(HASH_INTERATIONS);setCredentialsMatcher(matcher);}
}

六。shiro.ini文件内容添加对realm的支持。

#
# 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.
#
# =============================================================================
# Quickstart INI Realm configuration
#
# For those that might not understand the references in this file, the
# definitions are all based on the classic Mel Brooks' film "Spaceballs". ;)
# =============================================================================# -----------------------------------------------------------------------------
# Users and their assigned roles
#
# Each line conforms to the format defined in the
# org.apache.shiro.realm.text.TextConfigurationRealm#setUserDefinitions JavaDoc
# -----------------------------------------------------------------------------#realm
myRealm = com.susheng.shiro.ShiroDbRealm
securityManager.realm = $myRealm[users]
# user 'root' with password 'secret' and the 'admin' role
root = secret, admin
# user 'guest' with the password 'guest' and the 'guest' role
guest = guest, guest
# user 'presidentskroob' with password '12345' ("That's the same combination on
# my luggage!!!" ;)), and role 'president'
presidentskroob = 12345, president
# user 'darkhelmet' with password 'ludicrousspeed' and roles 'darklord' and 'schwartz'
darkhelmet = ludicrousspeed, darklord, schwartz
# user 'lonestarr' with password 'vespa' and roles 'goodguy' and 'schwartz'
lonestarr = vespa, goodguy, schwartz# -----------------------------------------------------------------------------
# Roles with assigned permissions
#
# Each line conforms to the format defined in the
# org.apache.shiro.realm.text.TextConfigurationRealm#setRoleDefinitions JavaDoc
# -----------------------------------------------------------------------------
[roles]
# 'admin' role has all permissions, indicated by the wildcard '*'
admin = *
# The 'schwartz' role can do anything (*) with any lightsaber:
schwartz = lightsaber:*
# The 'goodguy' role is allowed to 'drive' (action) the winnebago (type) with
# license plate 'eagle5' (instance specific id)
goodguy = winnebago:drive:eagle5[urls]
/login.jsp = anon
/index.html = user
/index.jsp = user
/homePageDebug.jsp = user
/module/** = user

七。tomcat添加对这个应用的部署。启动tomcat,输入相应的url。

查看实现效果:

登录界面的显示

点击登录之后,插入了shiro的实现。

临时没有进行实质认证。仅仅是大概搭建的shiro环境。

自己插入自己的realm实现就能够了。

OK。如今。以及实现了对web的支持。

代码下载地址:http://download.csdn.net/detail/sushengmiyan/8022503

转载于:https://www.cnblogs.com/yfceshi/p/6934510.html

[shiro学习笔记]第二节 shiro与web融合实现一个简单的授权认证相关推荐

  1. Shiro学习笔记_02:shiro的认证+shiro的授权

    Shiro 学习笔记 本文基于B站UP主[编程不良人]视频教程[2020最新版Shiro教程,整合SpringBoot项目实战教程]进行整理记录,仅用于个人学习交流使用. 视频链接:https://w ...

  2. 文件用户Apache shiro学习笔记+ spring整合shiro (一)

    改章节朋友在青岛游玩的时候突然想到的...这两天就有想写几篇关于文件用户的博客,所以回家到之后就奋笔疾书的写出来发表了 Apache Shiro官网:http://shiro.apache.org/ ...

  3. Core Animation学习笔记—第二节Setting up Layer Objects

    各位iOS开发大佬们好: 我是一名Swift+SwiftUI栈的iOS小白,目前还在上大三,最近准备实习,面试的过程中发现现在大公司很多还在用OC + UIKit的技术栈,OC我还在考虑要不要学,目前 ...

  4. python基础课程学习笔记-第二节课

    1.Python语⾔ 1.1 Python语⾔的基本概念 Python 是⼀种极少数能兼具 简单 与 功能强⼤ 的编程语⾔.你将惊异于发 现你正在使⽤的这⻔编程语⾔是如此简单,它专注于如何解决问题,⽽ ...

  5. Tensorflow学习笔记-第二节程序结构

    目录 TensorFlow程序分为两个独立的部分: 计算图: 计算图的执行: 简单实例--向量相加 程序模版 结果 分析: with语法: InteractiveSession 和 Session的区 ...

  6. 贝加莱学习笔记第二节

    1.点击 setting---online-browser 可以搜索 plc 的地址 2.在 PLC 上有 PLC 的节点号,上面的那个是 16 的 1 次方,下面的是 16 的 0 次方. 3.cm ...

  7. CCSA学习笔记 第二节 搭建实验环境

    搭建CCSA实验环境 一.个人电脑的要求 1.CPU支持虚拟化 2.win10注意关闭更新 3.内存大于等于16G 二.关于EVE的资源分配 1.内存大于等于8G 2.CPU分配2个,必须激活虚拟化( ...

  8. 学习笔记第二节:最大权闭合图

    关于 这个算法是在接触太空飞行计划问题时接触到的.为了解决这道问题,我在网上查阅了相当多的资料,在这里整理给大家.题目点击打开链接https://www.luogu.org/problemnew/sh ...

  9. Shiro学习笔记(三)源码解析

    Shiro作为轻量级的权限框架,Shiro的认证流程是怎样的一个过程. 如果没有对Shiro进行了解的话,建议先对Shiro学习笔记(一)学习一下Shiro基本的组 成. 1,几大重要组件解析 1.1 ...

最新文章

  1. 动态获取的图片当做背景,而且图片是小图
  2. bzoj 3329: Xorequ
  3. java transient 和Volatile关键字
  4. 数据切分——Atlas读写分离Mysql集群的搭建
  5. kubernetes1.8.4安装指南 -- 2. ssh免密登录
  6. 魅族发布会邀请函来了!“无字天书”的秘密明晚揭晓
  7. idea中未被识别的maven项目,如何手动添加
  8. 物联网项目设计 (七) 基于RT-thread的MQTT协议物联网辉光钟
  9. 华为er路由器设置虚拟服务器,华为AR111-S路由器双线路策略路由配置笔记
  10. 交通运输学计算机吗,交通运输专业所属学科门类是什么
  11. 团队项目:即时聊天软件 需求分析、用例、UI原型
  12. 固态硬盘是什么接口_小白指南:固态硬盘接口傻傻分不清,新手用户应该如何选?...
  13. 多因子模型 —— 因子正交化处理
  14. 点击链接重定向跳转微信公众号关注页、微信关注链接
  15. RK方案OTG口 OTG与HOST切换
  16. windows10下安装MSYS2+MinGW64
  17. c语言格式字符-5d,-是什么意思在c语言中%5d是什么意思? 爱问知识人
  18. 1997年苹果公司《think different》广告台词中英文版本
  19. 国内AI众包竞赛加速发展,云计算成助推器
  20. java将实体数据导出到excel,压缩,删除等一系列~

热门文章

  1. 【PTA天梯赛CCCC -2017决赛L2-3】图着色问题 (25 分)(图染色)
  2. 【牛客 - 272D】Where are you(Tarjan求桥)
  3. pc服务器不同型号,服务器与PC系统软件之不同
  4. layui数据表格获取当前页数
  5. 计算机技术员好学吗,电脑技术员,沦落到如此地步...
  6. php中节点值怎么获取,php – 节点更新:获取旧值
  7. FileIo 删除类中的private方法
  8. c55x汇编语言,TMS320C55x汇编语言编程A.ppt
  9. 四川省中职计算机考试题,四川省计算机等级考试模拟试题(一级)
  10. mysql版本不支持 loop,loopback4, node mysql connector支持 utf8mb4字符集