Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to implement single sign-on Single Sign On in java

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

Editor to share with you how to achieve single sign-on Single Sign On in java. I hope you will get something after reading this article. Let's discuss it together.

Demand

In multiple application systems, users only need to log in once to access all applications that trust each other.

Website An and website B are related services of the same company. Now requires that users as long as one of the sites to log in, and then visit another website will automatically log in, how to achieve?

Key points involved:

This involves cross-domain authentication and front-end page JavaScript cross-domain issues.

I. Cross-domain authentication

Internet service is inseparable from user authentication. The general procedure is as follows.

The user sends the account and password to the server

After the authentication of the server is passed, save the relevant data, such as user role, user ID, etc., in the current session (session).

The server returns a session_id to the user and writes to the user cookie

Every subsequent request from the user will send the session_id back to the server through Cookie

The server receives the session_id, finds the previously stored data, and knows the identity of the user.

Here is an example of logging in to site An and visiting site B

Option 1: session persistence

Persist session data and write it to a database or other persistence layer. When various services are requested, they request data from the persistence layer.

In this scheme, the amount of code change for all kinds of systems is small, as long as it is judged in the place of permission verification.

A login success code

After logging in successfully, store the session to Redis persistent storage, and pay attention to setting the validity period

Tip:

Redis saves data in hierarchical form and directory form, up to four levels, in the following format:

Set ('dir:dir:dir:key',' value')

