Shiro of Java Applications

Source: Internet
Author: User
Tags assert set set

Apache Shiro is a powerful and flexible open source security framework that handles identity authentication, authorization, enterprise session management, and encryption cleanly.

Here's what you can do with Apache Shiro:

1. Verify the user

2, the user to perform access control, such as:

Determines whether the user has the role admin.

To determine whether a user has permission to access

3. Use the Session API in any environment. such as CS programs.

4. You can use multiple user data sources. For example, one is the Oracle User library and the other is the MySQL user library.

5, Single Sign-On (SSO) feature.

6, "Remember Me" service, similar to the function of shopping cart, Shiro official suggestions open.

4 of Shiro--authentication, authorization, session management and encryption

· Authentication: Authentication, referred to as "login".

· Authorization: authorization, assigning roles or permissions resources to users

· Session Management: User Session Manager, you can let CS program also use session to control permissions

· Cryptography: Encapsulates a complex password encryption method in the JDK.

Subject is an object that interacts with a program, which can be either a person or a service or something else, which is usually understood as a user.

All subject instances must be bound to a securitymanager. We interact with a Subject, and the runtime Shiro automatically translates into the interaction of a specific Subject interacting with SecurityManager

1.Subject (Org.apache.shiro.subject.Subject):

Abbreviation user

2.SecurityManager (Org.apache.shiro.mgt.SecurityManager)

As mentioned above, SecurityManager is the core of Shiro, coordinating the various components of Shiro

3.Authenticator (Org.apache.shiro.authc.Authenticator):

Login control

Note: Authentication strategy

(Org.apache.shiro.authc.pam.AuthenticationStrategy)

If there is more than one realm, then the interface authenticationstrategy will determine what kind of login is successful (for example, if one realm succeeds and the other fails, is the login successful?). )

4.Authorizer (Org.apache.shiro.authz.Authorizer):

Decide what roles or permissions subject can have.

5.SessionManager (Org.apache.shiro.session.SessionManager):

Create and manage a user session. By setting this manager, Shiro can use the session in any environment.

6.CacheManager (Org.apahce.shiro.cache.CacheManager):

Cache Manager, you can reduce unnecessary background access. Improve application efficiency and increase user experience.

7.Cryptography (org.apache.shiro.crypto.*):

The Shiro API greatly simplifies the cumbersome password encryption in the Java API.

8.Realms (Org.apache.shiro.realm.Realm):

A bridge between program and safety data

Configuration of the Shiro

Note: Only spring configuration mode is described here.

Because the official example has a more concise INI configuration form, the use of the INI configuration does not integrate with spring. And the same as the two configuration methods, but the format is not the same.

Jar packages required for integration with spring

Jar Package Name

Version

Core Pack Shiro-core

1.2.0

Web-related Package shiro-web

1.2.0

Cache Package Shiro-ehcache

1.2.0

Integration with Spring package shiro-spring

1.2.0

Ehcache Cache Core Package Ehcache-core

2.5.3

Shiro Self-Log package slf4j-jdk14

1.6.4

2. Add the Shiro configuration in spring's Applicationcontext.xml

SecurityManager: This attribute is required.

loginurl : Users who are not logged in need to automatically jump to the login page when they request a page to log in, not the required properties, and the "/login.jsp" page in the root directory of the Project Web project is automatically searched if the address is not entered.

successurl : Login Successful default jump page, do not configure to jump to "/". If you click on a login before landing a page, the login will automatically jump to that need to sign in the page. Do not jump to this

unauthorizedurl : page without permission default jump

Filter abbreviation

the corresponding Java class

Anon

Org.apache.shiro.web.filter.authc.AnonymousFilter

Authc

Org.apache.shiro.web.filter.authc.FormAuthenticationFilter

Authcbasic

Org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter

Perms

Org.apache.shiro.web.filter.authz.PermissionsAuthorizationFilter

Port

Org.apache.shiro.web.filter.authz.PortFilter

Rest

Org.apache.shiro.web.filter.authz.HttpMethodPermissionFilter

Roles

Org.apache.shiro.web.filter.authz.RolesAuthorizationFilter

Ssl

Org.apache.shiro.web.filter.authz.SslFilter

User

Org.apache.shiro.web.filter.authc.UserFilter

Logout

Org.apache.shiro.web.filter.authc.LogoutFilter

