github certified landing

Use github OAuth implement user login

When do sign-on feature, allowing the use of the identity of a third-party website, which is called "Sign in."

principle

The authentication method in github

OAuth App application on github, enter the individual's Github home, Settings-> Applications-> Developer applications-> Register a new application

 

 

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

You can let other users of OAuth to authorize your 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">登陆</a>

scopeAttribute lists ranges granted to the user attached to the token. Typically, these will be the same range and scope of your request. However, users can edit their range, thus effectively granting your application access to your less than originally requested permissions. Further, the user can complete edit token stream in scope OAuth. You should be aware of this possibility, and adjust the behavior of the application accordingly.

Processing selected by the user grants you access to very less important than the error condition of permission you originally requested. For example, an application can warn their users or otherwise communicate with their users, informing them feature will reduce or unable to perform certain operations.

In addition, the application can always be sent back to the user process again to obtain additional privileges, but do not forget the user can always refuse.

client_id is registered to that, redirect_uri is that you write the callback address to get a token by visiting this address

Name Type Description
client_id string The Required . At The Client ID you Received from the when you GitHub Registered necessary. Registration received from the client GitHub end ID.
redirect_uri string The URL in your application where users will be sent after authorization. See details below about redirect urls application URL, the user will be sent to the URL after authorization. See below for more information on the redirect url.
login string Suggests a specific account to use for signing in and authorizing the app. Is recommended to use a specific account to log on and authorized applications.
scope `string Space-separated list of ranges. If you do not provide scope for the user does not authorize any scope for the application, the scope defaults to an empty list. For the user has authorized the scope for the application, OAuth authorization does not display the page with the scope of the list. In contrast, this step will flow using the user application authorization range set automatically. For example, if the user has performed two web stream, and authorized user with a token and the other token has a range repurchase range, the third flow does not provide web sc
state string An unguessable random string. It is used to protect against cross-site request forgery attacks. Random string can not guess. It is used to prevent cross-site request forgery attacks.
allow_signup string By Will or not the Users unauthenticated model types within Offered BE AN Sign up for the Option to GitHub During Flow at The OAuth. At The default IS true. The Use falsein at The Case A Policy that prohibits signups. During the OAuth flow, will provide a user is unauthenticated registration GitHub options. The default value is true. In the case of using a false policy prohibits registration.

By code and state acquisition, use httpclient to get AccessToken

java code callback interfaces 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) {
         //通过一个DTO对象封装,Code state received new new
         AccessTokenDTO accessTokenDTO =AccessTokenDTO (); 
         accessTokenDTO.setCode (code); 
         accessTokenDTO.setClient_id (ID); 
         accessTokenDTO.setClient_secret (Secret); 
         accessTokenDTO.setState (State); 
         accessTokenDTO.setRedirect_uri (URI); 
         // get the data back pass github code + Client Secret + Client id to get token 
         String accessToken = githubProvider.getAccessToken (accessTokenDTO);
          // parse encapsulated into an object 
         githubUser githubUser = githubProvider.getUser (accessToken);
              IF (! githubUser = null ) {
                  // write to the database 
        
             } 
             / /login success
             //  request.getSession().setAttribute("user",githubUser);
             return "redirect:/";
         } else {
           
             return "redirect:/";
         }

 

AccessToken get use to access github over again to get the user information

Wherein githubprovider code is as follows:

 
 public String getAccessToken (AccessTokenDTO accessTokenDTO) {
        // set GitHub where the setting data obtained from the format to a josn 
         the MediaType mediaType = MediaType.get ( "file application / JSON; charset = UTF-. 8" ); 
         OkHttpClient Client = new new OkHttpClient ();
          / / acquired github pass over the user information okhttclient, to use the data in the AceessTokenDTO!
           // will pass over into accesstokendto json format, transmitted via the post github form 
         requestBody body = RequestBody.create (mediaType, JSON.toJSONString (accessTokenDTO)); 
         the Request Request = new 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();
             //把传过来的token解析
             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) {
         //通过得到的token获取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();
             //封装
             GithubUser githubUser = JSON.parseObject(string, GithubUser.class);
             //System.out.println(string);
             return githubUser;
         } catch (Exception e) {
            // log.error("getUser error,{}", accessToken, e);
         }
         return null;
     }

 

json content acquisition are as follows:

 //封装
 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, do not need to authorize each landing again, you can replace the browser or select revoke all user tokens on it!

okhttpclient use cases and Introduction

Introduction

OkHttp is an HTTP client, default is efficient:

  • http / 2 support allows all requests to the same host shared socket.

  • Reduction request latency connection pool (if HTTP / 2 is not available).

  • Transparent GZIP reduce download size.

  • Caching the network in response to completely avoid duplicate requests.

     

Client = OkHttpClient new new OkHttpClient ();
  // get URL
  // access the site URL and get returns over a string 
 String RUN (String url) throws IOException { 
   Request Request = new new Request.Builder () 
       .url (url) 
       .build (); 
   the try (the Response Response = client.newCall (Request) .execute ()) {
      return response.body () String ();. 
   } 
 } 
 

 public  static  Final the MediaType the JSON
      = MediaType.get ( "file application / JSON; charset . 8-UTF = " ); 
 OkHttpClient Client =new new OkHttpClient ();
  // send to the server
  // package body to build an access request url parameter and the required execution client.newCall (request) .execute (), return value, it is typically a character format json string, of course, can choose its return data format! 
 String POST (URL String, String JSON) throws IOException { 
   requestBody body = RequestBody.create (JSON, the JSON); 
   the Request Request = new new Request.Builder () 
       .url (URL ) 
       .post (body) 
       .build (); 
   the try (the Response Response = client.newCall (Request) .execute ()) {
      return response.body () String ();. 
   } 
 }

 

For details, see: okhttp

githubdeveloper manual

Guess you like

Origin www.cnblogs.com/awsljava/p/11596077.html