How to guarantee the security of calls between various micro services in Spring cloud

Source: Internet
Author: User
Tags auth oauth tojson
I. Background

Under the micro-service architecture, our system is broken down into a number of single service micro services based on business.

Each service has its own set of APIs to provide other service calls, so how to ensure security.

Not that you want to call can be invoked, must have a certification mechanism, is our internal services issued by the request before we can call our interface.

Need to pay attention to is that we are talking about micro-service calls between the security certification, not uniform in the API official website certification, the demand is not the same, API Gateway of the unified certification is linked to the business, our side is to prevent the interface by others casually call. two. Programme OAUTH2

Spring Cloud can use OAUTH2 to achieve unified authentication for multiple micro services

Obtain Access_token through centralized authentication and authorization to the OAUTH2 service

And this token is trusted by other micro-service, in the subsequent visit all bring the Access_token to pass, thus realizes the unified authentication authorization of the micro-service. JWT

JWT is a safety standard. The basic idea is to provide user name and password to the authentication server, the server verifies the legality of the user submitting information information; If the validation succeeds, it generates and returns a token that the user can use to access the protected resource on the server. Token

Feel that these 2 kinds of seems not much different ah, in fact, there is a difference: OAUTH2 is an authorization framework, JWT is an authentication protocol

Either way, remember to use HTTPS to secure your data. three. What kind of

I personally recommend the use of JWT, lightweight, simple, and suitable for distributed stateless applications

Use the OAUTH2 words on the point of trouble, various roles, authentication types, clients and so a lot of concepts four. How to use

First of all, create a generic authentication service that provides authentication operations and returns a token after successful authentication

@RestController @RequestMapping (value= "/oauth") public class Authcontroller {@Autowired private authservice auth

    Service; @PostMapping ("/token") public responsedata auth (@RequestBody authquery query) throws Exception {if (Stringuti Ls.isblank (Query.getaccesskey ()) | | Stringutils.isblank (Query.getsecretkey ())) {return Responsedata.failbyparam ("AccessKey and Secretkey NOT NULL
        ");
        User user = Authservice.auth (query);
        if (user = null) {return Responsedata.failbyparam ("Authentication failed");
        } jwtutils JWT = Jwtutils.getinstance ();
    Return Responsedata.ok (Jwt.gettoken (User.getid (). toString ())); @GetMapping ("/token") public responsedata OAuth (authquery query) throws Exception {if (STRINGUTILS.ISB Lank (Query.getaccesskey ()) | | Stringutils.isblank (Query.getsecretkey ())) {return Responsedata.failbyparam ("AccessKey and Secretkey NOT NULL
        "); } User User = AUthservice.auth (query);
        if (user = null) {return Responsedata.failbyparam ("Authentication failed");
        } jwtutils JWT = Jwtutils.getinstance ();
    Return Responsedata.ok (Jwt.gettoken (User.getid (). toString ())); }

}

JWT can add dependencies, and then write a tool class, it is recommended to write in the global package, all services are used, specific code please refer to: jwtutils

GitHub Address: HTTPS://GITHUB.COM/JWTK/JJWT

JWT provides a lot of encryption algorithms, I use RSA, is currently using a set of public key and private key, this approach is not good, because in case the secret key leaked, it is not safe, so the configuration center will be the way to dynamically manage the secret key.

The main logic in a class is to generate token, and then provide a way to check if the token is legitimate, and whether it expires, and so on.

<dependency>
    <groupId>io.jsonwebtoken</groupId>
    <artifactid>jjwt</ artifactid>
    <version>0.7.0</version>
</dependency>

The Unified authentication Service has, we only need to register the attestation service to the registration center can give other service to consume.

So how do we use just the authentication service to do the certification, the easiest way is to use the filter to deal with

For example, I now have a service fangjia-fsh-house-service, before anyone can invoke the interface I provided, and now I want to join the validation, only if the validation pass can let it call my interface

Then add a filter in the Fangjia-fsh-house-service to determine whether you have permission to call the interface, we get the authenticated token information from the request header, we don't need to rely on cookies

This filter I also suggest to write in the global project, because also all services are used, code please refer to: httpbasicauthorizefilter

The main logic is to obtain token and then through the jwtutils to verify whether legal, not legal to prompt, legal is let go

Here need to note that the decryption key must be encrypted with the same, or decryption must fail, is a bug

Verify that the token
if (! Stringutils.hastext (auth)) {
    PrintWriter print = Httpresponse.getwriter ();
    Print.write (Jsonutils.tojson (responsedata.fail) ("Illegal request" lacks authorization information "", 
                 responsecode.no_auth_ Code.getcode ()));
    return;
}
Jwtutils.jwtresult JWT = Jwtutils.checktoken (auth);
if (!jwt.isstatus ()) {
    PrintWriter print = Httpresponse.getwriter ();
    Print.write (Jsonutils.tojson (Responsedata.fail (Jwt.getmsg (), Jwt.getcode ()));
    return;
}
Chain.dofilter (HttpRequest, response);

By this step, as long as the caller has passed through the authentication service after the token, and then into the request header authorization, you can invoke other services that require authentication.

This looks like a perfect, but not easy to use it, each call before you need to go to the certification, and then plug the request head, how to do general-purpose, do not need specific developers to care, transparent to the user, the next article, we continue to explore how to achieve a convenient call.

The specific code can refer to my github:

Https://github.com/yinjihuan/spring-cloud

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.