github Certified Logon

Keywords: Java github JSON less OkHttp

Use github OAuth for user login

When doing the login function, you are allowed to use the identity of a third-party website, which is called "third-party login".

principle

Authentication methods within github

Apply for OAuth App on github, go to your personal Github homepage, Settings->Applications->Developer applications->Register a new application

 

 

The purpose of registering this app is: You can enable other users to authorize your OAuth App.

You can have other users authorize your OAuth application.

Get code and state

<a href="https://github.com/login/oauth/authorize?Client_id=1d1f99e3efc33edcbf45&redirect_uri=http://localhost:8080/callback&scope=user&state=1">Login</a>

The scope property lists the range that the user grants to attach to the token.Typically, these scopes will be the same as the ones you require.However, users can edit their scope to effectively grant your application less access than you originally requested.In addition, users can edit the token scope after the OAuth stream is complete.You should be aware of this possibility and adjust the application's behavior accordingly.

It is important to address errors where users choose to grant you less access than you originally requested.For example, an application can warn its users or otherwise communicate with them that functionality will be reduced or that certain operations cannot be performed.

In addition, applications can always send users back to the process again to gain additional privileges, but don't forget that users can always refuse.

client_id is the one registered with, redirect_uri is the callback address you wrote, access this address to get a token

Name Type Description
client_id string Required. The client ID you received from GitHub when you registered is required.Client ID received from GitHub at registration.
redirect_uri string The URL in your application where users will be sent after authorization. See details below about redirect urls application, which the user will send after authorization.See the following for more information about redirecting urls.
login string Suggests a specific account to use for signing in and authorizing the app.It is recommended that you use a specific account to log in and authorize the application.
scope `string A space-delimited list of ranges.If no scopes are provided, the scopes default to an empty list for users who have not authorized any scopes for the application.For users who have already authorized scopes for the application, the OAuth authorization page with a list of scopes will not be displayed.Instead, this step of the stream is automatically completed using the set of scopes authorized by the user for the application.For example, if a user has executed a web stream twice and authorized one token with user scope and another with buyback scope, the third web stream does not provide sc
state string An unguessable random string. It is used to protect against cross-site request forgery attacks. Unguessable random string.It is used to prevent cross-site Request Forgery attacks.
allow_signup string Whether or not unauthenticated users will be offered an option to sign up for GitHub during the OAuth flow. The default is true. Use false in the case that a policy prohibits signups. Whether an option to register GitHub will be provided to unauthenticated users during the OAuth flow.The default value is true.Use false if registration is prohibited by policy.

Get AccessToken from httpclient by getting code and state

The java code callback interface is as follows:

 
   @Value("${github.client.id}")
     private String id;
     @Value("${github.client.secret}")
     private String secret;
     @Value("${github.redirect.uri}")
     private String uri; 
     @RequestMapping("/callback")
     public String callback(@RequestParam(name = "code") String code,
                            @RequestParam(name = "state") String state,
                            HttpServletResponse response) {
         //Through a DTO Object Encapsulation,Received code state
         AccessTokenDTO accessTokenDTO = new AccessTokenDTO();
         accessTokenDTO.setCode(code);
         accessTokenDTO.setClient_id(id);
         accessTokenDTO.setClient_secret(secret);
         accessTokenDTO.setState(state);
         accessTokenDTO.setRedirect_uri(uri);
         //obtain github Data Returned code + Client Secret+Client id To get token
         String accessToken = githubProvider.getAccessToken(accessTokenDTO);
         //Encapsulate an object by parsing
         GithubUser githubUser = githubProvider.getUser(accessToken);
             if (githubUser != null) {
                 //Write to database
        
             }
             //login success
             //  request.getSession().setAttribute("user",githubUser);
             return "redirect:/";
         } else {
           
             return "redirect:/";
         }

 

Access github again using the acquired AccelessToken to get user information

The githubprovider code is as follows:

 
 public String getAccessToken(AccessTokenDTO accessTokenDTO) {
       //Set from GitHub The data you get there is set to josn format
         MediaType mediaType = MediaType.get("application/json; charset=utf-8");
         OkHttpClient client = new OkHttpClient();
         //adopt okhttclient To get github User information passed in,To utilize AceessTokenDTO Data within!
          //To be passed accesstokendto translate into json format,adopt post Form passed to github
         RequestBody body = RequestBody.create(mediaType, JSON.toJSONString(accessTokenDTO));
         Request request = new Request.Builder()
                 .url("https://github.com/login/oauth/access_token")
                 .post(body)
                 .build();
         try (Response response = client.newCall(request).execute()) {
             String string = response.body().string();
             //Pass it over token analysis
             String token = string.split("&")[0].split("=")[1];
             return token;
         } catch (Exception e) {
             //log.error("getAccessToken error,{}", accessTokenDTO, e);
         }
         return null;
     }
 ​
     public GithubUser getUser(String accessToken) {
         //By token Obtain user
         OkHttpClient client = new OkHttpClient();
         Request request = new Request.Builder()
                 .url("https://api.github.com/user?access_token=" + accessToken)
                 .build();
         try {
             Response response = client.newCall(request).execute();
             String string = response.body().string();
             //encapsulation
             GithubUser githubUser = JSON.parseObject(string, GithubUser.class);
             //System.out.println(string);
             return githubUser;
         } catch (Exception e) {
            // log.error("getUser error,{}", accessToken, e);
         }
         return null;
     }

 

The following json is obtained:

 //encapsulation
 JSON.parseObject(string, GithubUser.class);
 

 {
     "login": "Diamondtest",
     "id": 28478049,
     "avatar_url": "https://avatars0.githubusercontent.com/u/28478049?v=3",
     "gravatar_id": "",
     "url": "https://api.github.com/users/Diamondtest",
     "html_url": "https://github.com/Diamondtest",
     "followers_url": "https://api.github.com/users/Diamondtest/followers",
     "following_url": "https://api.github.com/users/Diamondtest/following{/other_user}",
     "gists_url": "https://api.github.com/users/Diamondtest/gists{/gist_id}",
     "starred_url": "https://api.github.com/users/Diamondtest/starred{/owner}{/repo}",
     "subscriptions_url": "https://api.github.com/users/Diamondtest/subscriptions",
     "organizations_url": "https://api.github.com/users/Diamondtest/orgs",
     "repos_url": "https://api.github.com/users/Diamondtest/repos",
     "events_url": "https://api.github.com/users/Diamondtest/events{/privacy}",
     "received_events_url": "https://api.github.com/users/Diamondtest/received_events",
     "type": "User",
     "site_admin": false,
     "name": null,
     "company": null,
     "blog": "",
     "location": null,
     "email": null,
     "hireable": null,
     "bio": null,
     "public_repos": 0,
     "public_gists": 0,
     "followers": 0,
     "following": 0,
     "created_at": "2017-05-06T08:08:09Z",
     "updated_at": "2017-05-06T08:16:22Z"
 }

 

After authorization, you do not need to re-authorize each login. You can change your browser or choose revoke all user tokens!

Use case and introduction of okhttpclient

introduce

OkHttp is an HTTP client and is efficient by default:

  • http/2 supports allowing all requests to the same host to share sockets.

  • Connection pooling can reduce request latency if HTTP/2 is unavailable.

  • Transparent GZIP reduces download size.

  • Response caching completely avoids duplicate requests from the network.

     

 OkHttpClient client = new OkHttpClient();
 //Obtain URL
 //Visit URL And get the string returned from the website
 String run(String url) throws IOException {
   Request request = new Request.Builder()
       .url(url)
       .build();
 ​
   try (Response response = client.newCall(request).execute()) {
     return response.body().string();
   }
 }
 

 public static final MediaType JSON
     = MediaType.get("application/json; charset=utf-8");
 ​
 OkHttpClient client = new OkHttpClient();
 //Send to server
 //adopt build One request And encapsulate the required parameters into body Visit url,implement client.newCall(request).execute(),Get Return Value,Generally one json Format string,You can also choose its return data format by yourself!
 String post(String url, String json) throws IOException {
   RequestBody body = RequestBody.create(json, JSON);
   Request request = new Request.Builder()
       .url(url)
       .post(body)
       .build();
   try (Response response = client.newCall(request).execute()) {
     return response.body().string();
   }
 }

 

See: okhttp

githubdeveloper manual

Posted by MishaPappa on Thu, 26 Sep 2019 20:01:05 -0700