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

本文地址: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

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/455544.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Web安全之Cookie劫持

1.Cookie是什么? 2.窃取的原理是什么? 3.系统如何防Cookie劫持呢? 看完这三个回答&#xff0c;你就明白哪位传奇大侠是如何成功的!!! Cookie: HTTP天然是无状态的协议&#xff0c;为了维持和跟踪用户的状态&#xff0c;引入了Cookie和Session。Cookie包含了浏览器客户端的用…

python中关于深拷贝和浅拷贝的详解

python中关于深拷贝和浅拷贝的详解 概述 在python的语法中,有两种变量的拷贝方式 一种是深拷贝,一种是浅拷贝 我们先说深拷贝 语法 这里需要通过导入系统的copy模块中的deepcopy才可以 import copy 新的对象 copy.deepcopy(被拷贝对象) 解释 深拷贝是将操作对象整体复制…

运动估计简介

运动估计( Motion Estimation) 维基百科链接&#xff1a;http://en.wikipedia.org/wiki/Motion_estimation运动估计的应用有很多&#xff0c;最初的应用的领域是视频的编码。运动估计算法一般分为: 像素递归法pel-recursive algorithm (PRA)和块匹配法 block-matching algorith…

tutte定理证明hall定理_深入浅出|中心极限定理(Central Limit Theorem)及证明

在介绍统计学中最重要的定理之一-中心极限定理-之前&#xff0c;我们先来想一个问题&#xff1a;统计学的目的是什么&#xff1f;根据<Mathematical statistics with application 7th Edition>书中所写的&#xff1a;统计学的目的是基于从总体中的样本所获得的信息&#…

让数据中心变得更加友好

通常来说&#xff0c;数据中心是一个安全防护十分严密的地方&#xff0c;其安全功能的设计旨在阻止不速之客的访问。但专家认为数据中心可以变得更加友好&#xff0c;因为数据中心需要在人类社会中发挥更大的作用。 数据中心的整体概念是一种可以通过云计算或其他方法进行远程访…

traceroute/tracert--获取网络路由路径

traceroute 是用来检测发出数据包的主机到目标主机之间所经过的网关数量的工具。traceroute 的原理是试图以最小的TTL发出探测包来跟踪数据包到达目标主机所经过的网关&#xff0c;然后监听一个来自网关ICMP的应答。发送数据包的大小默认为 38个字节。 通过traceroute我们可以知…

使用Cygwin实现vlc 1.0.5的wince移植

本文完全参照了天将降的博客文章&#xff0c;写于此以作来日备忘之用&#xff0c;原文地址&#xff1a;http://bk6.blog.163.com/blog/static/24498560201051193449196/ 第一步&#xff1a;下载安装Cygwin。笔者建议大家不要安装不完整的版本&#xff0c;以免出现不必要的错误…

andriod studio 运行 无结果_华为物联网操作系统LiteOS内核教程01——IoT-Studio介绍及安装...

1. 物联网一站式开发工具 —— IoT StudioIoT Studio 是支持 LiteOS 嵌入式系统软件开发的工具&#xff0c;提供了代码编辑、编译、烧录 及调试等一站式开发体验&#xff0c;支持 C、C、汇编等多种开发语言&#xff0c;让您快速&#xff0c;高效地进 行物联网开发。2. IoT Stud…

5G通信技术能否终结商用WiFi?

科技创新与体育发展可谓相生相伴&#xff0c;而如今科技在体育领域的应用也越来越广泛。本周的话题关于5G技术与球场&#xff0c;作者为英国体育娱乐营销咨询公司Stadia Solutions的联席首席执行官戈登坎贝尔。在坎贝尔先生看来&#xff0c;球场Wi-Fi赋予了俱乐部对数据的掌控力…

颜色转换

以蓝色为例&#xff0c;#0000FF应该被表示成rgb(0,0,255)。 我们将函数命名为getRGB() &#xff08;可以将字符串视为数组&#xff0c;这个数组的元素为字符&#xff09; function getRGB(color) {var rgb [parseInt(0xcolor.slice(1,3)),parseInt(0xcolor.slice(3,5)),parseI…

