简体   繁体   English

从mvc中的中间件手动调用授权流

[英]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.

相关问题 在个人授权MVC 5中手动添加新用户 - Adding a new user manually in individual authorization mvc 5 授权中间件无法识别通过 MVC 约定添加的策略 - Authorization middleware doesn't recognize policies added through MVC conventions C# .NET 5.0 MVC JWT 中间件授权 Z099FB995346F31C749F6E40DB0F39E - C# .NET 5.0 MVC JWT Middleware authorization header 如何手动检查MVC5中的网址授权? - How can I manually check the url authorization in MVC5? 如何使用OWIN中间件在Web Api中实现OAuth2 Authorization_Code流? - How do I implement an OAuth2 Authorization_Code Flow in Web Api using OWIN Middleware? 构建API调用“授权”标头MVC5 - Building API Call 'Authorization' header MVC5 API 调用:“端点……包含授权元数据,但未找到支持授权的中间件。” - API call: “Endpoint … contains authorization metadata, but a middleware was not found that supports authorization.” 在OWIN中间件中使用来自请求的参数请求授权 - request authorization in OWIN middleware using also paramters from request 为什么AsyncLocal不会从OWIN中间件流向WebForms页面? - Why doesn't an AsyncLocal flow from OWIN middleware to a WebForms page? 从自定义中间件调用控制器和操作 - Call controller and action from custom middleware
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM