在 .Net-Core 中使用 JWT 和 OAuth 身份验证 [英] Use JWT with OAuth Authentication in .Net-Core

查看:28
本文介绍了在 .Net-Core 中使用 JWT 和 OAuth 身份验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 .Net-Core 中有一个 .AddOAuth() 的自定义实现.我已经使用 Coinbase 创建了一个用于身份验证的 nuget 包(它基本上是 add google 实现的克隆以及一些特定于 coinbase 的自定义选项)完整来源.然而,我已经查看了其他一些问题他们似乎没有实现 OAuth(例如我不能传递范围)我想使用 OAuth 登录但我想向我的客户返回一个 JWT.

I have a custom implementation of .AddOAuth() in .Net-Core. I've created a nuget package for Authentication using Coinbase (which is basically a clone of the add google implementation plus a few custom options specific to coinbase) full source. I've looked at a few other questions on this however they don't seem to implement OAuth (e.g I cannot pass scopes) I would like to login using OAuth But I want to return to my clients a JWT.

当我尝试将 JWT 与 AddCoinbase(这只是 AddOAuth 的衍生物)一起使用时

When I try to use JWT with AddCoinbase ( which is just a derrivative of AddOAuth)

services.AddAuthentication(JWT_BEARER_AUTH)
.AddJwtBearer(cfg =>
{
    cfg.RequireHttpsMetadata = false;
    cfg.SaveToken = true;

    cfg.TokenValidationParameters = new TokenValidationParameters()
    {
        ValidIssuer = Configuration["Tokens:Issuer"],
        ValidAudience = Configuration["Tokens:Issuer"],
        //TODO: get key from secret section
        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Tokens:Key"]))
     };
 })
 .AddCoinbase(options => {
     options.AccessAllAccounts = true;
     options.SendLimitAmount = 1;
     options.SendLimitCurrency = "USD";
     options.SendLimitPeriod = SendLimitPeriod.day;
     options.ClientId = Configuration["Coinbase:ClientId"];
     options.ClientSecret = Configuration["Coinbase:ClientSecret"];
     COINBASE_SCOPES.ForEach(scope => options.Scope.Add(scope));
     options.SaveTokens = true;
     options.ClaimActions.MapJsonKey("urn:coinbase:avatar", "avatar_url");
 });

在我登录到 coinbase 后,外部回调将我重定向

After I login to coinbase the external callback redirects me

[HttpGet("ExternalLoginCallback")]
[AllowAnonymous]
public async Task<IActionResult> ExternalLoginCallback(string returnUrl = null, string remoteError = null)
{
    if (remoteError != null)
    {
        //TODO: Handle remote error failure
        throw new Exception($"Error from external provider: {remoteError}");            
    }
    var info = await _signInManager.GetExternalLoginInfoAsync();
    if (info == null)
    {
        //TODO: Handle null external login info
        throw new Exception("Error: could not find user info");
    }

    // Sign in the user with this external login provider if the user already has a login.
    var result = await _signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent: false, bypassTwoFactor: true);1

    var user = await (result.Succeeded ?
            _userManager.FindByLoginAsync(info.LoginProvider, info.ProviderKey)
        : this.CreateIdentityUser(info));

     await _signInManager.UpdateExternalAuthenticationTokensAsync(info);
    _logger.LogInformation("User logged in with {Name} provider.", info.LoginProvider);

    return Redirect(returnUrl);
}

重定向后,我从未收到 JSON Web 令牌,我总是收到 Cookie.如何在向我的客户端提供 JWT 的同时利用 OAuth 身份验证?

After the redirect I never receive a JSON Web Token I always receive a Cookie. How can I leverage OAuth Authentication while serving JWT to my Clients?

推荐答案

OAuth 不是 Json Web Token 解决方案.OAuth 2.0 提供授权和可选标识 (OIDC).

OAuth is not a Json Web Token solution. OAuth 2.0 provides authorization and optionally identification (OIDC).

当您通过 OAuth 2.0 端点进行授权时,您会收到一个访问令牌和一个可选的 ID 令牌.ID 令牌是签名的 JWT.访问令牌是一个不透明的对象,它是一些供应商实现的签名 JWT,但不是所有(谷歌是不透明的).

When you authorize via an OAuth 2.0 endpoint, you receive an Access Token and optionally an ID Token. The ID Token is a Signed JWT. The Access Token is an opaque object that is a Signed JWT for some vendor implementations but not all (Google is opaque).

授权后,您会收到一两个令牌(访问权限和 ID).您可以将它们包装在您自己的 JWT 中,对其进行签名,然后以您想要的任何方式使用组合的 JWT.

After authorization you receive one or two tokens (access and ID). You can wrap them in your own JWT, sign it and then use the combined JWT any way that you want.

这篇关于在 .Net-Core 中使用 JWT 和 OAuth 身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