抢夺URL令牌

问题描述

我使用Dotnetcore 3.1创建了一个Web应用程序。使用OAuth 2方法通过API进行身份验证。

我需要找到一种方法获取API返回的URL中的代码

在我的项目中,Startup.cs看起来像这样:

public void ConfigureServices(IServiceCollection services)
        {
            services.AddRazorPages();
            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = "MyAuthSchema";
            })
               .AddCookie()
               .AddOAuth("MyAuthSchema",options =>
               {
                   options.ClientId = Configuration["artAPI:ClientId"];
                   options.ClientSecret = Configuration["artAPI:ClientSecret"];
                   options.CallbackPath = new PathString("/test");
                   options.AuthorizationEndpoint = "https://artForce.ch/oauth/authorize?response_type=code&client_id=y_gkjtj448HGHG483&redirect_uri=https://display.zh.edu/authorize";
                   options.TokenEndpoint = "MyTokenEndPoint";
                   options.UserinformationEndpoint = "MyUserinformationEndPoint";
               });
        }

第三方API希望端点的格式如下所示:

options.AuthorizationEndpoint = "https://artForce.ch/oauth/authorize?response_type=code&client_id=y_gkjtj448HGHG483&redirect_uri=https://display.zh.edu/authorize";

其中https://artForce.ch/oauth/authorize是第三方API端点

https://display.zh.edu/authorize是我的应用。

我可以使用它,但是我希望能够在代码中获得授权令牌,然后将其重定向https://display.zh.edu/authorize

因此,当我尝试授权时,我按下了触发该控制器的按钮:

[Route("[controller]/[action]")]
public class AuthController : Controller
{
    [HttpGet]
    public IActionResult Login(string returnUrl = "/")

    {
        return Challenge(new AuthenticationProperties() { RedirectUri = returnUrl });
    }
}

但是,当它碰到return Challenge行时,它会重定向我,并且我无法找到让我预先捕获授权代码方法

重定向在这里

https://display.zh.edu/authorize?code=JsAt9KwROG_19484846333GFHsuuwuh

这是我想在重定向之前 的目的:

code=JsAt9KwROG_19484846333GFHsuuwuh

我什至在其中放置了一个断点,并检查了Visual Studio中的所有局部变量和自动变量,但没有显示任何类型的授权代码

所以我想知道,在程序进行重定向之前,是否有地方可以在程序中获取代码

谢谢!

解决方法

您应该添加

.AddOAuth("MyAuthSchema",options =>
    {
        // save your tokens for future use
        config.SaveTokens = true;

        // get token inside oauth events
        config.Events.OnCreatingTicket = context =>
        {
            var token = context.AccessToken;
            return Task.CompletedTask;
        };
    });

或者当您设置为True SaveToken配置时,您应该可以在代码中的任何地方获取令牌:

var token = await HttpContext.GetTokenAsync("access_token");