[shiro學習筆記]第二節 shiro與web融合實現一個簡單的授權認證

來源:互聯網
上載者:User

標籤:style   blog   http   color   io   os   ar   java   for   

本文地址: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 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);}// 授權@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# -----------------------------------------------------------------------------#realmmyRealm = com.susheng.shiro.ShiroDbRealmsecurityManager.realm = $myRealm[users]# user ‘root‘ with password ‘secret‘ and the ‘admin‘ roleroot = secret, admin# user ‘guest‘ with the password ‘guest‘ and the ‘guest‘ roleguest = 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


OK。現在,以及實現了對web的支援。

代碼:http://download.csdn.net/detail/sushengmiyan/8022503


[shiro學習筆記]第二節 shiro與web融合實現一個簡單的授權認證

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.