/ * Storage Session to Redis * @ param boolean $logout whether to exit login default No * @ return array * / public function sessionToRedis ($logout = false) {try {if ($logout) {(new Redis ())-> del ('Admin:session:'. Session_id ();} else {$userInfo = session ('CH_ADMIN_LOGIN_STATUS'); $res = (new Redis ())-> setex (' Admin:session:'. Session_id (), 28800, json_encode ($userInfo, JSON_UNESCAPED_UNICODE); if ($res = false) throw new\ Exception ('Redis storage failed'); return true;}} catch (\ Exception $e) {return false;}}

Visit B and B for user authentication after a successful login

Note that the link URL that accesses B at this time should carry the parameter sessionid!

When processing request-authentication, B first parses whether the sessionid parameter is carried, then queries the redis for the relevant data, and saves the data to the current session. At this point, you have successfully logged in to B.

/ * pass session_id (for session sharing) * / $params = $request- > param () via other background single sign-on * /! empty ($params) & & isset ($params ['session_id']) {session_id ($params [' session_id']); / / set session id$userInfo = Session::get ('userinfo',' admin') If (empty ($userInfo)) {$userInfo = json_decode ((new Redis ())-> get ('Admin:session:'.$params [' session_id']), true); Session::set ('userinfo', $userInfo,' admin');} else {$userInfo = Session::get ('userinfo',' admin');} scenario 2: JWT (JSON Web Token)

The server simply does not save the session data, the "user data" is encrypted and saved to the "client", and each request sends the data back to the server, and the server parses to get the user identity information data. JWT is a representative of this kind of scheme.

JWT principle

After the server is authenticated, a JSON object is generated and sent back to the user, as shown below.

{"name": "Zhang San", "role": "Administrator", "expiration time": "00:00 on October 1st, 2019"}

In the future, when the user communicates with the server, the JSON object will be sent back. The server relies entirely on this object to identify the user. To prevent users from tampering with data, the server will add a signature when generating this object (see later).

The server does not save any session data, that is, the server becomes stateless, making it easier to extend.

Data structure of JWT

It is a long string separated into three parts by a dot (.). Note that there is no line wrapping inside the JWT, and it is written into a few lines just for presentation purposes.

The three parts of JWT are as follows.

Header (head)

Payload (load)

Signature (signature)

Write it on a line, and that's what it looks like.

Header.Payload.Signature

Header

The Header part is a JSON object that describes the metadata of the JWT, usually like this.

{"alg": "HS256", "typ": "JWT"}

In the above code, the alg attribute represents the signature algorithm (algorithm), and the default is HMAC SHA256 (written as HS256); the typ attribute indicates the type of the token (type), and the JWT token is written as JWT.

Finally, the above JSON object is converted to a string using the Base64URL algorithm (see later).

Payload

The Payload part is also a JSON object that holds the data that actually needs to be passed. JWT specifies seven official fields to choose from.

Iss (issuer): issuer

Exp (expiration time): expiration time

Sub (subject): topic

Aud (audience): audience

Nbf (Not Before): effective time

Iat (Issued At): time of issue

Jti (JWT ID): number

In addition to official fields, you can also define private fields in this section. Here is an example.

{"sub": "1234567890", "name": "John Doe", "admin": true}

Note that JWT is unencrypted by default and can be read by anyone, so don't put secret information in this section.

This JSON object is also converted to a string using the Base64URL algorithm.

Signature

The Signature part is the signature of the first two parts to prevent data tampering.

First, you need to specify a key (secret). This key is known only to the server and cannot be disclosed to the user. Then, using the signature algorithm specified in Header (default is HMAC SHA256), generate the signature according to the following formula.

HMACSHA256 (base64UrlEncode (header) + "." + base64UrlEncode (payload), secret)

After calculating the signature, the three parts Header, Payload, and Signature are put together into a string. Each part is separated by a "dot" (.), and it can be returned to the user.

Base64URL

As mentioned earlier, the algorithm for serialization of Header and Payload is Base64URL. This algorithm is basically similar to the Base64 algorithm, but with some small differences.

JWT, as a token, may be put into URL in some situations (such as api.example.com/?token=xxx). Base64 has three characters +, / and =, which have a special meaning in URL, so they have to be replaced: = is omitted, + is replaced with -, / is replaced with _. This is the Base64URL algorithm.

How to use JWT

The client receives the JWT returned by the server, which can be stored in Cookie or localStorage.

Since then, the client will bring this JWT with it every time it communicates with the server. You can send it automatically in Cookie, but it's not cross-domain, so it's better to put it in the header Authorization field of the HTTP request.

Authorization: Bearer

Alternatively, when crossing domains, the JWT is placed in the data body of the POST request.

Several characteristics of JWT

(1) JWT is not encrypted by default, but it can also be encrypted. After the original Token is generated, it can be encrypted again with the key.

(2) if JWT is not encrypted, secret data cannot be written to JWT.

(3) JWT can be used not only for authentication, but also for exchanging information. Effective use of JWT can reduce the number of times the server queries the database.

(4) the biggest disadvantage of JWT is that because the server does not save the session state, it cannot abolish a token or change the permissions of token during use. That is, once the JWT is signed, it will remain valid until it expires, unless the server deploys additional logic.

(5) JWT itself contains authentication information, and once disclosed, anyone can get all the permissions of the token. To reduce embezzlement, the validity period of JWT should be set to be short. For some of the more important permissions, users should be authenticated again when using them.

(6) in order to reduce embezzlement, JWT should not use HTTP protocol for clear code transmission, but should use HTTPS protocol for transmission.

II. JavaScript cross-domain

Single sign-on will inevitably encounter the cross-domain problem of JS between windows, and the solution at this time is postMessage

PostMessage is the API in HTML5 XMLHttpRequest Level 2 and is one of the few window attributes that can operate across domains. It can be used to solve problems in the following areas:

A.) data transfer between the page and the new window it opens

B.) message passing between multiple windows

C.) Page and nested iframe messaging

D.) Cross-domain data transfer in the above three scenarios

Usage: the postMessage (data,origin) method accepts two parameters

The data: html5 specification supports any basic type or replicable object, but some browsers only support strings, so it's best to serialize parameters with JSON.stringify () when passing parameters.

Origin: protocol + host + port number, which can also be set to "*" to indicate that it can be passed to any window, or "/" if you want to specify the same origin as the current window.

1.) a.html: (http://www.domain1.com/a.html)

Var iframe = document.getElementById ('iframe'); iframe.onload = function () {var data = {name:' aym'}; / / transfer cross-domain data iframe.contentWindow.postMessage (JSON.stringify (data), 'http://www.domain2.com');}) to domain2 / / accept domain2 return data window.addEventListener ('message', function (e) {alert (' data from domain2-- >'+ e.data);}, false)

2.) b.html: (http://www.domain2.com/b.html)

/ / receive domain1 data window.addEventListener ('message', function (e) {alert (' data from domain1-- >'+ e.data); var data = JSON.parse (e.data); if (data) {data.number = 16; / / send back domain1 window.parent.postMessage (JSON.stringify (data), 'http://www.domain1.com');) after processing }, false); after reading this article, I believe you have a certain understanding of "how to achieve single sign-on Single Sign On in java". If you want to know more about it, welcome to follow the industry information channel, thank you for reading!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report