Default Authentication and custom authentication

Source: Internet
Author: User
Tags url example

Filter chain definition:


[Html]
<! -- Filter chain definition -->
<Property name = "filterChainDefinitions">
<Value>
...
/Pages/User/create. do * = perms [User: create]
...
</Value>
</Property>

<! -- Filter chain definition -->
<Property name = "filterChainDefinitions">
<Value>
...
/Pages/User/create. do * = perms [User: create]
...
</Value>
</Property>
The meaning of this configuration is: The Request Path such as/pages/User/create. do * requires authentication and the User must have the "User: create" permission string.

Perms is the name of the Interceptor. The default implementation class is org. apache. shiro. web. filter. authz. PermissionsAuthorizationFilter.

This filter will obtain the permission string corresponding to the Request Path in the configuration, such as "User: create", and then find the permissions contained by the current User in realm. Specifically, it calls the reaml callback function:


[Java]
/**
* The authentication callback function extracts the role and permissions of the client.
* Principals Client
*/
Protected AuthorizationInfo doGetAuthorizationInfo (
PrincipalCollection principals ){
// User Name
String username = (String) principals. fromRealm (
GetName (). iterator (). next ();

/* These codes should be dynamically extracted from the database. Write them to death */
If (username! = Null & username. equals ("admin ")){
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo ();
// Info. addRole ("admin"); // Add a role, not in the configuration sense, but to prove that the user has the admin role
Info. addStringPermission ("User: create ");
Info. addStringPermission ("/pages/index. jsp"); // Add Permissions
Info. addStringPermission ("/pages/info. jsp"); // Add Permissions
Return info;
}
Return null;
}

/**
* The authentication callback function extracts the role and permissions of the client.
* Principals Client
*/
Protected AuthorizationInfo doGetAuthorizationInfo (
PrincipalCollection principals ){
// User Name
String username = (String) principals. fromRealm (
GetName (). iterator (). next ();

/* These codes should be dynamically extracted from the database. Write them to death */
If (username! = Null & username. equals ("admin ")){
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo ();
// Info. addRole ("admin"); // Add a role, not in the configuration sense, but to prove that the user has the admin role
Info. addStringPermission ("User: create ");
Info. addStringPermission ("/pages/index. jsp"); // Add Permissions
Info. addStringPermission ("/pages/info. jsp"); // Add Permissions
Return info;
}
Return null;
}
This code belongs to the custom Realm -- public class CustomRealm extends AuthorizingRealm

In the code, we use test data and directly add the role string and permission string to info. We can also obtain them from the database, which is not the focus of this section.

At present, the key is to understand that SecurityManager obtains the expected permission string from the request end, obtains the role and permission string of the client from Realm, and compares them. If the comparison is successful, the authentication succeeds. Otherwise, the authentication fails.

 


In fact, this configuration authentication method is not required for custom Realm. user information, role information, and permission information can be configured as follows:


[Html]
[Users]
# User1 = sha256-hashed-hex-encoded password, role1, role2 ,...
User1 = role, role1, role2 ,...
[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)
# License plate 'eagle5' (instance specific id)
Goodguy = winnebago: drive: eagle5

[Users]
# User1 = sha256-hashed-hex-encoded password, role1, role2 ,...
User1 = role, role1, role2 ,...
[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)
# License plate 'eagle5' (instance specific id)
Goodguy = winnebago: drive: eagle5
For more information, see the official documentation.

 


============================ Custom authentication ==========================

We often design several tables for our projects, especially legacy projects, to store user information, role information, and permission ing information. Therefore, Realm is generally customized.

Generally, the request URL is directly used as the permission string, that is, some permission strings do not need to be mapped to the URL. Therefore, we may also need to customize the filter.

Custom authentication filter:


[Java]
Package javacommon. shiro;
 
Import java. io. IOException;
Import java. util. regex. Matcher;
Import java. util. regex. Pattern;
 
Import javax. servlet. ServletRequest;
Import javax. servlet. ServletResponse;
Import javax. servlet. http. HttpServletRequest;
 
Import org. apache. shiro. web. filter. authz. PermissionsAuthorizationFilter;
 
/**
* URL-based permission judgment filter <p>
* The so-called permission string is automatically generated based on the URL. This item is written in the configuration file in the Shiro example. By default, the permission cannot be dynamically configured. <p>
* URL example:/User/create. do? * ** = *** --> Permission string:/User/create. do
* @ Author zhengwei lastmodified August 15, 2013
*
*/
Public class URLPermissionsFilter extends PermissionsAuthorizationFilter {
/**
* @ Param mappedValue refers to the permission string specified when the url is declared, for example,/User/create. do = perms [User: create]. we need to dynamically generate this permission string, so this configuration is useless to us.
*/
Public boolean isAccessAllowed (ServletRequest request,
ServletResponse response, Object mappedValue) throws IOException {
Return super. isAccessAllowed (request, response, buildPermissions (request ));
}
/**
* Generate a permission string based on the request URL. Only the permission string is generated here, and the comparison is handed over to Realm.
* @ Param request
* @ Return
*/
Protected String [] buildPermissions (ServletRequest request ){
String [] perms = new String [1];
HttpServletRequest req = (HttpServletRequest) request;
String path = req. getServletPath ();
Perms [0] = path; // path directly serves as the permission string
/* String regex = "/(.*?) /(.*?) \\.(.*)";
If (url. matches (regex )){
Pattern pattern = Pattern. compile (regex );
Matcher matcher = pattern. matcher (url );
String controller = matcher. group (1 );
String action = matcher. group (2 );

}*/
Return perms;
}
}

Package javacommon. shiro;

Import java. io. IOException;
Import java. util. regex. Matcher;
Import java. util. regex. Pattern;

Import javax. servlet. ServletRequest;
Import javax. servlet. ServletResponse;
Import javax. servlet. http. HttpServletRequest;

Import org. apache. shiro. web. filter. authz. PermissionsAuthorizationFilter;

/**
* URL-based permission judgment filter <p>
* The so-called permission string is automatically generated based on the URL. This item is written in the configuration file in the Shiro example. By default, the permission cannot be dynamically configured. <p>
* URL example:/User/create. do? * ** = *** --> Permission string:/User/create. do
* @ Author zhengwei lastmodified August 15, 2013
*
*/
Public class URLPermissionsFilter extends PermissionsAuthorizationFilter {
/**
* @ Param mappedValue refers to the permission string specified when the url is declared, for example,/User/create. do = perms [User: create]. we need to dynamically generate this permission string, so this configuration is useless to us.
*/
Public boolean isAccessAllowed (ServletRequest request,
ServletResponse response, Object mappedValue) throws IOException {
Return super. isAccessAllowed (request, response, buildPermissions (request ));
}
/**
* Generate a permission string based on the request URL. Only the permission string is generated here, and the comparison is handed over to Realm.
* @ Param request
* @ Return
*/
Protected String [] buildPermissions (ServletRequest request ){
String [] perms = new String [1];
HttpServletRequest req = (HttpServletRequest) request;
String path = req. getServletPath ();
Perms [0] = path; // path directly serves as the permission string
/* String regex = "/(.*?) /(.*?) \\.(.*)";
If (url. matches (regex )){
Pattern pattern = Pattern. compile (regex );
Matcher matcher = pattern. matcher (url );
String controller = matcher. group (1 );
String action = matcher. group (2 );

}*/
Return perms;
}
}

We can see that we directly use the request path as the permission string, and the filter will call Realm. Therefore, we need to add the permission string in the same format for the user in the Custom Realm.


[Java]
Info. addStringPermission ("/pages/index. jsp"); // Add permissions. admin can access this path.

Info. addStringPermission ("/pages/index. jsp"); // Add permissions. admin can access this path.
Finally, let's take a look at the configuration of global Filter:


[Html]
<! -- Shiro Filter interceptor configuration -->
<Bean id = "shiroFilter" class = "org. apache. shiro. spring. web. ShiroFilterFactoryBean">
...
<Property name = "filters">
<Util: map>
<Entry key = "authc" value-ref = "myAuthenFilter"/>
<Entry key = "perms" value-ref = "URLPermissionsFilter"/>
</Util: map>
</Property>
<! -- Filter chain definition -->
<Property name = "filterChainDefinitions">
<Value>
/Login. jsp = authc
/Pages/* = authc, perms
/Logout. do = logout
...
</Value>
</Property>
</Bean>
 
...
<! -- Custom authentication interceptor -->
<Bean id = "URLPermissionsFilter" class = "javacommon. shiro. URLPermissionsFilter"/>

<! -- Shiro Filter interceptor configuration -->
<Bean id = "shiroFilter" class = "org. apache. shiro. spring. web. ShiroFilterFactoryBean">
...
<Property name = "filters">
<Util: map>
<Entry key = "authc" value-ref = "myAuthenFilter"/>
<Entry key = "perms" value-ref = "URLPermissionsFilter"/>
</Util: map>
</Property>
<! -- Filter chain definition -->
<Property name = "filterChainDefinitions">
<Value>
/Login. jsp = authc
/Pages/* = authc, perms
/Logout. do = logout
...
</Value>
</Property>
</Bean>

...
<! -- Custom authentication interceptor -->
<Bean id = "URLPermissionsFilter" class = "javacommon. shiro. URLPermissionsFilter"/>

 


This configuration indicates that authentication is required for access to/pages/*, and authentication uses a custom interceptor.

Test:

Log on to and access pages/info. jsp as admin. No problem, because it has this permission.

Access pages/NB. jsp. Because this path is not added to the admin permission, authentication fails and will jump to the path specified by unauthorizedUrl.

 

 

 

Section:

If the customer requires the program developer to manage permissions on their own and does not need dynamic configuration, it is very simple to use the default configuration method.

When you need dynamic management permissions, You need to customize Realm and Filter. The key lies in the request URL -- "permission string. Realm can return a user-owned permission string.

These strings should be comparable.


 

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.