Justauth actual combat document – basic part

Time:2020-8-13

Justauth actual combat document - basic part

Justauth actual combat document

Just auth, as you can see, is only a tool class library for third-party login authorization. It can let us get rid of the tedious third-party login SDK and make the login so easy! This column will introduce in detail how to use justauth to realize third-party login and how to use the advanced features of justauth.

Initializing the project using springboot

Before the tutorial begins, we should prepare the corresponding software environment. JustAuth

Create a project in the following way under idea: ClickFile-New-ProjectThen select spring initializer and operate according to the prompts. Check when configuring the dependencyspring-boot-starter-webandlombokTwo dependencies. In order to facilitate development and testing, I have chosen one more herespring-boot-devtools

According to the prompt, the POM is obtained as follows

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.6.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>me.zhyd.justauth</groupId>
    <artifactId>justauth-tutorial</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>justauth-tutorial</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

After the project is compiled, we begin to formally integrate justauth.

➕ Add justauth dependency

Before you start, I suggest you take a look at justauth’s user documentation https://docs.justauth.whnb.wang Focus on getting started quickly.

Justauth actual combat document - basic part

This section contains information about OAuth and justauthimportantOnce again, it is recommended that the content of this chapter be viewed first.

Repeat it in three steps(These three steps are also suitable for any platform supported by justauth):

  1. Application for registration of developer account of third party platform
  2. Create the application of the third party platform and get the configuration information(accessKey, secretKey, redirectUri)
  3. Use this tool to realize authorized login

Of course, it doesn’t matter who comes first in the third and the first two steps. You can implement the code first and then apply for a third-party application, or you can apply for a third-party application first, and then integrate the code.

Next, we follow the first step in the documentation to add the POM dependency.

<dependency>
    <groupId>me.zhyd.oauth</groupId>
    <artifactId>JustAuth</artifactId>
    <version>1.15.1</version>
</dependency>

After the dependency is added, wait for the project to be compiled, and then we will officially access justauth.

➕ API integrating justauth

Note that in the following code, our request links are passed through dynamic parameters{source}It is convenient for us to integrate any platform. For example, when integrating gitee, our request address is: http://localhost : 8080 / OAuth / render / gitee, and the callback address is http://localhost :8080/oauth/callback/gitee。

Of course, the examples only show that you can use this method, but if you only need to integrate a single platform, you can directly{souce}Change to the platform name, such as gitee

package me.zhyd.justauth;

import me.zhyd.oauth.config.AuthConfig;
import me.zhyd.oauth.model.AuthCallback;
import me.zhyd.oauth.request.AuthGiteeRequest;
import me.zhyd.oauth.request.AuthRequest;
import me.zhyd.oauth.utils.AuthStateUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 *How to use justauth to realize the third party login
 *
 * @author yadong.zhang (yadong.zhang0415(a)gmail.com)
 * @version 1.0.0
 * @since 1.0.0
 */
@RestController
@RequestMapping("/oauth")
public class JustAuthController {

    /**
     *Get the authorization link and jump to the third party authorization page
     *
     * @param response response
     *Possible exceptions in @ throws IOException response
     */
    @RequestMapping("/render/{source}")
    public void renderAuth(HttpServletResponse response) throws IOException {
        AuthRequest authRequest = getAuthRequest();
        String authorizeUrl = authRequest.authorize(AuthStateUtils.createState());
        response.sendRedirect(authorizeUrl);
    }

    /**
     *After the user confirms the authorization (login) of the third-party platform, the third-party platform will redirect to the address, and carry the parameters such as code and state
     *
     *@ param callback
     *@ return user information of the third party platform
     */
    @RequestMapping("/callback/{source}")
    public Object login(AuthCallback callback) {
        AuthRequest authRequest = getAuthRequest();
        return authRequest.login(callback);
    }

    /**
     *Obtain authorization request
     *
     * @return AuthRequest
     */
    private AuthRequest getAuthRequest() {
        return new AuthGiteeRequest(AuthConfig.builder()
                .clientId("clientId")
                .clientSecret("clientSecret")
                .redirectUri("redirectUri")
                .build());
    }

}

Next, we need to go to gitee to create our OAuth application. After logging in to gitee, we click the user profile in the upper right corner, select settings, and then click the third-party application to enter the third-party application management page. Click the create application button in the upper right corner to enter the application creation page

Justauth actual combat document - basic part

