将JWT与.Net-Core中的OAuth身份验证一起使用 [英] Use JWT with OAuth Authentication in .Net-Core

查看:301
本文介绍了将JWT与.Net-Core中的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");
 });

我登录币库后,外部回调将我重定向

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令牌解决方案. 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.

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

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