Skip to content

No-op Authorization middleware for Razor Pages #7028

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

Merged
merged 2 commits into from
Jan 25, 2019
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
namespace Microsoft.AspNetCore.Mvc.ApplicationModels
{
// This is used to store the uncombined parts of the final page route
// Note: This type name is referenced by name in AuthorizationMiddleware, do not change this without addressing https://github.com/aspnet/AspNetCore/issues/7011
internal class PageRouteMetadata
{
public PageRouteMetadata(string pageRoute, string routeTemplate)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1190,11 +1190,11 @@ public async Task PagesCanByRoutedToApplicationRoot_ViaAddPageRoute()
public async Task AuthFiltersAppliedToPageModel_AreExecuted()
{
// Act
var response = await Client.GetAsync("/ModelWithAuthFilter");
var response = await Client.GetAsync("/Pages/ModelWithAuthFilter");

// Assert
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
Assert.Equal("/Login?ReturnUrl=%2FModelWithAuthFilter", response.Headers.Location.PathAndQuery);
Assert.Equal("/Login?ReturnUrl=%2FPages%2FModelWithAuthFilter", response.Headers.Location.PathAndQuery);
}

[Fact]
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using Xunit;

namespace Microsoft.AspNetCore.Mvc.FunctionalTests
{
public class RazorPagesWithEndpointRoutingTest : IClassFixture<MvcTestFixture<RazorPagesWebSite.StartupWithEndpointRouting>>
{
public RazorPagesWithEndpointRoutingTest(MvcTestFixture<RazorPagesWebSite.StartupWithEndpointRouting> fixture)
{
Client = fixture.CreateDefaultClient();
}

public HttpClient Client { get; }

[Fact]
public async Task Authorize_AppliedUsingConvention_Works()
{
// Act
var response = await Client.GetAsync("/Conventions/AuthFolder");

// Assert
await response.AssertStatusCodeAsync(HttpStatusCode.Redirect);
Assert.Equal("/Login?ReturnUrl=%2FConventions%2FAuthFolder", response.Headers.Location.PathAndQuery);
}

[Fact]
public async Task Authorize_AppliedUsingConvention_CanByOverridenByAllowAnonymousAppliedToModel()
{
// Act
var response = await Client.GetAsync("/Conventions/AuthFolder/AnonymousViaModel");

// Assert
await response.AssertStatusCodeAsync(HttpStatusCode.OK);

var content = await response.Content.ReadAsStringAsync();
Assert.Equal("Hello from Anonymous", content.Trim());
}

[Fact]
public async Task Authorize_AppliedUsingAttributeOnModel_Works()
{
// Act
var response = await Client.GetAsync("/ModelWithAuthFilter");

// Assert
await response.AssertStatusCodeAsync(HttpStatusCode.Redirect);
Assert.Equal("/Login?ReturnUrl=%2FModelWithAuthFilter", response.Headers.Location.PathAndQuery);
}

[Fact]
public async Task Authorize_WithEndpointRouting_WorksForControllers()
{
// Act
var response = await Client.GetAsync("/AuthorizedAction/Index");

// Assert
await response.AssertStatusCodeAsync(HttpStatusCode.Redirect);
Assert.Equal("/Login?ReturnUrl=%2FAuthorizedAction%2FIndex", response.Headers.Location.PathAndQuery);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace RazorPagesWebSite.Controllers
{
[Route("[controller]/[action]")]
[Authorize]
public class AuthorizedActionController : Controller
{
public IActionResult Index() => Ok();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;

namespace RazorPagesWebSite
{
public class StartupWithEndpointRouting
{
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options => options.LoginPath = "/Login");

services.AddMvc()
.AddRazorPagesOptions(options =>
{
options.Conventions.AuthorizeFolder("/Admin");
})
.SetCompatibilityVersion(CompatibilityVersion.Latest);
}

public void Configure(IApplicationBuilder app)
{
app.UseRouting(routes =>
{
routes.MapApplication();
});

app.UseAuthorization();
}
}
}
11 changes: 9 additions & 2 deletions src/Security/Authorization/Policy/src/AuthorizationMiddleware.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
using Microsoft.AspNetCore.Authorization.Policy;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Endpoints;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.Extensions.DependencyInjection;

namespace Microsoft.AspNetCore.Authorization
Expand Down Expand Up @@ -45,11 +44,19 @@ public async Task Invoke(HttpContext context)
throw new ArgumentNullException(nameof(context));
}

var endpoint = context.GetEndpoint();

// Workaround for https://github.com/aspnet/AspNetCore/issues/7011. Do not use the AuthorizationMiddleware for Razor Pages
if (endpoint.Metadata.Any(m => m.GetType().FullName == "Microsoft.AspNetCore.Mvc.ApplicationModels.PageRouteMetadata"))
{
await _next(context);
return;
}

Copy link
Member

@rynowak rynowak Jan 25, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I guess what I expected to see was for AuthorizeFilter (MVC) to ignore AuthorizationMiddlewareInvokedKey - so that we always run authorization twice. This should be a little bit slower, but it's is close to what we shipped in preview1 that didn't have this bug.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Summing up offline conversation: Authenticate \ Authorize has side effects and I wanted to avoid running it twice if we could help it. This does work correctly for the particular scenario that is broken. I've added an additional test with controllers to make sure that works correctly too so we've covered all the bases.

// Flag to indicate to other systems, e.g. MVC, that authorization middleware was run for this request
context.Items[AuthorizationMiddlewareInvokedKey] = AuthorizationMiddlewareInvokedValue;

// IMPORTANT: Changes to authorization logic should be mirrored in MVC's AuthorizeFilter
var endpoint = context.GetEndpoint();
var authorizeData = endpoint?.Metadata.GetOrderedMetadata<IAuthorizeData>() ?? Array.Empty<IAuthorizeData>();
var policy = await AuthorizationPolicy.CombineAsync(_policyProvider, authorizeData);
if (policy == null)
Expand Down