Justauth actual combat document - basic part

We can fill in our application information according to the prompt.

Application Name:Generally, fill in your own website name

Application Description:Generally, fill in your own application description

App home page:Fill in the home page address of your website

Application callback address: a keyThe address is the address of the website that the user needs to jump to after authorization. It carries a code parameter by default

jurisdiction:According to the page prompt operation, the first one is selected by default, because we only need to obtain user information

After the above information is input, click OK to create the application. After the creation, click to enter the application details page, where you can see the application key and other information

Justauth actual combat document - basic part

Copy the following three messages:Client IDClient SecretandApplication callback address

➕ Custom HTTP tools

Get the configuration information from the previous stepAuthConfigAs follows:

private AuthRequest getAuthRequest() {
        return new AuthGiteeRequest(AuthConfig.builder()
                .clientId("4c504cd2e1b1dbaba8dc1187d8070adf679acab17b2bc9cf6dfa76b9ae06aadc")
                .clientSecret("fa5857175723475e4675e36af9eafde338545c1a0dfa49d1e0cc78f9c3ce5ebe")
                .redirectUri("http://localhost:8080/oauth/callback/gitee")
                .build());
    }

}

After the above work is completed, we directly launch the project and access it in the browser http://localhost : 8080 / OAuth / render / gitee. When the following page appears, it indicates that we have successfully integrated and have jumped to the third party’s authorization page.

Justauth actual combat document - basic part

Note that if you have not logged in your account in the browser, you will see the following page:

Justauth actual combat document - basic part

After we click “agree to authorize”, the third party application (gitee) will generate aCode authorization codeAnd we passed it on firststateCall back to our configuredredirectUriInterface.

Justauth actual combat document - basic part

As shown in the figure above, after entering the callback interface, we can trace the information returned by the third-party platform: state and code.

If you are a new project, a small problem may arise here:

2020-04-21 23:50:02 http-nio-8080-exec-4 me.zhyd.oauth.log.Log(error:45) [ERROR] - Failed to login with oauth authorization.
com.xkcoding.http . exception.SimpleHttpException : http implementation class not specified!
    at com.xkcoding.http.HttpUtil.checkHttpNotNull(HttpUtil.java:70)
    at com.xkcoding.http.HttpUtil.post(HttpUtil.java:119)
    at me.zhyd.oauth.request.AuthDefaultRequest.doPostAuthorizationCode(AuthDefaultRequest.java:213)
    at me.zhyd.oauth.request.AuthGiteeRequest.getAccessToken(AuthGiteeRequest.java:31)
    at me.zhyd.oauth.request.AuthDefaultRequest.login(AuthDefaultRequest.java:79)
    at me.zhyd.justauth.JustAuthController.login(JustAuthController.java:47)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:190)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:105)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:879)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:793)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1040)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:943)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:634)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:373)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1594)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:748)

This is because justhauth has integrated simple HTTP as the general HTTP interface by default since v1.14.0 (for the update, please refer to the official release of justhaut1.14.0! In view of the fact that the general projects have integrated HTTP tools, such as okhttp3 and Apache Httpclient and hutool http. Therefore, in order to reduce unnecessary dependency, justhauthor will not integrate hutool HTTP by default since v1.14.0. If the developer’s project is brand new or there is no integrated HTTP implementation tool in the project, the corresponding HTTP implementation class needs to be added. Justauth provides three alternative POM dependencies:

hutool-http

<dependency>
    <groupId>cn.hutool</groupId>
    <artifactId>hutool-http</artifactId>
    <version>5.2.5</version>
</dependency>

httpclient

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
      <artifactId>httpclient</artifactId>
      <version>4.5.12</version>
</dependency>

okhttp

<dependency>
  <groupId>com.squareup.okhttp3</groupId>
  <artifactId>okhttp</artifactId>
  <version>4.4.1</version>
</dependency>

After adding the HTTP tool dependency, restart the project and re access it http://localhost : 8080 / OAuth / render / gitee link and then authorize.

After authorization, you will see the following page:

Justauth actual combat document - basic part

Recommended Today

How to share queues with hypertools 2.5

Share queue with swote To realize asynchronous IO between processes, the general idea is to use redis queue. Based on the development of swote, the queue can also be realized through high-performance shared memory table. Copy the code from the HTTP tutorial on swoole’s official website, and configure four worker processes to simulate multiple producers […]