3

The old Spring Security OAuth2 has been out of maintenance for some time, and 99% of Spring Cloud microservice projects are still using these old systems, which are seriously out of date. Many students are looking for new solutions, and even remember the password mode. The fat brother also wrote an article on the solution before. It seems that it is still not enough. Blessed are the students who read this article today, and the problem will be solved here.

Program

At present, this should be the latest solution in the Spring ecosystem, and there is no one. Let's look at the process first. Other components unrelated to microservices are shielded here first, leaving several components in the figure:

The detailed process is :

  • ① The user requests the gateway to log in or requests the resources of the resource server through the gateway.
  • ② The gateway finds that the user is not authorized to initiate the OIDC process based on the OAuth2 authorization code, and initiates an authorization request to the authorization server Id Server .
  • ③ The authorization server Id Server receives the authorization request and redirects it to the user login page to request user login authentication to initiate authorization.
  • ④ The user enters the user name and password for login authentication.
  • ⑤ The Id Server authorization server processes user authentication and redirects to the OAuth2 Redirect URI agreed by the gateway. This process belongs to the standard OIDC authorization code process.
  • ⑥ The gateway obtains AccessToken and IdToken :

    • Redirect to / if login was originally initiated.
    • If the initial request is for a resource server resource, the token is relayed and redirected to the corresponding resource.
  • The resource server responds to the user's request through two links ⑦⑧.

Please note that the AccessToken and IdToken generated in the above process are not allowed to be provided to the user side, otherwise it will cause a man-in-the-middle attack. By default, a cookie policy is provided. In most cases, this policy is sufficient. If you need to customize it, you must For a deep understanding of the mechanics, you can learn from my Spring Security OAuth2 column .

Implementation

According to the above scheme, we need three applications, namely gateway Spring Cloud Gateway application, resource server application Resource Server and OAuth2 authorization server Id Server .

Spring Cloud Gateway

Spring Cloud Gateway application, port 8080 , it is not only a gateway but also an OAuth2 client registered with the authorization server Id Server , through which you can complete the configuration in one minute. It requires configuration of routing rules and token relay capabilities to the resource server. The core configuration is:

 spring:
  application:
    name: gateway
  security:
    oauth2:
      client:
        registration:
          # 这里为客户端名称可自行更改
          gatewayclient:
            client-id: e4da4a32-592b-46f0-ae1d-784310e88423
            # 密码为注册客户端时的密码
            client-secret: secret
            # 只能选择一个
            redirect-uri: http://127.0.0.1:8080/login/oauth2/code/gatewayclient
            # 其它两种方式为refresh_token,client_credentials
            authorization-grant-type: authorization_code
            client-authentication-method: client_secret_basic
            scope: message.write,userinfo,message.read,openid
        provider:
          gatewayclient:
            # 要保证授权服务器地址可以被客户端访问
            issuer-uri: http://localhost:9000
  cloud:
    gateway:
      routes:
        - id: resource-server
          uri: http://127.0.0.1:8084
          predicates:
            - Path=/res/**
          filters:
            - TokenRelay

Resource Server

The resource server is the server of the business interface we usually write. The port is defined here as 8084 , which needs to integrate Spring Security and its Resource Server components. It is responsible for defining access rights to resource interfaces, such as:

 // 只有message.read才有资格访问资源/res/foo
        httpSecurity.authorizeRequests()
                .antMatchers("/res/foo").hasAnyAuthority("SCOPE_message.read")

In addition, it also needs to communicate with the authorization server Id Server to obtain the decoding public key of the AccessToken :

 spring:
  security:
    oauth2:
      resourceserver:
        jwt:
          jwk-set-uri: http://localhost:9000/oauth2/jwks

The principle of obtaining the decoded public key is described in detail in my Spring Security OAuth2 column , and will not be repeated here.

Id Server

Warehouse address: https://github.com/NotFound403/id-server Welcome to star, welcome to contribute.

Id Server is an open source authorization server based on Spring Authorization Server . It greatly reduces the difficulty of learning and using OAuth2 authorization server, provides UI console, dynamic permission control, convenient OAuth2 client management, and can generate Spring Security configuration with one click, out of the box Ready to use, can be deployed with a few configuration modifications, the code is open source, convenient for secondary development, and supports four client authentication methods and three authorization modes of OAuth2 . It is an important part of the current Spring security ecosystem, and it is also the future technology development trend. For more information, please refer to the introduction of the Id Server project repository .

Id Server plays the role of OAuth2 authorization server in this article, which is responsible for processing authorization requests, maintaining client registration information, and authorizing user information. IDP support will be added later, and users who log in from various three parties can also log in dynamically here. like this:

联合登录

According to business needs, third-party OAuth2 authorized login can also be accessed elegantly. Of course, the login method of access requires the support of OIDC or OAuth2 .

DEMO and how to use it

The above complete DEMO is under samples in the warehouse of Id Server . Instructions:

  • Pull the Id Server project and load the dependencies.
  • In IntelliJ IDEA , right-click the right-click menu and select Add As Maven Project for all projects in the pom.xml samples . This step is very important.
  • Start the three projects of Id Server , gateway , and resource-server in turn.

test login

  • Browser access http://127.0.0.1:8080/login , click http://localhost:9000 .
  • Enter the username and password user/user .
  • Being able to view the authentication information proves success. Again, this information is very sensitive in production and should not be exposed directly to the front end.
  • Browser access http://127.0.0.1:8080/res/foo , you can access the resources of the resource server.

another test

Close the browser and reopen it, visit the browser http://127.0.0.1:8080/res/foo , and see what happens?

Summarize

Through the linkage of OAuth2 client, Spring Cloud Gateway , OAuth2 authorization server, and OAuth2 resource server, you will find that authorization code mode can also realize complete microservice authentication and authorization, and it is more secure than password mode. After the Id Server implements federated login, other third-party logins can also be seamlessly integrated. Pay more attention, more advanced black technology is waiting for you.

关注公众号:Felordcn 获取更多资讯

Personal blog: https://felord.cn


码农小胖哥
3.8k 声望8k 粉丝