如何解决抢夺URL令牌
我使用Dotnetcore 3.1创建了一个Web应用程序。使用OAuth 2方法通过API进行身份验证。
在我的项目中,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");
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。