Open Closed

Use Cookies and Bearer together #216


User avatar
0
saintpoida created
  • ABP Framework version: v2.7.0
  • UI type: Angular
  • Tiered (MVC) or Identity Server Seperated (Angular): yes
  • Exception message and stack trace: None
  • Steps to reproduce the issue:

Hi guys,

So firstly background, i have created a custom class library to represent another module im working on, it is MyModule.HttpApi for example, its added as a project reference to the main HttpApi project and it loads fine. It has custom middleware in it to serve files from a certain path (basically hiding the physical path to the file) so I can call https://localhost:44311/StaticFiles/image0.jpeg and it serves an image from where ever i want. This works fine too.

However now i am trying to protect it with authorization and im having real troubles. Obviously if you go straight to an image or file path there is no bearer token set on that request but cookies are sent. I can see when i look at dev console that cookies are in the request but i cant tell if they are the right cookies or not. So then i have read lots of docs and tried various things for it to recognise cookies but i cant tell if im doing it correctly.

Can you guys give me any info i should follow if i want cookies to work as well as bearer token?

I have tried lots of things with no luck and currently am sitting with the code below which also doesnt work. My custom policy only has context.Succeed in it so it should pass if it gets there but its blocked by the policy.RequireAuthenticatedUser(); I can tell its blocked cause if i remove that line then my handler gets picked up but debugging the context in that handler shows no claims either

.AddAuthentication(options =>
                {
                    options.DefaultScheme = "IdentityAndCookie";// IdentityServerAuthenticationDefaults.AuthenticationScheme;
                    //options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                    //options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                })
                .AddPolicyScheme("IdentityAndCookie", "Identity server and cookie", options =>
                {
                    options.ForwardDefaultSelector = context =>
                    {
                        var bearerAuth = context.Request.Headers["Authorization"].FirstOrDefault()?.StartsWith("Bearer ") ?? false;
                        // You could also check for the actual path here if that's your requirement:
                        // eg: if (context.HttpContext.Request.Path.StartsWithSegments("/api", StringComparison.InvariantCulture))
                        if (bearerAuth)
                            return IdentityServerAuthenticationDefaults.AuthenticationScheme;
                        else
                            return CookieAuthenticationDefaults.AuthenticationScheme;
                    };
                })
                .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options =>
                {
                    //options.LoginPath = "/Account/Unauthorized/";
                    //options.AccessDeniedPath = "/Account/Forbidden/";
                    options.Cookie.Name = ".AspNetCore.Identity.Application";
                })
                .AddIdentityServerAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme, options =>
                {
                    options.Authority = configuration["AuthServer:Authority"];
                    options.RequireHttpsMetadata = true;
                    options.ApiName = "Hub";
                })
                ;


            context.Services.AddSingleton<IAuthorizationHandler, StaticFilesReadHandler>();

            context.Services.AddAuthorization(options =>
            {
                options.DefaultPolicy = new AuthorizationPolicyBuilder(CookieAuthenticationDefaults.AuthenticationScheme, IdentityServerAuthenticationDefaults.AuthenticationScheme)
                    .RequireAuthenticatedUser()
                    //.AddRequirements(new StaticFilesReadRequirement())
                    .Build();
                options.AddPolicy("StaticFiles.Read", policy =>
                {
                    policy.AuthenticationSchemes.Add(CookieAuthenticationDefaults.AuthenticationScheme);
                    //policy.AuthenticationSchemes.Add(IdentityServerAuthenticationDefaults.AuthenticationScheme);
                    policy.RequireAuthenticatedUser();
                    policy.Requirements.Add(new StaticFilesReadRequirement());
                });


            });

6 Answer(s)
  • User Avatar
    0
    liangshiwei created
    Support Team Fullstack Developer

    Hi

    Can your use CLI to create a simple project to reproduce this problem?

  • User Avatar
    0
    saintpoida created

    @liangshiwei

    Hi yeah i have created basically a whole abp project to reproduce problem and can be found here

    The middleware and custom policy are in the HttpApi project, settings in HttpApi Host project. I think my settings are wrong because if i manually edit the request for that path to include bearer token it works as expected. So something related to the cookie setup is wrong or im missing a setting i believe.

    Let me know thanks

  • User Avatar
    0
    liangshiwei created
    Support Team Fullstack Developer

    Sorry, I mean use free start template to reproduce this problem, commercial project has your license information.

  • User Avatar
    0
    saintpoida created

    Good point i have removed access to that lnk and can see you removed it from the message thanks!

    I will redo it in the next few hours

  • User Avatar
    0
    saintpoida created

    Sorry i havent had a chance to make the project today, will get it done tomorrow. However i was testing it with the mvc version of abp and it works as expected but there are different cookies when using mvc so im pretty sure its just a difference in configuration. I will also try copying the mvc auth settings to api host and see if that makes a difference. I could always create a tiny mvc web project to just serve that middleware as a fallback

    Will update after i have tried a few things

  • User Avatar
    0
    alper created
    Support Team Director

    thnx for the feedback

Made with ❤️ on ABP v9.1.0-preview. Updated on November 11, 2024, 11:11