Source code analysis of social media login to spring social

Time:2020-8-25

In the last article, we introduced the oauth2 authorization standard, and focused on the authorization code authentication mode of oauth2. At present, the vast majority of social media platforms open their interfaces (login authentication and user information interface) through oauth2 authorization code authentication mode. However, we also see that oauth2 has certain complexity. If all the code is developed by ourselves, there will be a certain amount of work. Therefore, we can use spring social to help us. Spring social encapsulates oauth2 standard completely and friendly.
In this paper, through the spring social source code analysis, so that in the subsequent development of third-party media platform login authentication function, can be more clear.

1、 Source code analysis from the perspective of spring social structure

Spring social is a spring class library that helps us connect with social media platform and facilitate the development of third-party login authentication and other functions in our own applications. The core classes and interfaces are compared, as shown in the figure below. Let’s analyze them one by one.

First of all, let’s briefly review oauth2, which mainly includes two parts: authentication and authentication.

  • The authentication process is the process of obtaining the authorization code and exchanging the accesstoken through the user authorization. This process is the standard oauth2 authentication process, which is followed by all platforms and can be considered as consistent.
  • The authentication process is to carry the accesstoken to visit the API interface of social media platform. Of course, the users and services of each platform are different, so the interfaces provided are different.

If you are not familiar with this part of the content, first look back to my last article. Please understand the following text in combination with the picture below.

Source code analysis of social media login to spring social

1.1.oauth2 authentication source code

First of all, in the process of realizing oauth2 login authentication, there are many requests and responses between our own application and social media platform. Therefore, we need to encapsulate a class to handle the standard oauth2 authentication specific HTTP tool class. This can be said to be the most important work. Spring security has provided us with the oauth2operations interface. Its default implementation class is oauth2template. According to the implementation differences of different platforms, we may need to implement (fine tune) ourselves. During the authentication process, all the work that interacts with the oauth2 authentication server is handed over to oauth2 operations, and finally an accesstoken is returned to us.

Source code analysis of social media login to spring social
For developers, just tell oauth2 operations the values of the above four properties. As long as the service provider is strictly in accordance with the oauth2 standard development of authentication services, we do not need to deal with the rest of the process of interaction with the authentication server.

1.2. Interface resource authentication

After obtaining the accesstoken, we have the right to request the resources in the oauth2 resource server. Different social media platforms provide different interfaces according to different users and businesses. In this case, we need to use resttemplate and common HTTP tool class to process requests and responses. As can be seen from the figure, resttemplate will determine which class library to use according to the environment for processing various data formats such as JSON and XML.

Source code analysis of social media login to spring social
Since the business interfaces of each platform are different, we have to develop different interfaces to implement apiimpl. At this point, we should need a unified parent class, including accesstoken and resttemplate, so that our custom interface implementation can obtain and use accesstoken and resttemplate by inheriting this class. This unified parent class is called abstractoauth2binding. It also helps us to carry the parameters of HTTP requests, and to deserialize the request results to objects.

Source code analysis of social media login to spring social

So far, oauth2 operations and custom interface implement apiimpl, one responsible for authentication process request response, and the other responsible for resource request response. They are encapsulated as service provider service provider.
Source code analysis of social media login to spring social

1.3. Determine user relationship

By implementing the interface in the above code, the HTTP interaction process between our own application and social media platform (service provider) can be fully supported. However, there is another important step in developing social media login: determining the relationship between the user information responded by the social media platform and our own application users. We use a database table to represent this relationship, and it must be this table (special for spring social, which can be found in the spring social core package)

create table UserConnection (
    userId varchar(255) not null,
    providerId varchar(255) not null,
    providerUserId varchar(255),
    rank int not null,
    displayName varchar(255),
    profileUrl varchar(512),
    imageUrl varchar(512),
    accessToken varchar(512) not null,
    secret varchar(512),
    refreshToken varchar(512),
    expireTime bigint,
    primary key (userId, providerId, providerUserId));
create unique index UserConnectionRank on UserConnection(userId, providerId, rank);

In this table, the three most important fields are userid (unique ID of user for self-developed application), provider (unique ID of service provider and social media platform), and provideruserid (unique ID of service provider user). These three fields reflect the relationship between self-developed application users and service provider users, so as to determine whether the service provider users can log in to our application through oauth2 authentication. (the data in this table is added through the registration or binding operation, and has nothing to do with the authentication and authentication process.)

  • Through the interface in section 1.2, we can obtain the data user of social media users, but we have said that the structure of this user on different service provider platforms is completely different. However, spring social only knows one kind of data structure of users, that is connection (oauth2connection). So we need to adapt the two. Apiadapter is an interface, and the content needs to be implemented by ourselves.
  • Now we have the user information connection of spring social approved service provider, and then use connection to load the userid (the userid of our own platform). If it can be loaded into the userid (not empty), it means that the login authentication is successful.

Source code analysis of social media login to spring social

1.4. Local application authorization

By implementing the interface in the code above, we can get the userid, the unique ID of the user of our own application. It also means that using social media users to log in to our own application has been successful. However, there is another problem that has not been solved. It does not mean that you can access all the resources in the local application. So, we look up the current user based on the userid and empower him.

In our previous case of logging in with user name and password, we implemented the user details service and user details interface. In the process of social media login, the interfaces we need to implement are social user details service and social user details. In fact, the implementation principle is the same, that is, the user’s unique ID userid is used to load the permission information of the user’s role. At this point, spring security knows the user’s permission information and can effectively control its access rights.

Source code analysis of social media login to spring social

2、 Source code analysis from the perspective of spring social process

Spring social autoconfiguration adds a social authentication filter to the filter chain that blocks social media login requests.

Source code analysis of social media login to spring social
The address of the social media login request intercepted by the social authentication filter filter is {filterprocessesurl} / {providerid}. The default value of filterprocessesurl is / auth. If your service provider providerid (custom) is GitHub, the address requested by your social media login button should be / auth / GitHub. Of course, we can modify both values.

Source code analysis of social media login to spring social

It should be noted that {filterprocessesurl} / {providerid} is both the address of the authentication request and the callback address of the service provider in spring social. When the user clicks the “GitHub login” button, the access to / {filterprocessesurl} / {providerid} is blocked. At this time, the user is not authenticated, so the user jumps to the GitHub authorization page, the user enters the user password authorization, jumps back to the local application in the browser, and still returns to / {filterprocessesurl} / {providerid} again.

Source code analysis of social media login to spring social
First of all, it is necessary to detect whether the user is authorized to use the third-party platform user information, and if not, throw an exception directly. If the user is authorized, it will execute a series of request responses of oauth2 to obtain the authorization code, accesstoken and connection user information. This procedure code is defined in oauth2authenticationservice.

Source code analysis of social media login to spring social
For the authorization process in doauthentication, refer to sections 1.3 and 1.4. If the authorization fails (the social platform user has no corresponding user in the local application), it will jump to signupurl. Perform registration, that is, user relationship binding business logic.

Source code analysis of social media login to spring social

Note: in the oauth2 authentication process implemented by spring social, session is used (as shown in the sessionstrategy code in the figure above). So when your application is a stateless application, spring social needs to be reformed to a certain extent. But I never did. The simple way is: use session to develop stateful applications, and the status information saved by session is handed over to redis for centralized management; or before developing stateless applications, make sure that the application does not need social media login function, such as an enterprise intranet application.

Looking forward to your attention

  • Recommend to you a series of documents of bloggers: “teach you to learn spring boot series by hand – 16 chapters and 97 sections”
  • This article reprints to indicate the source (must take the link, cannot only turn the text): letter brother blog.