Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
A

AspNetAuthorizationWorkshop

> 编程语言
Open source

A workshop for moving through the various new pieces in ASP.NET Core Authorization

1.2K stars0 likes0 views
WebsiteGitHub

About

A workshop for moving through the various new pieces in ASP.NET Core Authorization

ASP.NET Core Authorization Lab

This is walk through for an ASP.NET Core Authorization Lab, now updated for ASP.NET Core 2.1 and VS2017. (If you're still using 1.x then the older version of the labs are available in the Core1x branch.)

This lab uses the Model-View-Controller template as that's what everyone has been using up until now and it's the most familiar starting point for the vast majority of people.

Official authorization documentation is at https://docs.asp.net/en/latest/security/authorization/index.html.

Tip: When you stop finish running the app at each stage always close the browser to clear the identity cookie.

Step 0: Preparation

Create a new, blank, ASP.NET project.

  • File > New Project > Visual C# > .NET Core
  • Select ASP.NET Core Web Application, give the project a name of AuthorizationLab and click OK.
  • Select the Empty Template, ensure that ASP.NET Core 2.1 is selected in the drop down above the project types and click OK.

Add MVC to the app.

  • Edit Startup.cs and add services.AddMvc(); to the top of the ConfigureServices() method;
  • Edit the Configure() method, delete the existing code.
  • In the now empty Configure(); add the following code to setup MVC default routing;
csharp
app.UseMvc(routes =>
{
     routes.MapRoute(
          name: "default",
          template: "{controller=Home}/{action=Index}/{id?}");
});
  • Create a Controllers folder
  • Create a HomeController.cs file in the Controllers directory, using the VS Controller template, or create it from scratch and ensuring inherits from Controller and has an Index() method which returns a View, for example
csharp

using Microsoft.AspNetCore.Mvc;

namespace AuthorizationLab.Controllers
{
    public class HomeController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }
    }
}
  • Create a Views folder.
  • Create a Home folder under the Views.
  • Create an Index.cshtml file inside the Views\Home folder, and edit it to contain Hello World.
  • Run your application and ensure you see Hello World.

Step 1: Setup authentication

  • In ASP.NET Core 2.1 the Microsoft.AspNetCore.App meta package contains all the authentication and authorization packages, so you don't need to add any extra packages or references.
  • Open startup.cs
  • Add app.UseAuthentication(); at the top of the Configure() method.
  • Add Cookie middleware to the authentication service by adding the following to the top of the ConfigureServices() method.
csharp
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
    .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme,
        options => 
        {
                options.LoginPath = new PathString("/Account/Login/");
                options.AccessDeniedPath = new PathString("/Account/Forbidden/");
        });
  • Edit the Home controller and add the [Authorize] attribute to the controller.
  • Run the project and panic. You get a 404 error. you have no login page.
  • Now create an Account controller, AccountController.cs in the Controllers folder. Create an Login() action and a Forbidden() action.
csharp
using Microsoft.AspNetCore.Mvc;

namespace AuthorizationLab.Controllers
{
    public class AccountController : Controller
    {
        public IActionResult Login()
        {
            return View();
        }

        public IActionResult Forbidden()
        {
            return View();
        }
    }
}
  • Create an Account folder under the Views folder and create corresponding views for the actions, Login.cshtml and Forbidden.cshtml.
  • Add some text to each view so you can tell which view is being displayed, and run your project. You will see you end up at the Login view.
  • Return to the Account controller. Change the Login action to create a Principal and persist it using the code below. This will create user information and put it inside a cookie. This fakes what would normally happen in a forms based login system.
…
  • Finally edit the Home\Index view to display the name claim for the identity. Replace the contents of that view with the following code. This code is a little over complicated on purpose, as a user principal can contain more than one authenticated identity. This rarely happens, and frankly you'll know if you've written code to do this, but you should be aware of this edge case.
@using System.Security.Claims;

@if (!User.Identities.Any(u => u.IsAuthenticated))
{
    
Hello World

}
else
{
    
Hello @User.Identities.First(
      u => u.IsAuthenticated && 
      u.HasClaim(c => c.Type == ClaimTypes.Name)).FindFirst(ClaimTypes.Name).Value

}
  • Run the project and see what happens. You should see 'Hello barry'. The code claims.Add(new Claim(ClaimTypes.Name, "barry", ClaimValueTypes.String, Issuer)); inside the Login() method in the account controller is what is setting the name claim, and is what is being displayed by the view.

Remember to close the browser to clear the identity cookie before moving on to the next step.

Step 2: Authorize all the things

  • First remove the Authorize attribute from the Home controller.
  • Change the AddMvc() call in ConfigureServices() in Startup.cs to add a default authorization policy to the MVC configuration.
csharp
services.AddMvc(config =>
{
    var policy = new AuthorizationPolicyBuilder()
                     .RequireAuthenticatedUser()
                     .Build();
    config.Filters.Add(new AuthorizeFilter(policy));
});
  • Run and watch everything blow up into an infinite redirect loop. Why? You've made every page require authentication. This even includes the login pages.
  • Now add the [AllowAnonymous] attribute to the Account controller, run again and see the user is logged in. AllowAnonymous allows you to mark a controller or an action method as not requiring authentication, even if you require authentication elsewhere.

