首页 > 解决方案 > .Net Core OAuth 在授权代码重定向时返回 302

问题描述

我正在尝试使用 .Net-Core 2.1 为 StripeConnect 实施 OAuth。我已经像这样配置了我的启动:

services.AddAuthentication(options =>
{
    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(cfg =>
{
    cfg.RequireHttpsMetadata = false;
    cfg.SaveToken = true;
    cfg.TokenValidationParameters = tokenValidationParameters;
})
.AddGoogle(options =>
{
    options.SaveTokens = true;
    options.ClientId = Configuration["Google:ClientId"];
    options.ClientSecret = Configuration["Google:ClientSecret"];
})
.AddOAuth(StripeConnectDefaults.AuthenticationScheme, options => {
    options.SaveTokens = true;
    options.ClientId = Configuration["Stripe:ClientId"];
    options.ClientSecret = Configuration["Stripe:ClientSecret"];
    options.TokenEndpoint = StripeConnectDefaults.TokenEndpoint;
    options.AuthorizationEndpoint = StripeConnectDefaults.AuthorizationEndpoint;
    options.CallbackPath = new PathString("/signin-stripeconnect");
    options.ClaimActions.MapJsonKey(ClaimTypes.NameIdentifier, "stripe_user_id");
});

我可以使用令牌获得 OAuthTokenResponse 就可以了,但是当它到达 ExternalLoginCallback 时,没有提供令牌

[HttpPost("ExternalLogin")]
[AllowAnonymous]
public IActionResult ExternalLogin(string provider, string returnUrl = null)
{
    var redirectUrl = Url.Action(nameof(ExternalLoginCallback), "Account", new { returnUrl });
    var properties = _signInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl);
    return Challenge(properties, provider);
}

[HttpGet("ExternalLoginCallback")]
[AllowAnonymous]
public async Task<IActionResult> ExternalLoginCallback(string returnUrl = null, string remoteError = null)
{
    if (remoteError != null)
    {
        throw new Exception($"Error from external provider: {remoteError}");
    }
    var info = await _signInManager.GetExternalLoginInfoAsync();
    if (info == null)
    {
        //It throws here, since there are no tokens 
        throw new Exception("Error: could not find user tokens");
    }

    //Handle the rest of authentication
}

更新

我创建了一个 Dummy Handler 进行调查,看起来我的 OAuthTokenResponse 很好,但由于某种原因,签名管理器没有找到令牌:

public class DummyOAuthHandler<T> : OAuthHandler<T>
    where T: OAuthOptions, new()
{
    public DummyOAuthHandler(IOptionsMonitor<T> options, 
        ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock) : base(options, logger, encoder, clock)
    {
    }

    protected override async Task<OAuthTokenResponse> ExchangeCodeAsync(string code, string redirectUri)
    {
        var result = await base.ExchangeCodeAsync(code, redirectUri);
        return result;
    }
}

如何让 .Net-core 正确获取带有授权码的令牌?

标签: c#asp.net-coreoauth.net-corestripe-payments

解决方案


推荐阅读