[英]Manually call the authorization flow from a middleware in mvc
I've setup oauth authorization in an MVC aspnet core 2 application. 我已经在MVC aspnet core 2应用程序中设置了oauth授权。 It works as intended when I use the
[Authorize]
attribute but I can't get it to work with my middleware RequestHandler
. 当我使用
[Authorize]
属性时,它可以按预期工作,但无法使其与中间件RequestHandler
。
I tried creating a service that calls the context.ChallengeAsync()
method but it fails when called from the middleware (the call never redirects). 我尝试创建一个调用
context.ChallengeAsync()
方法的服务,但是从中间件调用该服务时将失败(该调用永远不会重定向)。 If the user isn't already logged in the consent page is never shown and the token returned is null
. 如果用户尚未登录,则永远不会显示同意页面,并且返回的令牌为
null
。
If the user was already logged in the call returns the token. 如果用户已经登录,则调用返回令牌。 The service does work when called from inside a controller (instead of using
[Authorize]
) 从控制器内部调用时,该服务可以正常工作(而不是使用
[Authorize]
)
So how do I get it to work ? 那么如何使它工作呢? I want to make sure the user is authorized (so that i have access to a token) before continuing...
我要确保用户已被授权(以便我可以访问令牌),然后再继续...
Here are the relevant code sections: 以下是相关的代码部分:
Startup.cs 启动文件
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = OAuthOptionsDefaults.SchemeName;
})
.AddCookie()
.AddOAuth(OAuthOptionsDefaults.SchemeName,
options => { options.SaveTokens = true; /*other options*/ });
services.AddMvc();
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddScoped<IOAuthService, OAuthService>();
services.AddTransient<IRequestHandler, RequestHandler>();
}
public void Configure(IApplicationBuilder app, IRequestHandler requestHandler, ..)
{
app.UseExceptionHandler("/Home/Error");
app.UseStaticFiles();
app.UseAuthentication();
app.Map(new PathString("/myapi"), appbuilder =>
{
appbuilder.Run(async (context) =>
{
await requestHandler.Handle(context, "url to an api", "an api key");
});
});
app.UseMvcWithDefaultRoute();
}
}
RequestHandler.cs RequestHandler.cs
public class RequestHandler : IRequestHandler
{
//[Authorize] doesn't work
public async Task Handle(HttpContext context, string apiUrl, string apiKey)
{
//injected IOAuthService _service;
//tried with and without context as parameter
var accessToken = await _service.GetAccesTokenAsync();
//do stuff ...
}
}
OAuthService.cs OAuthService.cs
public class OAuthService : IOAuthService
{
private async Task<string> GetAccesTokenAsyncHelper(HttpContext context)
{
var isAuthenticated = ((ClaimsIdentity)context.User.Identity)?.IsAuthenticated ?? false;
if (!isAuthenticated)
{
//tried with and without setting schemename
await context.ChallengeAsync(OAuthOptionsDefaults.SchemeName);
}
return await context.GetTokenAsync(OAuthOptionsDefaults.SchemeName, "access_token");
}
public async Task<string> GetAccesTokenAsync()
{
//injected IHttpContextAccessor _accessor;
var context = _accessor.HttpContext;
return await GetAccesTokenAsyncHelper(context);
}
public async Task<string> GetAccesTokenAsync(HttpContext context)
{
return await GetAccesTokenAsyncHelper(context);
}
}
Edit : made the question shorter and more to point in the hopes of someone answering it. 编辑 :使问题更短,更多以指出有人回答的希望。
You need to add Identity to the user property of HttpContext 您需要将身份添加到HttpContext的用户属性中
context.User.AddIdentity((ClaimsIdentity) principal.Identity);
I have added a tutorial here explaining how to authorize HttpContext in Middleware with JWT from the URL hope this will be helpful :) 我在这里添加了一个教程,该教程解释了如何通过URL通过JWT在中间件中授权HttpContext,希望这会有所帮助:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.