Remember to close the browser to clear the identity cookie before moving on to the next step.

Step 3: Roles

  • Go to the Home controller and add an Authorize attribute with a role demand to either the controller, or the Index action method;
csharp
[Authorize(Roles = "Administrator")]
  • Run the application and confirm you are redirected to the Forbidden view. This happens because you have an identity, but it's not part of the Administrator role.
  • Close the browser to clear the identity cookie.
  • Return to the AccountController and add a second claims.Add() line, as shown below. This adds a Role claim with the value of Administrator to the issued identity.
csharp
claims.Add(new Claim(ClaimTypes.Role, "Administrator", ClaimValueTypes.String, Issuer));
  • Run the application and confirm you are logged in.

Remember to close the browser to clear the identity cookie before moving on to the next step.

Step 4: Simple Policies

  • Return to Startup.cs and locate the services.AddAuthentication() call in ConfigureServices() call.
  • After services.AddAuthentication() add a call to services.AddAuthorization() and create a simple policy as shown below.
csharp
services.AddAuthorization(options =>
{
    options.AddPolicy("AdministratorOnly", policy => policy.RequireRole("Administrator"));
});
  • This policy is the equivalent of the Role check you used in the Authorize attribute parameters in Step 3.
  • Now change the Home controller Authorize attribute to require a policy, rather than use the role parameter.
csharp
[Authorize(Policy = "AdministratorOnly")]
  • Run the app and confirm you still see the home page. All that has changed is how you're specifying your requirements. Instead of embedding the role name in the attribute you've written a policy which specifies the role name.
  • Close your browser to clear your identity cookie.
  • Now add a second policy, this time requiring a claim.
csharp
services.AddAuthorization(options =>
{
    options.AddPolicy("AdministratorOnly", policy => policy.RequireRole("Administrator"));
    options.AddPolicy("EmployeeId", policy => policy.RequireClaim("EmployeeId"));
});
  • Add a suitable claim to the identity issued by Login action in the Account Controller.
csharp
claims.Add(new Claim("EmployeeId", string.Empty, ClaimValueTypes.String, Issuer));
  • Add a new Authorize attribute to the Home controller, using the new policy name.
csharp
[Authorize(Policy = "EmployeeId")]
  • Run the app and ensure you can see the home page.
  • This is a rather useless check, though. Claims are made up of a claim name and a claim values. You really want to check the values and not just the presence of a claim. Luckily there's a parameter for that. Change the EmployeeId policy to require one of a number of values;
csharp
options.AddPolicy("EmployeeId", policy => policy.RequireClaim("EmployeeId", "123", "456"));
  • Run the app again and the empty claim will be rejected and you will end up at the Forbidden page.
  • Close your browser to clear the identity cookie.
  • Change the identity issuing code to have a suitable claim value to the Login action, as shown below, and try again.
csharp
claims.Add(new Claim("EmployeeId", "123", ClaimValueTypes.String, Issuer));

If a policy has multiple claim requirements all the claim requirements must be fulfilled for authorization to succeed.

Remember to close the browser to clear the identity cookie before moving on to the next step.

Step 5: Code Based Policies

Code based policies consist of a requirement, implementing IAuthorizationRequirement and a handler for the requirement, implementing AuthorizationHandler where T is the requirement.

  • Add a date of birth claim to the user principal in the Login action in the Account controller.
csharp
claims.Add(new Claim(ClaimTypes.DateOfBirth, "1970-06-08", ClaimValueTypes.Date));
  • Now create a custom requirement and handler class; called MinimumAgeRequirement. Here we're going to use a single class for both the requirement and the handler, for simplicity's sake.
…
  • Create an Over21 policy in the AddAuthorization function;
csharp
options.AddPolicy("Over21Only", policy => policy.Requirements.Add(new MinimumAgeRequirement(21)));
  • Apply it to the Home controller using the Authorize attribute.
  • Run the app and ensure you can see the home page.
  • Experiment with the date of birth value (for example, make the year last year) to make authorization fail. Don't forget to set it back to a passing value before you move on.

Remember to close the browser to clear the identity cookie before moving on to the next step.

Step 6: Multiple handlers for a requirement

You may have noticed what a handler returns, nothing at all (Strictly we're returning Task.CompletedTask;, which is effectively nothing). Handlers inform the authorization service they have succeeded by calling context.Succeed(requirement);. You may be asking yourself if there is a context.Succeed() is there a context.Fail()? There is, but if your requirement isn't met you shouldn't touch the context at all. Now you may be asking why not? Well ...

Sometimes you may want multiple handlers for an Authorization Requirement, for example when there are multiple ways to fulfill a requirement. Microsoft's office doors open with your Microsoft badge, however on days you forget your badge you can go to reception and get a temporary pass and the receptionist will let you through the gates. Thus there are two ways to fulfill the single entry requirement. In the ASP.N

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

C#aspnet-coredotnet-core

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category编程语言
PricingOpen source

> Related tools

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言