SPA + .NET Core3.1 GitHubの第三者がAspNet.Security.OAuth.GitHubを使用してログインすることを許可しました

利用SPA + .NET Core3.1達成同様のGitHubの第三者は、次のようにAspNet.Security.OAuth.GitHub、フロントエンドを使用してログオンする権限:VUE +ヴュー・ルータ+ axios

AspNet.Security.OAuth.GitHub

GitHubの認可ログイン

どのようなコンフィギュレーションプロセスは言いません。プッシュがあります。

以下は一例です

client_id:0be6b05fc717bfc4fb67
client_secret:dcaced9f176afba64e89d88b9b06ffc4a887a609

取得する

https://github.com/login/oauth/authorize?client_id=0be6b05fc717bfc4fb67&redirect_uri=https://localhost:5001/signin-github

にリダイレクト

https://ではlocalhost:5001 /サインイン-githubのコード= 07537a84d12bbae08361?

要求に次のコードは、access_tokenは得
POSTモード(ポストマンに要求)

https://github.com/login/oauth/access_token?client_id=0be6b05fc717bfc4fb67&client_secret=dcaced9f176afba64e89d88b9b06ffc4a887a609&code=07537a84d12bbae08361

方法を取得

https://api.github.com/user?access_token=787506afa3271d077b98f18af56d7cfdc8db43b4

その後、ユーザー情報を取得することができます

{
   "login": "luoyunchong",
   "id": 18613266,
   "node_id": "MDQ6VXNlcjE4NjEzMjY2",
   "avatar_url": "https://avatars1.githubusercontent.com/u/18613266?v=4",
   "gravatar_id": "",
   "url": "https://api.github.com/users/luoyunchong",
   "html_url": "https://github.com/luoyunchong",
   "followers_url": "https://api.github.com/users/luoyunchong/followers",
   "following_url": "https://api.github.com/users/luoyunchong/following{/other_user}",
   "gists_url": "https://api.github.com/users/luoyunchong/gists{/gist_id}",
   "starred_url": "https://api.github.com/users/luoyunchong/starred{/owner}{/repo}",
   "subscriptions_url": "https://api.github.com/users/luoyunchong/subscriptions",
   "organizations_url": "https://api.github.com/users/luoyunchong/orgs",
   "repos_url": "https://api.github.com/users/luoyunchong/repos",
   "events_url": "https://api.github.com/users/luoyunchong/events{/privacy}",
   "received_events_url": "https://api.github.com/users/luoyunchong/received_events",
   "type": "User",
   "site_admin": false,
   "name": "IGeekFan",
   "company": null,
   "blog": "https://blog.igeekfan.cn",
   "location": null,
   "email": "[email protected]",
   "hireable": null,
   "bio": "学习之路漫漫无期。",
   "public_repos": 14,
   "public_gists": 0,
   "followers": 16,
   "following": 11,
   "created_at": "2016-04-22T10:33:44Z",
   "updated_at": "2019-12-21T14:49:33Z"
}

.NET Core3.1

次のコードは、メインのコードは、以下のDEMOリンクを参照するための完全なコードです。

WEBAPIを使用している場合、私は私が欲しいもの、すべてのMVCの構造に基づいてプロジェクトの数、ではないに見えました。説明の上にいくつかのブログを読ん前端と後端が分離されると、手順は、同じパターンです。

  • フロントランニングます。http:// localhost:8081
  • バックエンドランます。https:// localhostを:5001

    前と後に、次のように認可されたサードパーティのログインプロセスとSPAの分離の終わりがあります

場合はローカルテスト、githubのコールバックアドレスセットHTTP(S):// IP:ポート/サインイン-githubの

  • 如ます。https:// localhostを:5001 /サインイン-githubの。

これは明らかに、上記のアドレス1のバックエンドを埋める結果はそれの前を伝える方法をバックエンドいますか?

前端请求ます。https:// localhostを:?5001 /サインインプロバイダ= GitHubの&redirectUrl =にhttp:// localhost:8080 /ログイン-結果

  • 、GitHubのにパラメータプロバイダの提供
  • GitHubの不正アクセスにredirectUrlした後、サインイン-githubのコールバック、リダイレクトアドレスのバックエンドに行き、ここではルートのフロントエンドを埋めます。

2.バックエンドは、ルートがコールバックがまだ戻ってくるどのように構成されていることをサインイン、サインイン・コールバックルーティングなしサインイン-githubの、githubのを提供しますか?

google-ログイン、マイクロソフトの文書を含め、変更のデフォルトのコールバックのURI CallbackPathプロパティの設定でAddGitHubすることにより、。

それは、彼が設定可能であり、このルートをサインイン-googleの処理、独自のプログラムを書く必要はありませんが、内部のミドルウェアが対処しなければならないがあるコールバックアドレスは、サインインとGoogle設定する必要がありますについて説明し、そのサインイン-githubのがあるはずです。

3.サインイン-githubのにコールバックした後、バックエンド、フロントエンドに対処する方法をリフレッシュするようにします。それを、ログイン後の情報へのアクセス。

上記の具体的な手順のコード取得access_tokenは、これらのプロセス処理のユーザーaccess_tokenはに基づいて情報へのアクセスによると、私たちは自分自身に対処する必要はありません。我々は、ユーザ情報への直接アクセスを使用することができます。

方法サインイン限り、リターンチャレンジ(プロパティ、プロバイダ)

  • プロバイダGitHubのように、
  • プロパティVARプロパティ=新しいAuthenticationProperties {RedirectUri = URL}。

