[Shiro Study Notes] section 2 integrate shiro with web to implement a simple authorization Authentication

Source: Internet
Author: User

[Shiro Study Notes] section 2 integrate shiro with web to implement a simple authorization Authentication

 

Shiro Chinese manual: http://wenku.baidu.com/link? Url = ZnnwOHFP20LTyX5ILKpd_P94hICe9Ga154KLj_3cCDXpJWhw5Evxt7sfr0B5QSZYXOKqG_FtHeD-RwQvI5ozyTBrMAalhH8nfxNzyoOW21K

Author: sushengmiyan

Certificate ------------------------------------------------------------------------------------------------------------------------------------

I. Create a java web project named shirodemo

II. Add the dependent jar package as follows:

3. Add web Support for shiro

As described in the first article, add the webs. xml deployment description:

 

  
   
  
   org.apache.shiro.web.env.EnvironmentLoaderListener
    
   
   
  
   shiro
    
  
   org.apache.shiro.web.servlet.ShiroFilter
    
   
   
  
   shiro
    
  
   /*
    
 

 

4. Add the jsp page login button and tag support:

 

<% 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 (logon successful);} catch (IncorrectCredentialsException e) {out. println ({success: false, msg: 'incorrect user name and password! '});} Catch (UnknownAccountException e) {out. println ({success: false, msg:' the user name does not exist! '}) ;}Return ;}%>

Add the user name and password logon box on the jsp page.

5. Create realm implementation

 

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. sim PleAuthenticationInfo; 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. apa Che. shiro. subject. principalCollection; import org. apache. shiro. subject. subject; import org. slf4j. logger; import org. slf4j. loggerFactory; // The 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 () {// authentication super. Authentication (false); // authorization super. setAuthorizationCacheName (AUTHCACHENAME);} // authorization @ Overrideprotected AuthorizationInfo doGetAuthorizationInfo (PrincipalCollection principalCollection) {if (! SecurityUtils. getSubject (). isAuthenticated () {doClearCache (principalCollection); SecurityUtils. getSubject (). logout (); return null;} // Add the role and permission information SimpleAuthorizationInfo sazi = new SimpleAuthorizationInfo (); return sazi;} // AuthenticationInfo (authentprotetoken) 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;}/*** sets the Hash algorithm and number of iterations for Password verification. * // @ PostConstructpublic void initCredentialsMatcher () {HashedCredentialsMatcher matcher = new HashedCredentialsMatcher (HASH_ALGORITHM); matcher. setHashIterations (HASH_INTERATIONS); setCredentialsMatcher (matcher );}}

 

Sat. Added support for realm in the shiro. ini file content.

 

## 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

7. Tomcat adds deployment for this application. Start tomcat and enter the corresponding url.

View the implementation result:

Logon page display

Click Log On and insert the shiro implementation. There is no substantive authentication yet, but the shiro environment is generally set up. Insert your own realm implementation.

 

 

OK. Now, we have implemented web support.

Code: http://download.csdn.net/detail/sushengmiyan/8022503


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.