wince ./configure

CPPFLAGS"-I/usr/wince/include -D_WIN32_WCE0x0500" LDFLAGS"-L/usr/wince/lib" ./configure--hostarm-mingw32ce 指定软件运行的系统平台&#xff1b;host就是你编译好的程序可以运行的平台--target-osmingw32ce 指定软件面向(target to)的系统平台.这主…

android 按键会触发ontouch吗?_Android实现炫酷的拖拽浮动按钮

IOS的Assistive Touch效果很炫酷&#xff0c;可以任意拖拽&#xff0c;同时点击后会展开菜单栏。然而&#xff0c;这不只是IOS的特权&#xff0c;Android也可以实现。但是由于悬浮窗需要申请权限&#xff0c;所以本文仅在app内实现&#xff0c;可以任意拖拽&#xff0c;并可以响…

强名称程序集(strong name assembly)——为程序集赋予强名称

引言&#xff1a;在曾经的项目开发中&#xff0c;在程序集中见到过一个后缀为*.snk的文件。当时看这个文件的图标。感觉可能是企业内部保护版权啥的一种方式。一&#xff0c;强程序集攻克了哪些问题&#xff1f;1&#xff0c;唯一标识一个程序集2&#xff0c;放置程序集被仿冒和…

如何成为一名合格的数据分析师

“21世纪什么最贵&#xff0c;人才”&#xff0c;在目前大数据时代下&#xff0c;什么最难找&#xff0c;什么最贵&#xff0c;实现数据价值的人&#xff0c;数据分析师。 但是对于数据分析师的认识&#xff0c;比较极端&#xff0c;但对数据分析师价值的认识正在回归理性。很多…

【ffmpeg for wince】音视频编解码多平台移植(for window/wince))ffmpeg

from: http://www.cnblogs.com/windwithlife/archive/2009/05/31/1492728.html 终于完成了了第二个Client side原型&#xff08;for Wince)&#xff0c;其中花掉我最多时间的就是ffmpeg的对WINCE的移植。其中有大半时间是由于网上的一些不完整及不正确信息所误导&#xff0c;但…

Java 重写(Override)与重载(Overload)

重写(Override) 重写是子类对父类的允许访问的方法的实现过程进行重新编写&#xff01;返回值和形参都不能改变。即外壳不变&#xff0c;核心重写&#xff01; 重写的好处在于子类可以根据需要&#xff0c;定义特定于自己的行为。也就是说子类能够根据需要实现父类的方法。在面…

银联pos小票word模板_商家pos机刷卡必须知道的知识

相信很多卡友伙伴或者商铺店家都装有pos机&#xff0c;然后一般pos机都没有使用说明书&#xff0c;更没有结合刷卡方法在内的秘籍。今天我就分享下刷卡必须知道的一些知识。刚刚办理pos机的当天一定要注意&#xff1a;使用之前呢&#xff0c;务必核对一下基本信息&#xff0c;例…

《Ext JS权威指南》——2.4节关于Ext.onReady

2.4 关于Ext.onReady 代码为什么写在Ext.onReady中&#xff0c;而不是在body中添加一个onload事件并在onload事件中运行呢&#xff1f;主要原因是Ext.onReady在DOM模型加载完毕后即可进行操作&#xff0c;而无需像onload事件那样&#xff0c;等待页面的所有资源都加载完毕后才…

git push 提交时显示 Empty reply from server的解决办法

输入 git fetch origin --prune 参考链接&#xff1a;https://stackoverflow.com/questions/28364023/gits-error-on-push-empty-reply-from-server 转载于:https://www.cnblogs.com/team42/p/6941678.html

转]移动视频监控(1)---项目综述

对于市场上的视频监控系统&#xff0c;大家都有一定的了解&#xff0c;就是视频采集&#xff0c;经过无线/有线发送到服务或代理&#xff0c;客户从服务或代理上得到视频/音频流。不复杂。 对于不远的将来&#xff0c;3G&#xff0c;4G的到来&#xff0c;对移动的业务有一个推动…