Anon: Example/admins/**=anon has no parameters, which means it can be used anonymously.

AUTHC: For example,/ADMINS/USER/**=AUTHC indicates that authentication (login) is required to use, no parameters

Roles: Example/admins/user/**=roles[admin], parameters can be written multiple, multiple must be quoted, and the parameters are separated by commas, when there are multiple parameters, such as admins/user/**=roles["Admin,guest "], each parameter is passed only, equivalent to the Hasallroles () method.

Perms: Example/admins/user/**=perms[user:add:*], parameters can be written multiple, multiple must be quoted, and the parameters are separated by commas, such as/admins/user/**=perms["user:add:*, user:modify:* "], when there are multiple parameters must be passed before each argument, want to be in the Ispermitedall () method.

Rest: Example/admins/user/**=rest[user], according to the method requested, equivalent to/admins/user/**=perms[user:method], where method is Post,get,delete, etc.

Port: Example/admins/user/**=port[8081], when the port of the requested URL is not 8081 is jump to schemal://servername:8081?querystring, Where Schmal is the protocol HTTP or HTTPS, etc., servername is the host,8081 you access is the port in the URL configuration, queryString

Is it in the URL you visited? The following parameters.

Authcbasic: For example/admins/user/**=authcbasic no parameter indicates httpbasic authentication

SSL: Example/admins/user/**=ssl has no parameters, represents a secure URL request, the protocol is HTTPS

User: For example,/admins/user/**=user does not have a parameter that indicates that it must exist, and does not check when logging in

Note: Anon,authcbasic,auchc,user is a certified filter,

Perms,roles,ssl,rest,port is an authorization filter

3. Add the securitymanagerper configuration in Applicationcontext.xml

4. Configure Bosrealm

5. Configuring Shiro Annotation Mode

@RequiresAuthentication

Verify that the user is logged on, equivalent to Method subject.isauthenticated () When the result is true

@ requiresuser

To verify that users are remembered, user has two meanings:

One is a successful login (the subject.isauthenticated () result is true);

The other is the memory (subject.isremembered () result is true).

@ requiresguest

Verify that a guest request is the exact opposite of @ requiresuser.

In other words, Requiresuser = =! Requiresguest.

The Subject.getprincipal () result is null at this time.

Three. Simple extension

    1. Custom Realm:

<!--custom Myrealm inherit from Authorizingrealm, or you can choose the Shiro provided- -

<bean id="Myrealm" class= "Com.yada.shiro.MyReam" ></bean>

// This is the authorization method

protected Authorizationinfo dogetauthorizationinfo (principalcollection principals) {

String userName = (string) getavailableprincipal (principals);

TODO gets all of the user's resources through the username and stores the resources in info

.........................

Simpleauthorizationinfo info = new Simpleauthorizationinfo ();

Info.setstringpermissions (set set);

Info.setroles (set set);

Info.setobjectpermissions (set set);

return info;

}

// This is the authentication method .

protected AuthenticationInfo dogetauthenticationinfo (Authenticationtoken token) throws Authenticationexception {

//token stored in the user name and password entered

Usernamepasswordtoken Uptoken = (usernamepasswordtoken) token;

// get user name and password

String username = uptoken.getusername ();

string Password = string. valueOf (Uptoken.getpassword ());

TODO is compared to the user name and password in the database. Compared to the success of the return info, compared to the failure to throw the corresponding information exception authenticationexception

.......................

Simpleauthenticationinfo info = new Simpleauthenticationinfo (username, password. ToCharArray (), GetName ());

return info;

}

2. Custom Login

// Create a token for the user name and password

Usernamepasswordtoken token=new Usernamepasswordtoken (User.getusername (), User.getpassword ());

// record the token, if not logged, then the shopping cart feature cannot be used.

Token.setrememberme (TRUE);

//subject understood as a permission object. Similar to User

Subject Subject = securityutils. Getsubject ();

try {

Subject.login (token);

} catch (Unknownaccountexception ex) {// username not found.

} catch (Incorrectcredentialsexception ex) {// username password does not match.

}catch (authenticationexception e) {// Other login errors

}

// methods to verify successful logons

if (subject.isauthenticated ()) {

}

3. Custom Logout

Subject Subject = securityutils. Getsubject ();

Subject.logout ();

    1. Encoding-based Role authorization implementation

Subject CurrentUser = Securityutils.getsubject ();

if (Currentuser.hasrole ("Administrator")) {

Have a role administrator

} Else {

No role handling

}

Assert mode control

Subject CurrentUser = Securityutils.getsubject ();

If there is no role admin, an exception will be thrown and somemethod () will not be executed

Currentuser.checkrole ("admin");

SomeMethod ();

    1. Implementation of resource authorization based on coding

Subject CurrentUser = Securityutils.getsubject ();

if (Currentuser.ispermitted ("Permssion:look")) {

Have resource permissions

} Else {

No permissions

}

Assert mode control

Subject CurrentUser = Securityutils.getsubject ();

An exception is thrown if there is no resource permission.

Currentuser.checkpermission ("Permssion:look");

SomeMethod ();

    1. The tag implementation on the JSP

Label name

Label conditions (both display label contents)

<shiro:authenticated>

After login

<shiro:notAuthenticated>

When not in the login state

<shiro:guest>

When the user is not rememberme

<shiro:user>

When users are RememberMe

<shiro:hasanyroles name="abc,123" >

When there are ABC or 123 characters

<shiro:hasrole name="abc" >

have role ABC

<shiro:lacksrole name="abc" >

No role ABC

<shiro:haspermission name="abc" >

have permission resource ABC

<shiro:lackspermission name="abc" >

No ABC permissions Resources

<shiro:principal>

Show user name by default

7.

By default, the user's role or resource is added or removed, and the system does not need to be restarted, but requires the user to log back on.

That is, the user's authorization is loaded when the first access requires a permissions page after the first logon.

However, permission resources that need to be controlled are loaded at startup, and if a new permission resource is required to restart the system.

8.

Spring security differs from Apache Shiro:

A) Shiro configuration is easier to understand and easy to get started; Security configuration is relatively difficult to understand.

b) in the spring environment, security integration is better. Shiro is better compatible with many other frameworks, claiming to be seamlessly integrated.

c) Shiro can not only be used in the web, it can work in any application environment.

D) One of the most important benefits of Shiro during a cluster session is that its session is separate from the container.

e) password encryption provided by Shiro is very convenient to use.

9.

Control accuracy:

Annotation mode control permissions can only be controlled on a method and cannot control class-level access.

The filter mode control is controlled based on the URL accessed. Allows you to use * to match URLs, so you can do coarse-grained or fine-grained control.

Shiro of Java Applications

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.