[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.pswp.cn/news/455544.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/455544.shtml
英文地址,請注明出處:http://en.pswp.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;對移動的業務有一個推動…