代码之家  ›  专栏  ›  技术社区  ›  johnny 5

在.Net核心中使用JWT和OAuth身份验证

  •  0
  • johnny 5  · 技术社区  · 7 年前

    .AddOAuth() 在.Net核心中。我使用Coinbase创建了一个用于身份验证的nuget包(它基本上是add google实现的克隆,外加一些特定于Coinbase的自定义选项) full source questions 但是在这方面,他们似乎没有实现OAuth(例如,我不能传递作用域),我想使用OAuth登录,但是我想向我的客户返回一个JWT。

    当我尝试使用JWT AddCoinbase (这只是对 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");
     });
    

    [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);
    }
    

    1 回复  |  直到 7 年前
        1
  •  1
  •   John Hanley    7 年前

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