githubのアカウントのログイン認証を達成Springboot

githubのアカウントのログイン認証を達成Springboot

まず、準備作業

公式サイト次のドキュメント:

新しいアプリを作成します。

APPを許可

okhttp使用

次のようにAPPが公式文書の読み取りが許可し、タイミング図を合計しました:

第二に、戦闘

新しい承認APPを作成します。1.

ホームにgithubのは、個々のトップの右側の中央に、ドロップダウンメニューをクリックし、[設定]> [開発者設定] - > [OAuthのApps->新規のOAuthアプリケーションを入力します。

新しいアプリの後のような認可は、我々は我々だけで構築されたアプリケーションを持っていることを確認できます。

それにクリックすると、クライアントIDとクライアントシークレットを見ることができます:

2.使用springbootプロジェクトは、アカウント認証をシミュレートします

次のように新しいプロジェクト、導入okhttp、fastjson、依存パッケージ構成をSpringboot:

<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </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>

        <!-- https://mvnrepository.com/artifact/com.squareup.okhttp/okhttp -->
        <dependency>
            <groupId>com.squareup.okhttp</groupId>
            <artifactId>okhttp</artifactId>
            <version>2.7.5</version>
        </dependency>


        <!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.68</version>
        </dependency>

    </dependencies>

プロジェクトのディレクトリ構造は次のよう:

フォルダのHTMLテンプレート・ファイル内のインデックスページがあり、ラベルを配置し、その要求の承認githubのにクリックします。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<a href="https://github.com/login/oauth/authorize?client_id=your_client_id&redirect_uri=http://localhost:8090/callback&state=test&scope=user">授权github登录</a>
</body>
</html>

// localhostを::HTTP書かREDIRECT_URIの上に書かれた注意私は新しいコントローラを作成したいので、8090 /コールバック、アドレスマッピングコールバックに、はserver.portのspringboot私もに8090を設定します。

application.properties:

server.port=8090

okhttp HttpHelperパッケージで使用されます:

package com.github_auth.helper;

import com.squareup.okhttp.*;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class HttpHelper
{
    public String Get(String url)
    {
        OkHttpClient client = new OkHttpClient();

        Request request = new Request.Builder()
                .url(url)
                .build();
        try
        {
            Response response = client.newCall(request).execute();
            return response.body().string();
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public String Post(String url,String json)
    {
        OkHttpClient client = new OkHttpClient();
        MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
        RequestBody body = RequestBody.create(mediaType, json);
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        try
        {
            Response response = client.newCall(request).execute();
            return response.body().string();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        return null;
    }
}

承認プロセスのコールバック関数:

package com.github_auth.controller;

import com.alibaba.fastjson.JSON;
import com.github_auth.dto.RequestAccessTockenParam;
import com.github_auth.dto.UserInfo;
import com.github_auth.helper.HttpHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.sound.midi.Soundbank;

@Controller
public class AuthController {
    @Autowired
    private HttpHelper httpHelper;
    String client_id="your_client_id";
    String client_secret="your_client_secret";

    @RequestMapping("/callback")
    @ResponseBody
    public UserInfo callback(@RequestParam("code") String code)
    {
        //1.code参数为github回调callback_uri时,github传递过来的
        System.out.println("请求callback...,code:"+code);

        RequestAccessTockenParam param=new RequestAccessTockenParam();
        param.setClient_id(client_id);
        param.setClient_secret(client_secret);
        param.setCode(code);//传入code参数
        param.setRedirect_url("http://localhost:8090");
        param.setState("test");

        //获取access token
        String url="https://github.com/login/oauth/access_token";
        String json= JSON.toJSONString(param);
        //2.根据传入的参数(包含code),post请求https://github.com/login/oauth/access_token,获取返回值
        String result= httpHelper.Post(url,json);//access_token=your_client_id&scope=user&token_type=bearer
        System.out.println( "callback result:"+result);

        String[] strs=result.split("&");
        String access_token=strs[0].split("=")[1];//解析access_token

        //3.根据access token,请求https://api.github.com/user获取用户信息
        String url_user="https://api.github.com/user?access_token="+access_token;
        String userInfo=httpHelper.Get(url_user);
        System.out.println("userInfo:"+userInfo);//返回的是一个json字符串

        UserInfo user=JSON.parseObject(userInfo,UserInfo.class);
        return  user;
    }
}


ランは、我々はホームページを入力します。

おすすめ

転載: www.cnblogs.com/lishuanguan1987/p/12642047.html