Detailed process and implementation of Github third party login

Keywords: Programming github JSON OkHttp Spring

1, Flow chart

2, Specific implementation steps

I. create OAuth App

  1. First of all, we need to create an OAuth App. Click according to the steps below

  1. Fill in the information in turn, and then click Register application

  1. Then we can see that an id and password will be generated, which will be used later. Try not to let others see it (I'm here for testing, and I will delete it later)

II. Write background code. I use Spring Boot here

  1. Write a hyperlink as a login button and two entity classes
<a href="https://GitHub. COM / login / OAuth / authorize? Client? Id = your client? ID & redirect? URI = http: / / localhost: 8080 / callback & state = 1 "> login</a>
public class AccessTokenDto {
    private String client_id; //Client ID.
    private String client_secret; //Client key
    private String code; //Code received as a response to step 1.
    private String redirect_uri; //URL sent by the user in the application after authorization
    private String state; //Unpredictable random string provided in step 1
    //Omit getter setter
}
public class GithubUser {
    private Long id;
    private String name;
    private String bio;
    //Omit getter setter
}
  1. Controller
@Controller
public class AuthoriseController {

    @Autowired
    private GithubProvider githubProvider;

    @Autowired
    private GithubParams githubParams;

    @GetMapping("/callback")
    public String callback(@RequestParam("code") String code,
                           @RequestParam("state") String state){
        AccessTokenDto accessTokenDto = new AccessTokenDto();
        accessTokenDto.setClient_id(githubParams.getClient_id());
        accessTokenDto.setClient_secret(githubParams.getClient_secret());
        accessTokenDto.setCode(code);
        accessTokenDto.setRedirect_uri(githubParams.getRedirect_uri());
        accessTokenDto.setState(state);
        //Get access_token
        String access_token = githubProvider.getAccessToken(accessTokenDto);
        //Get user information according to accessToken
        GithubUser githubUser = githubProvider.getGithubUser(access_token);
        System.out.println(githubUser.getName());

        return "index";
    }
}
  1. You need to import two maven dependencies
<!--Introduce OKHTTP,Send request-->
<dependency>
    <groupid>com.squareup.okhttp3</groupid>
    <artifactid>okhttp</artifactid>
    <version>3.6.0</version>
</dependency>

<!--Introduce fastjson-->
<dependency>
    <groupid>com.alibaba</groupid>
    <artifactid>fastjson</artifactid>
    <version>1.2.62</version>
</dependency>
  1. GithubProvider (for access_token and user information)
@Component
public class GithubProvider {
    @Autowired
    private GithubParams githubParams;

    /**
     * Get AccessToken
     */
    public String getAccessToken(AccessTokenDto accessTokenDto) {
        OkHttpClient client = new OkHttpClient();
        MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
        //Convert accessTokenDto to json string passed in parameter
        RequestBody body = RequestBody.create(mediaType, JSON.toJSONString(accessTokenDto));
        Request request = new Request.Builder()
                .url(githubParams.getToken_uri())
                .post(body)
                .build();
        try (Response response = client.newCall(request).execute()) {
            String str = response.body().string();
            //What we get is a string like this. We need to split it, as long as the access_token part
            //access_token=9566ba3483a556c610be42d44338f3fd16a3b8d1&amp;scope=&amp;token_type=bearer
            return str.split("&amp;")[0].split("=")[1];
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * Get user information according to access_token
     */
    public GithubUser getGithubUser(String access_token) {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(githubParams.getUser_uri() + "?access_token=" + access_token)
                .build();

        try (Response response = client.newCall(request).execute()) {
            //You get the json string, so you need to convert it to the GithubUser object
            return JSON.parseObject(response.body().string(), GithubUser.class);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
  1. GithubParams, configuration parameters
@Component
@ConfigurationProperties(prefix = "github")
public class GithubParams {

    private String client_id;
    private String client_secret;
    private String redirect_uri;
    private String token_uri;
    private String user_uri;
    //Omit getter setter
}
  1. Configuration file application.properties
server.port=8087
github.client_id=You generated id
github.client_secret=Your generated password
github.redirect_uri=http://localhost:8887/callback
github.token_uri=https://github.com/login/oauth/access_token
github.user_uri=http://localhost:8887/callback

3, Operation effect

github access is a little slow, please wait patiently

Look at your console. Normally, it will output the name of your Github setting

Four. Literature

Reference resources: Github official documents

Posted by labmixz on Fri, 14 Feb 2020 07:35:57 -0800