Use of the Shiro security framework

Source: Internet
Author: User

L use of Shiro

Configuring in Web.xml: Shiro Core Controller Delegatingfilterproxy

Applicationcontext.xml Transaction Management Declaration configuration: Open Cglib Dynamic proxy mode

Configure Shiro Profiles: based on spring

Shiro configuration file:

Configuration of Description>shiro </description>

<!--SecurityManager configuration-->

<!--Configure Realm domain-->

<!--password Comparator-->

<!--how the agent is generated. Use the factory to generate Shiro filters-->

<!--configuration cache: Ehcache Cache-->

<!--safety Management-->

<bean id= "SecurityManager" class= "Org.apache.shiro.web.mgt.DefaultWebSecurityManager" >

<!--single Realm app. If you are have Multiplerealms, use the ' Realms ' property instead. -->

<property name= "Realm" ref= "Authrealm"/><!--reference to Custom realm-->

<!--cache-->

<property name= "CacheManager" ref= "Shiroehcachemanager"/>

</bean>

<!--custom permission authentication-->

<bean id= "Authrealm" class= "cn.itcast.jk.shiro.AuthRealm[A1]" >

<property name= "UserService" ref= "UserService"/>

<!--custom password encryption algorithm-->

<property name= "Credentialsmatcher" ref= "Passwordmatcher"/>

</bean>

<!--Set Password encryption policy Md5hash-->

<bean id= "Passwordmatcher" class= " Cn.itcast.jk.shiro.CustomCredentialsMatcher [A2] "/>

<!--filter-name The value of this name comes from the name of the filter in Web.xml-->

<bean id= "Shirofilter" class= "Org.apache.shiro.spring.web.ShiroFilterFactoryBean" >

<property name= "SecurityManager" ref= "SecurityManager"/>

<!--login Page-->

<property name= "loginurl" value= "/index.jsp" ></property>

<!----> after successful login

<property name= "Successurl" value= "/home.action" ></property>

<property name= "Filterchaindefinitions" >

<!--/** represents the following multilevel directory also filter-->

<value>

/index.jsp* = Anon

/home* = Anon

/sysadmin/login/login.jsp* = Anon

/sysadmin/login/logout.jsp* = Anon

/login* = Anon

/logout* = Anon

/components/** = Anon

/css/** = Anon

/images/** = Anon

/js/** = Anon

/make/** = Anon

/skin/** = Anon

/stat/** = Anon

/ufiles/** = Anon

/validator/** = Anon

/resource/** = Anon

/** = authc

/*.* = authc

</value>

</property>

</bean>

<!--user authorization/authentication information cache, using Ehcache caching-->

<bean id= "Shiroehcachemanager" class= "Org.apache.shiro.cache.ehcache.EhCacheManager" >

<property name= "cachemanagerconfigfile" value= " Classpath:ehcache-shiro.xml [A3] "/>

</bean>

<!--guarantee the implementation of Shiro internal lifecycle function Bean execution-->

<bean id= "Lifecyclebeanpostprocessor" class= "Org.apache.shiro.spring.LifecycleBeanPostProcessor"/>

<!--generation agent, control--> by proxy

<bean class= "Org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"

depends-on= "Lifecyclebeanpostprocessor" >

<property name= "Proxytargetclass" value= "true"/>

</bean>

<!--security Manager-->

<bean class= "Org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor" >

<property name= "SecurityManager" ref= "SecurityManager"/>

</bean>


Licensing & Management Classes

Public class Authrealm extends authorizingrealm{

Private UserService UserService;

Public voidsetuserservice (UserService userservice) {

this. UserService = UserService;

}

/**

* Authorized

*/

@Override

protected Authorizationinfo dogetauthorizationinfo (principalcollection pc) {

User user = (user) Pc.fromrealm (this. GetName ()). Iterator (). Next (); [A4]

Get Object Navigation

set<role> roles = User.getroles ();

list<string> permissions = newarraylist<string> ();

for (Role Role:roles) {

Traversal roles get a list of modules under each role

set<module> modules = Role.getmodules ();

Put the module name into the permissions

for (Module module:modules) {

Permissions.add (Module.getname ());

}

Simpleauthorizationinfo info = newsimpleauthorizationinfo ();

Info.addstringpermissions (permissions);

return info;

}

return null;

}

/**

* Certification

*/

@Override

protected AuthenticationInfo dogetauthenticationinfo (authenticationtoken token[A5]) throws authenticationexception {

Usernamepasswordtoken uptoken = (usernamepasswordtoken) token; [A6]

Query users

String hql = "Fromuser where username=?";

list<user> list = Userservice.find (HQL, User. Class, new String[]{uptoken.getusername ()});

To determine whether a user exists

if (list!=null && list.size () >0) {

Get user Name

User user = List.get (0);

Core API

Simpleauthenticationinfo info = newsimpleauthenticationinfo (user, User.getpassword (),

this. GetName () [A7]); [A8]

return info;//Enter password comparator

}

return null;

}

 

Password Comparator:

Public class Customcredentialsmatcher extendssimplecredentialsmatcher{

Password comparison

Public booleandocredentialsmatch (authenticationtokentoken, authenticationinfo Info[A9] [A10]) {

Usernamepasswordtoken Uptoken = (usernamepasswordtoken) token;

Encrypt the original password entered by the user in the interface

Object pwd = encrypt.md5 (new String (Uptoken.getpassword ())[A11], uptoken.getusername () [A12]); [A13]

Get the encrypted password in the database

Object dbpwd = Info.getcredentials ();

return this. equals (pwd,dbpwd);//Password comparison

}

}

methods in action:

 

Try {

Subject Subject =securityutils.getsubject (); [A14]

Calling the Login method

Usernamepasswordtoken Tokan = newusernamepasswordtoken (username, password);

Subject.login (Tokan); When this code executes, it automatically jumps into the Authrealm authentication method

When the login succeeds, remove the user's login information from the Shiro

User user = (user) subject.getprincipal ();

Catch (Exception e) {

E.printstacktrace ();

Request.put ("ErrorInfo", "Username or password error");

return "Login";

}


Execution process:

 

 

 

[A1] Custom Authentication & permission path

[A2] custom password comparer

[A3] Cached configuration file

[A4] Gets the user object

[A5] store user name and password

[A6] casts an interface to its implementation class

[A7] can be any string, and in the authorization Pc.fromrealm(this. getName ()). Iterator (). Next (); GetName () Consistent <

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.