[shiro学习笔记]第二节 shiro与web融合实现一个简单的授权认证
本文地址:http://blog.csdn.net/sushengmiyan/article/details/39933993
shiro官网:http://shiro.apache.org/
本文作者:sushengmiyan
------------------------------------------------------------------------------------------------------------------------------------
一。新建java web工程 这里取名为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页面登陆按钮以及标签支持:
<%
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:'用户名与密码不正确!'}");
}catch(UnknownAccountException e){
out.println("{success:false,msg:'用户名不存在!'}");
}
return;
}
%>
在jsp页面中增加用户名和密码登陆框。
五。新建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);
} // 授权
@Override
protected AuthorizationInfo doGetAuthorizationInfo(
PrincipalCollection principalCollection) {
if (!SecurityUtils.getSubject().isAuthenticated()) {
doClearCache(principalCollection);
SecurityUtils.getSubject().logout();
return null;
} // 添加角色及权限信息
SimpleAuthorizationInfo sazi = new SimpleAuthorizationInfo(); return sazi;
} // 认证
@Override
protected 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算法与迭代次数.
*/
@PostConstruct
public 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
[shiro学习笔记]第二节 shiro与web融合实现一个简单的授权认证的更多相关文章
- [struts2学习笔记] 第二节 使用Maven搞定管理和构造Struts 2 Web应用程序的七个步骤
本文地址:http://blog.csdn.net/sushengmiyan/article/details/40303897 官方文档:http://struts.apache.org/releas ...
- [shiro学习笔记]第一节 使用eclipse/myeclipse搭建一个shiro程序
本文地址:http://blog.csdn.net/sushengmiyan/article/details/39519509 shiro官网:http://shiro.apache.org/ shi ...
- 【shiro】shiro学习笔记1 - 初识shiro
[TOC] 认证流程 st=>start: Start e=>end: End op1=>operation: 构造SecurityManager环境 op2=>operati ...
- [ExtJS5学习笔记]第二节 Sencha Cmd 学习笔记 使你的sencha cmd跑起来
本文地址: http://blog.csdn.net/sushengmiyan/article/details/38313537 本文作者:sushengmiyan ----------------- ...
- [ExtJS5学习笔记]第九节 Extjs5的mvc与mvvm框架结构简单介绍
本文地址:http://blog.csdn.net/sushengmiyan/article/details/38537431 本文作者:sushengmiyan ------------------ ...
- opengl学习笔记(五):组合变换,绘制一个简单的太阳系
创建太阳系模型 描述的程序绘制一个简单的太阳系,其中有一颗行星和一颗太阳,用同一个函数绘制.需要使用glRotate*()函数让这颗行星绕太阳旋转,并且绕自身的轴旋转.还需要使用glTranslate ...
- Shiro学习笔记(5)——web集成
Web集成 shiro配置文件shiroini 界面 webxml最关键 Servlet 測试 基于 Basic 的拦截器身份验证 Web集成 大多数情况.web项目都会集成spring.shiro在 ...
- Shiro学习笔记总结,附加" 身份认证 "源码案例(一)
Shiro学习笔记总结 内容介绍: 一.Shiro介绍 二.subject认证主体 三.身份认证流程 四.Realm & JDBC reaml介绍 五.Shiro.ini配置介绍 六.源码案例 ...
- shiro学习笔记_0600_自定义realm实现授权
博客shiro学习笔记_0400_自定义Realm实现身份认证 介绍了认证,这里介绍授权. 1,仅仅通过配置文件来指定权限不够灵活且不方便.在实际的应用中大多数情况下都是将用户信息,角色信息,权限信息 ...
随机推荐
- 删数方案数(regex)
[题目描述] 给出一个正整数序列 a,长度为 n,cyb 不喜欢完美,他要删掉一些数(也可以不删,即删掉0个),但是他不会乱删,他希望删去以后,能将 a 分成 2 个集合,使得两个非空集合的数的和相同 ...
- 【USACO】 洞穴奶牛
题目描述 贝西喜欢去洞穴探险.这次她去的地方由 N 个洞穴组成,编号分别是 1 到 N,1 号洞穴是出发 的起点. 洞穴之间由 M 条隧道相连,双向通行,第 i 条隧道连接 A i 和 B i .每条 ...
- hdu 5463(水水)
Sample Input 2 3 2 33 3 33 2 33 10 5 467 6 378 7 309 8 499 5 320 3 480 2 444 8 391 5 333 100 499 S ...
- bzoj 1407: [Noi2002]Savage
Description 解题报告: 因为给定答案范围,暴力枚举时间,然后再两两枚举野人,判断是否有可能在某一年相遇,我们设这一年为\(x\),那么显然相交的条件是: \(x*(p[i]-p[j])+y ...
- 使用JAXB解析xml文件(二)
前面一章简单演示了JAXB的用法,这个章节主要梳理一下JAXB常见的几个注解 1.@XmlRootElement 用于类级别的注解,对应xml的跟元素,常与 @XmlType 和 @XmlAccess ...
- 使用JdbcTemplate过程中使用到多个参数和like模糊
项目中经常会用到模糊查询,最近使用JdbcTemplate过程中就遇到了. 一开始尝试了拼接的方式去 String sql = "select count(1) from web_users ...
- 查询优化--小表驱动大表(In,Exists区别)
Mysql 系列文章主页 =============== 本文将以真实例子来讲解小表驱动大表(In,Exists区别) 1 准备数据 1.1 创建表.函数.存储过程 参照 这篇(调用函数和存储过程批 ...
- lgp20151222 java中如何将Object类型转换为int类型
if (object instanceof Integer) { Integer.parseInt(object.toString()); } 很简单是不是?我就想提醒下自己,java有个特殊词 ...
- 读书笔记-《Maven实战》-2018/4/16
第一章:Maven简介 1:Maven:Maven原本的单词意思为"知识的积累",谷歌翻译为"行家",而作为Apache的开源项目,Maven是一个主要服务于基 ...
- 让ckplayer支持m3u8格式的播放
一 ckplayer官网下载. 直接解压到本地,注意配置里面的默认文件路径,最好是放在服务器的根目录下,这样就可以去访问外链接的资源,官网也是这么推荐的,我这里就直接用node开启一个小服务器. 二 ...