Multi-project centralized rights management and distributed sessions

Source: Internet
Author: User
Tags memcached redis sessions mysql database nginx reverse proxy

When doing some enterprise internal projects or some Internet background, it may involve centralized rights management, unified multi-project rights management, and also need unified session management, that is, the realization of single-point authentication and authorization control.

Before you learn this chapter, be sure to first learn the tenth chapter session management and the 16th comprehensive example, the code of this chapter is based on the two chapters of the code to complete.

This chapter example is done under the same domain name scenario, if cross-domain refer to chapter 15th Single Sign-on and chapter 17th OAUTH2 Integration for cross-domain authentication and authorization using CAS or OAUTH2. In addition, such as client/server security check can refer to the 20th chapter of stateless Web application integration.

Deployment Architecture

1. There are three applications: Server for user/rights control (port: 8080), two applications App1 (port 9080) and APP2 (Port 10080);

2, using Nginx reverse proxy three applications, the NGINX.CONF Server configuration section is as follows:   Java code    server {        listen 80;       server_name  localhost;       charset utf-8;       location ~ ^/( Chapter23-server)/ {           proxy_pass http:// 127.0.0.1:8080;            index /;               proxy_set_header Host  $host;        }       location ~ ^/( CHAPTER23-APP1)/ {           proxy_pass http:// 127.0.0.1:9080;            index /;               proxy_set_header host  $host;        }       location ~ ^/(CHAPTER23-APP2)/ {            proxy_pass http://127.0.0.1:10080;             index /;                proxy_set_header Host  $host;       }   }   

such as Access Http://localhost/chapter23-server will be automatically forwarded to Http://localhost:8080/chapter23-server;

Access HTTP://LOCALHOST/CHAPTER23-APP1 is automatically forwarded to HTTP://LOCALHOST:9080/CHAPTER23-APP1; Access http://localhost/ CHAPTER23-APP3 will be automatically forwarded to HTTP://LOCALHOST:10080/CHAPTER23-APP3;

Nginx installation and use please search for their own study, this article is no longer elaborated.

Project Architecture

1, first through the user/authority server to maintain user, application, permissions information, data are persisted to the MySQL database;

2. Apply app1/application APP2 use client clients to remotely invoke the user/permissions server to obtain session and permission information.

Instead of using MySQL storage sessions, such as Memcached/redis, the main purpose is to reduce the cost of learning, and it will not be difficult if you switch to Redis;


Another benefit of using such as Redis is that you do not need to have a session expiration scheduler in user/permissions server, which can be done with Redis's own expiration policy.

Module Relationship Dependent




1. Shiro-example-chapter23-pom module: Provides the dependency of all other modules, so that other modules can inherit it directly, simplifying dependent configuration, such as Shiro-example-chapter23-server:java code < Parent> <artifactId>shiro-example-chapter23-pom</artifactId> <groupid>com.github.zhangkai Tao</groupid> <version>1.0-SNAPSHOT</version> </parent>

2, Shiro-example-chapter23-core module: Provided to Shiro-example-chapter23-server, Shiro-example-chapter23-client, The core dependence of shiro-example-chapter23-app* module, such as Remote Call interface;

3, Shiro-example-chapter23-server module: Provides users, applications, rights management functions;

4, Shiro-example-chapter23-client module: Provide to the application module to obtain the session and application of the corresponding permissions information;

5, shiro-example-chapter23-app* module: Each sub-application, such as some internal management system applications; its login jumps to Shiro-example-chapter23-server login In addition, permissions are obtained from Shiro-example-chapter23-server (for example, by remote invocation).

Shiro-example-chapter23-pom Module

The packaging type of the pom.xml is Pom, and the dependencies required by other modules are added to the Pom, and the other modules simply set the module to parent to automatically inherit these dependencies, such as the Shiro-example-chapter23-server module: Java code <parent> <artifactId>shiro-example-chapter23-pom</artifactId> <groupid>com. Github.zhangkaitao</groupid> <version>1.0-SNAPSHOT</version> </parent>

Simplifies the dependency configuration of other modules, etc.

Shiro-example-chapter23-core Module

Provides dependencies shared by other modules, such as the remote calling interface: Java code public interface Remoteserviceinterface {public Session getsession (String AppKey,       Serializable sessionId);       Serializable CreateSession (Session session);       public void Updatesession (String AppKey, session session);       public void Deletesession (String AppKey, session session);   Public Permissioncontext getPermissions (string AppKey, string username); }

Provides a crud for the session, and obtains the permission context (including roles and permissions strings) based on the application key and user name; Shiro-example-chapter23-server Module service-side implementation ; shiro-example-chapter23-client module Client call.

The com.github.zhangkaitao.shiro.chapter23.core.ClientSavedRequest is also provided, which expands the org.apache.shiro.web.util.SavedRequest; for Shiro-ex ample-chapter23-app* module when accessing some requests to log in, automatically save the request, then redirect to the Shiro-example-chapter23-server module login; login successful and redirect back Because Savedrequest does not save the schema://domain:port part of the URL, it is necessary to extend the savedrequest, so that clientsavedrequest can save Schema://domain:port To redirect from one app to another (or else only within one app):   Java code        public string  getrequesturl ()  {           string requesturi  = getrequesturi ();           if (backUrl !=  null)  {//1               if ( Backurl.tolowercase (). StartsWith ("http://")  | |  backurl.tolowercase (). StartsWith ("https://"))  {                    return backurl;               } else if (! Backurl.startswith (ContextPath))  {//2                    requestURI = contextPath + backUrl;               } else {//3                   requesturi  = backUrl;               }            }            stringbuilder requesturl = new stringbuilder (scheme);//4            requesturl.append ("://");            requesturL.append (domain);//5           //6            if ("http". Equalsignorecase (Scheme)  && port !=   {                Requesturl.append (":"). Append (string.valueof (port));            } else if ("https". Equalsignorecase (Scheme)  && port != 443)  {                requesturl.append (":"). Append (string.valueof (port));           }            //7            Requesturl.append (requesturi);           //8           if  (backurl == null && getquerystring ()  != null)  {                requesturl.append ("?"). Append (GetQueryString ());           }            return requesturl.tostring ();       }       

1, if the Successurl from the outside (the address of the redirect after successful login), and with http://or https://the beginning of the direct return (the corresponding interceptor directly redirected to it);

2. If Successurl has value but no context, spell the following;

3, otherwise, if Successurl has the value, directly assigns the value to the Requesturl to be able; otherwise, if Successurl does not have the value, then Requesturl is the current request address;

5. Spell the schema in front of the URL, such as HTTP or HTTPS;

6, spell the domain name;

7. Put the redirect to the address (with context);

8, if Successurl not value, and have query parameters, spell;

9 returns the address, and the corresponding interceptor redirects directly to it.

shiro-example-chapter23-server Module

a simple entity Relationship Diagram


Simple Data dictionary

Users (Sys_user)

Name

Type

Length

Describe

Id

bigint

Number PRIMARY Key

Username

varchar

100

User name

Password

varchar

100

Password

Salt

varchar

50

Salt

Locked

bool

Whether the account is locked

Application (Sys_app)

Name

Type

Length

Describe

Id

bigint

Number PRIMARY Key

Name

varchar

100

App Name

App_key

varchar

100

Apply key (unique)

App_secret

varchar

100

Apply Security Code

Available

bool

is locked

Authorization (sys_authorization)

Name

Type

Length

Describe

Id

bigint

Number PRIMARY Key

user_id

bigint

Owning user

app_id

bigint

The application that belongs

Role_ids

varchar

100

List of roles

user : Less role_ids than the 16th comprehensive example, because this chapter is multi-project centralized rights management, so the authorization needs to specify the appropriate application, rather than directly to the user authorization, so can not appear in the user role_ids;

application : All centralized permissions applications, where you need to specify the app key (App_key) and app Security Code (App_secret), the app needs to specify its own App_key and user name to get the app's user rights information when accessing the server In addition, App_secret can think of the app's password, such as the need for secure access to consider the use of it, you can refer to the 20th chapter of stateless Web application integration. In addition, the available property indicates whether the app is currently turned on, and if False indicates that the app is currently unavailable, the appropriate permission information cannot be obtained.

Authorization : Authorizes the specified user under the specified app, that is, the role is associated with the user and the app.

Because this chapter uses the 16th synthetic instance code, there are other corresponding table structures (not used in this chapter).

 

table/Data SQL

For details, please refer to

Sql/shiro-schema.sql (table structure)

Sql/shiro-data.sql (initial data)

Entity

Please refer to the entity under the Com.github.zhangkaitao.shiro.chapter23.entity package for details, not listed here.

DAO

Please refer to the DAO interface and implementation under Com.github.zhangkaitao.shiro.chapter23.dao package for details.

Service

Please refer to the Service interface and implementation under the Com.github.zhangkaitao.shiro.chapter23.service package for details. The following is a critical interface outside of the basic crud: Java code public interface Appservice {public Long findappidbyappkey (String appKey);//Based on AppKey Find AppID} Java code public interface Authorizationservice {//find its role based on Appkey and user name public set<string> f       Indroles (string AppKey, string username);   Find the permission string based on AppKey and user name public set<string> findpermissions (string AppKey, string username); }

Finds the roles and permissions strings that the user has for the specified app, based on the Appkey and user name.

userrealm    Java code    protected authorizationinfo  Dogetauthorizationinfo (principalcollection principals)  {       string  username =  (String) principals.getprimaryprincipal ();        Simpleauthorizationinfo authorizationinfo = new simpleauthorizationinfo ();       authorizationinfo.setroles (            authorizationservice.findroles (constants.server_app_key, username));        authorizationinfo.setstringpermissions (        Authorizationservice.findpermissions (constants.server_app_key, username));        return authorizationInfo;  }   

Here you need to call Authorizationservice's Findroles/findpermissions method to get the user's role and permission string collection by passing in Appkey and the user name. The other is the same as the 16th integrated example code.

 

Serverformauthenticationfilter  Java code    public class serverformauthenticationfilter extends  formauthenticationfilter {       protected void  Issuesuccessredirect (Servletrequest request, servletresponse response)  throws  exception {           string fallbackurl =   (String)  getsubject (request, response)                     .getsession (). getattribute ("Authc.fallbackUrl");            if (Stringutils.isempty (fallbackurl))  {               fallbackurl = getsuccessurl ( );           }            webutils.redirecttosavedrequest (requEst, response, fallbackurl);       }  }   

Because it is a multi-item login, for example, if it is redirected from another application, first check if there is a "Authc.fallbackurl" attribute in the session, and if so, consider it to be the default redirect address. Otherwise, use the server's own successurl as the address that was redirected to when the login was successful.

Mysqlsessiondao

Persist the session to the MySQL database; Here you can implement it as storage to redis/memcached and so on, please refer to the session store/Persistence section in chapter tenth session management for Mysessiondao, exactly the same.

Mysqlsessionvalidationscheduler

It is identical to the Mysessionvalidationscheduler in the chapter section of Session validation in chapter tenth session management. If you use a db such as Redis that has an automatic expiration policy, you can simply take advantage of these DB expiration policies without implementing sessionvalidationscheduler.

remoteservice    Java code    public class remoteservice  implements remoteserviceinterface {        @Autowired   private  AuthorizationService authorizationService;        @Autowired    private SessionDAO sessionDAO;          public  Session getsession (String appkey, serializable sessionid)  {            return sessiondao.readsession (sessionId);        }       public serializable createsession (session  session)  {           return sessiondao.create ( session);   &nbs

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.