このURLは限りステッチ良いアドレスなど、ユーザー情報を取得するための別のルートです。

var authenticateResult = await _contextAccessor.HttpContext.AuthenticateAsync(provider);
string email = authenticateResult.Principal.FindFirst(ClaimTypes.Email)?.Value;
string name = authenticateResult.Principal.FindFirst(ClaimTypes.Name)?.Value;

注入する必要があります

private readonly IHttpContextAccessor _contextAccessor;
public AuthenticationController( IHttpContextAccessor contextAccessor)
{
    _contextAccessor = contextAccessor;
}

展開コード(簡体字)

オープンNuGetパッケージ管理、インストールパッケージ

Install-Package AspNet.Security.OAuth.GitHub

appSettings.json

"Authentication": {
    "GitHub": {
      "ClientId": "0be6b05fc717bfc4fb67",
      "ClientSecret": "dcaced9f176afba64e89d88b9b06ffc4a887a609"
    }
}

拡張メソッドを追加

public static class JwtConfiguration
{
    public static void AddJwtConfiguration(this IServiceCollection services, IConfiguration configuration)
    {

        services.AddAuthentication(opts =>
            {
                opts.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                opts.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            }).AddCookie(options =>
        {
            options.LoginPath = "/signin";
            options.LogoutPath = "/signout";
        }).AddGitHub(options =>
        {
            options.ClientId = configuration["Authentication:GitHub:ClientId"];
            options.ClientSecret = configuration["Authentication:GitHub:ClientSecret"];
        });
    }
}

このようアバター、電子メールなど、デフォルトで、それが得られません。

.AddGitHub(options =>
{
    options.ClientId = configuration["Authentication:GitHub:ClientId"];
    options.ClientSecret = configuration["Authentication:GitHub:ClientSecret"];
    //options.CallbackPath = new PathString("~/signin-github");//与GitHub上的回调地址相同,默认即是/signin-github
    options.Scope.Add("user:email");
    //authenticateResult.Principal.FindFirst(LinConsts.Claims.AvatarUrl)?.Value;  得到GitHub头像
    options.ClaimActions.MapJsonKey(LinConsts.Claims.AvatarUrl, "avatar_url");
    options.ClaimActions.MapJsonKey(LinConsts.Claims.BIO, "bio");
    options.ClaimActions.MapJsonKey(LinConsts.Claims.BlogAddress, "blog");
});

#其中LinConsts类为静态常量
public static class LinConsts
{
    public static class Claims
    {
        public const string BIO = "urn:github:bio";
        public const string AvatarUrl = "urn:github:avatar_url";
        public const string BlogAddress = "urn:github:blog";
    }
}

startup.cs

ConfigureServicesは、このサービスを設定します

    services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
    services.AddJwtConfiguration(Configuration);

作成AuthenticationController.csは
サインインは、後処理のユーザ認証に成功すると、再バックサインイン-コールバック増加、およびパラメータに戻って。

        private readonly IHttpContextAccessor _contextAccessor;
        private readonly IConfiguration _configuration;

        public AuthenticationController(IHttpContextAccessor contextAccessor, IConfiguration configuration)
        {
            _contextAccessor = contextAccessor;
            _configuration = configuration;
        }
        
        [HttpGet("~/signin")]
        public async Task<IActionResult> SignIn(string provider, string redirectUrl)
        {
            var request = _contextAccessor.HttpContext.Request;
            var url =
                $"{request.Scheme}://{request.Host}{request.PathBase}{request.Path}-callback?provider={provider}&redirectUrl={redirectUrl}";
            var properties = new AuthenticationProperties { RedirectUri = url };
            properties.Items["LoginProviderKey"] = provider;
            return Challenge(properties, provider);

        }

ユーザは、認可(1回目)クリックサインイン・コールバック、このアドレスにリダイレクトするために、そのURLに応じて転送されるサインインの方法では、パラメータが一緒に運びます。ます。http:へのGitHub、redirectUrlとしてプロバイダ// localhostを:8081 /ログイン-結果。

[HttpGet("~/signin-callback")]
public async Task<IActionResult> Home(string provider = null, string redirectUrl = "")
{
    var authenticateResult = await _contextAccessor.HttpContext.AuthenticateAsync(provider);
    if (!authenticateResult.Succeeded) return Redirect(redirectUrl);
    var openIdClaim = authenticateResult.Principal.FindFirst(ClaimTypes.NameIdentifier);
    if (openIdClaim == null || string.IsNullOrWhiteSpace(openIdClaim.Value))
        return Redirect(redirectUrl);

    //TODO 记录授权成功后的信息 

    string email = authenticateResult.Principal.FindFirst(ClaimTypes.Email)?.Value;
    string name = authenticateResult.Principal.FindFirst(ClaimTypes.Name)?.Value;
    string gitHubName = authenticateResult.Principal.FindFirst(GitHubAuthenticationConstants.Claims.Name)?.Value;
    string gitHubUrl = authenticateResult.Principal.FindFirst(GitHubAuthenticationConstants.Claims.Url)?.Value;
    //startup 中 AddGitHub配置项  options.ClaimActions.MapJsonKey(LinConsts.Claims.AvatarUrl, "avatar_url");
    string avatarUrl = authenticateResult.Principal.FindFirst(LinConsts.Claims.AvatarUrl)?.Value;

    return Redirect($"{redirectUrl}?openId={openIdClaim.Value}");
}

参照

Demoサンプル

おすすめ

転載: www.cnblogs.com/igeekfan/p/12110012.html