Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

AuthorizationFilterContext is no longer available in HandleRequirementAsync() #11075

Closed
FeodorFitsner opened this issue Jun 11, 2019 · 3 comments

Comments

@FeodorFitsner
Copy link

In ASP.NET Core 3.0 AuthorizationFilterContext is no longer available inside AuthorizationHandler.HandleRequirementAsync() method.

In 2.2 this method is used to work:

protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, CookieOrTokenAuthorizationRequirement requirement)
{
	if (context.Resource is AuthorizationFilterContext mvcContext)
	{
		if (mvcContext.Filters.Any(filter => filter is MyFilter))
		{
			context.Succeed(requirement);
			return Task.CompletedTask;
		}
	}
}

However, in 3.0 context.Resource is no longer AuthorizationFilterContext, but instead Microsoft.AspNetCore.Routing.RouteEndpoint.

What's recommended way of accessing action filters in 3.0 inside AuthorizationHandler?

@wu-yafeng
Copy link
Contributor

wu-yafeng commented Jun 11, 2019

protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, CookieOrTokenAuthorizationRequirement requirement)
{
	if (context.Resource is Endpoint endpoint)
	{
		if (endpoint.Metadata.OfType<IFilterMetadata>().Any(filter => filter is MyFilter))
		{
			context.Succeed(requirement);
			return Task.CompletedTask;
		}
	}
}

This is because when using endpoint routing in ASP.NET Core 3.0:

  • Mvc will no longer add AuthorizeFilter to ActionDescriptor and ResourceInvoker will not call AuthorizeAsync()

see https://github.com/aspnet/AspNetCore/blob/90ab2cb965aeb8ada13bc4b936b3735ca8dd28df/src/Mvc/Mvc.Core/src/ApplicationModels/AuthorizationApplicationModelProvider.cs#L40

  • Mvc will add all Filter as metadata to endpoint.Metadata

see https://github.com/aspnet/AspNetCore/blob/5561338cfecac5ca4b1dda2f09a7f66153d0b5fe/src/Mvc/Mvc.Core/src/Routing/ActionEndpointFactory.cs#L348

  • instead by AuthorizationMiddleware call the AuthorizeAsync() and resouorce is Endpoint

see https://github.com/aspnet/AspNetCore/blob/5561338cfecac5ca4b1dda2f09a7f66153d0b5fe/src/Security/Authorization/Policy/src/AuthorizationMiddleware.cs#L63

@FeodorFitsner
Copy link
Author

Worked like a charm, thanks for the fast response!

@rybkov
Copy link

rybkov commented Aug 7, 2019

As it is breaking change for Preview 8 - will we have workaround or suggested solution on how to redirect to custom URL when authorization failed?

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants