Home > Back-end >  Add Authorize Attribute to a controller through code
Add Authorize Attribute to a controller through code

Time:10-04

My question is related to another question I have here. Using the [Authorize] attribute on a controller, or, more specifically, using the [Authorize(AuthenticationSchemes = "MyScheme")], I am able to force authentication before access to a given controller is allowed.

However, we are using EPiServer, specifically, EPiServer.CMS 12.7.0 and EPiServer.Commerce 14.4.0 (along with various other EPiServer components). OOTB, the admin section of EPiServer is hidden behind the route /episerver. I can't add the [Authorize] attribute with my desired scheme to that, and so I'm hoping maybe there is a way I can do it directly within Startup.cs.

Currently, I'm attempting to get around that with endpoints.MapGet("/Util/Login", async ctx => await ctx.ChallengeAsync("AADB2B.OpenIdConnect", new AuthenticationProperties { RedirectUri = "/EPiServer" }));. The logic here is essentially, if I try to access any of the protected areas of the code (EG /EPiServer/CMS), I am automatically redirected to /Util/Login, at which point I map that to a challenge, and then redirect the user back. I can confirm the authentication works correctly - the challenge directs the user to the appropriate login page, and then the callback sends them back where I want them to go.

However, when they return, they hit the same chain, because when they go to /EPiServer, it thinks they aren't authenticated, and directs them back to /Util/Login. My theory is that I could solve this by explicitly telling it to use my specific authentication scheme, but I can't figure out how to do that.

I've also tried:

endpoints.MapGet("/Util/Login", async ctx => ctx.Response.Redirect("/PathThatLeadsToAChallenge"))

endpoints.MapGet("/Util/Login", async ctx => ctx.Response.Redirect("/")).RequireAuthorization(authorizeData: new AuthorizeAttribute { AuthenticationSchemes = "MyScheme" })

Neither worked. Any suggestions would be appreciated. Thanks!

CodePudding user response:

The solution ended up being to stop using AddMicrosoftIdentityWebApp, and return to using AddOpenIdConnect (as Ted suggested here). Why this ended up working is a mystery to me, but for now, I have other priorities to address.

  • Related