Chicago Code Camp 2018

I’m very excited to present in this year’s Chicago Code Camp!

This year’s topic is …

Authorization in ASP.NET Core: Tips for securing modern applications!

Microsoft’s transition to a claims based identity model, and policy based authorization opens the door to new techniques to manage modern applications. I’ll briefly explain the basics of Authorization in ASP.NET Core, then take a deeper dive into custom policies, authentication schemes, combining authorization requirements, resource-based, and view-based authorization. We’ll look at how these techniques can decouple authorization logic from business code and facilitate unit testing. Finally, I’ll talk about the benefits of using an authorization server when trying to administer the services feeding your applications.

If you attended my session and want to get a copy of the presentation or demo code, you’ve come to the right place.

Power Point
Source Code

DevExpress: Updating a dxGrid widget.

DevExpress has a line of web controls that I’ve been playing with.
https://js.devexpress.com/

On the whole, I think they are good. I have found the documentation to be plentiful, but the specifics can be scattered in different places. Which is why I’m sharing my experience with their data grid control. It’s more formally called a dxDataGrid. My goal was to simply have an input tag that could hold a foreign key ID. When that value changed, I wanted the data grid to be updated with JSON data from a WebAPI. Pretty common scenario, but I didn’t see a copy & paste example in the documentation that didn’t use Angular. So here is an example to save you some time.

I’m limiting the code to only the relevant parts. It basically displays a list of applications. When you click on one, the data grid gets populated with a list of roles for the application.

Index.cshtml

<div id="applicationList"></div>
<input id=”applicationExternalID” />
<div id=”applicationRolesGrid”></div>

In terms of the markup, this is pretty minimal. DevExpress offers some tag helpers that you can use to create the controls, but they stick a bunch of java script in the middle of the HTML, and I rather keep the java script in separate files. All the configuration can be done in JS.

Index.js

(function ($) {
    
    var applicationList = $("#applicationList").dxList({
        dataSource: DevExpress.data.AspNet.createStore({
            key: "ApplicationID",
            loadUrl: "https://localhost:44356/application/GetApplicationsByTenant",
            onBeforeSend: function (method, ajaxOptions) {
                ajaxOptions.xhrFields = { withCredentials: true };
            }
        }),
        height: 400,
        itemTemplate: function (data) {
            return $("<div>").text(data.DisplayName);
        },
        onItemClick: function (e) {
            var externalID = e.itemData.ExternalID;
            $("#applicatonExternalID").val(externalID);
            $("#DisplayName").text(e.itemData.DisplayName);

            roleSource = DevExpress.data.AspNet.createStore({
                key: "ApplicationRoleID",
                loadUrl: "https://localhost:44356/application/GetApplicationRolesByApplication",
                loadParams: { externalID: externalID },
                onBeforeSend: function (method, ajaxOptions) {
                    ajaxOptions.xhrFields = { withCredentials: true };
                }
            })
            applicationRolesGrid.option('dataSource', roleSource);
            applicationRolesGrid.refresh();
        }
    }).dxList("instance");

    var rolesSource = DevExpress.data.AspNet.createStore({
        key: "ApplicationRoleID",
        loadUrl: "https://localhost:44356/application/GetApplicationRolesByApplication",
        onBeforeSend: function (method, ajaxOptions) {
            ajaxOptions.xhrFields = { withCredentials: true };
        }
    })

    var applicationRolesGrid = $("#applicationRolesGrid").dxDataGrid({
    
        columns: [{
            dataField: "ApplicationRoleID",
            width: 80
        }, {
            dataField: "DisplayName"
        }],

        paging: {
            pageSize: 10
        }
    }).dxDataGrid("instance");

}(jQuery))

So the first thing to take note of is the data stores that are used. DevExpress has created a project on GitHub that allows their client side widgets (controls) to consume data from a ASP.NET web api.
https://github.com/DevExpress/DevExtreme.AspNet.Data
In the case of loading data for the list of applications, I was able to provide the data store with a URL to get the data. You can pass it credentials, and specify a key for each unique record. This is a pretty easy use case. To tell the dxList to use the data store, just set the list’s dataSource parameter to an instance of the data store. The rest is pretty much magic.

I actually create a second data store to get the list of roles for the selected application. This one will require the use of a parameter called loadParams. The WebAPI has a function that takes in a string called externalID, so the loadParams is provided with an object that contain the property externalID.

public async Task<IActionResult> GetApplicationRolesByApplication(string externalID)

This parameter should change every time a different item is clicked in the dxList. So I’ve added a handler to the dxList.onItemClick event. When that happens, I need to update the loadParams object with the new externalID. Here is the sticky party. I expected that I could call the data grid’s refresh method, and it would make the call to the web api and display the new data. But that’s not the case. I actually had to reassign the dxGrid’s dataSource property. That can be done by using the option function to reassign the dataSource property.

applicationRolesGrid.option('dataSource', roleSource);

This is really pretty simple to use, you have to find all the bits that need to be touched. If you know of better ways to do this, feel free to post in the comments.

Using JWTs with the ASP.NET UserManager

Last night I got stuck trying to fix a bug in a REST API that really drove me nuts, so I’ll share in the hopes it will save someone else a headache.
The service uses JWTs for authentication, and are issued in an authentication controller, while the data is provided by another controller. I have a CreateToken method that creates an instance of ApplicationUser for the requested user, and adds some claims.

                        var claims = new[]
                        {
                              new Claim(JwtRegisteredClaimNames.Sub, user.UserName),
                              new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                              new Claim(JwtRegisteredClaimNames.Email, user.Email)
                        }.Union(userClaims);

I’m sure this looks familiar if you’ve used JWTs in .NET. The method creates a valid token, and returns it to the user. The user can then take that token and pass it along to a different controller for authentication. In my case, I had customized the ApplicationUser to include a property called TenantID, and in the controller, I needed to create an instance of the ApplicationUser, and use the TenantID.

var user = await _userManager.GetUserAsync(User);

The problem was that the GetUserAsync(User) always returned null. After screwing around with it for way too long, I went to GitHub to see what GetUserAsync was actually doing.

https://github.com/aspnet/Identity/blob/dev/src/Core/UserManager.cs

It calls GetUserID, and passes in the ClaimsPrincipal.

        public virtual string GetUserId(ClaimsPrincipal principal)
	        {
	            if (principal == null)
	            {
	                throw new ArgumentNullException(nameof(principal));
	            }
	            return principal.FindFirstValue(Options.ClaimsIdentity.UserIdClaimType);
	        }

It wants to find the first claim associated with the UserIdClaimType….Which is what?

JwtRegisteredClaimNames.Sub

When I was creating the token, I was giving the Sub claim the user’s username, but ASP.NET identity was searching the database for the Id field in the AspNetUsers table in SQL.

UGH.

So I changed the assignment when the token is created, and everything seems to work fine now.

                        var claims = new[]
                        {
                              new Claim(JwtRegisteredClaimNames.Sub, user.Id),
                              new Claim(JwtRegisteredClaimNames.UniqueName, user.UserName),
                              new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                              new Claim(JwtRegisteredClaimNames.Email, user.Email)
                        }.Union(userClaims);

Going under the hood of ASP.NET Core 2 Authorization

Microsoft has made implementing simple Authorization requirements in ASP.NET Core 2 feel familiar to previous versions. But when you plan to implement something more complex, it’s very helpful to understand how things work under the hood. With that in mind, I’ll be writing a series of posts about how Authorization is currently implemented in Core 2.

Lay of The Land

It’s common for developers to think of Authorization and Authentication as the same thing, but they really have two different purposes. The job of Authentication is to confirm the identity of a user, while Authorization determines what a user can do. The criteria for allowing a user to perform an action may depend on the user’s membership in a role or group, a claim possessed by the user, or the state of a resource being acted upon. Microsoft’s design for Authorization in .NET Core 2 addresses those needs, and implements a separation of concerns, so that you can unit test authorization in your application. With this in mind, let’s begin with a brief introduction to policy based authorization.

What exactly is a Policy?

A policy is a list of requirements that a user must meet in order to perform an operation. Having a simple example to reference makes describing a policy easier, so I’ll use one from Microsoft’s “Blowdart” repository on Github.

services.AddAuthorization(options =>
{
     options.AddPolicy("AdministratorOnly", policy => policy.RequireRole("Administrator"));
     options.AddPolicy("EmployeeId", policy => policy.RequireClaim("EmployeeId", "123", "456"));
});

In this case the first policy is named “AdministratorOnly”, and its requirement is that the user is assigned to the “Administrator” role. The second policy, “EmployeeId”, requires that the user has a claim called “EmployeeId” that has a value of 123 or 456. Each of these policies has a single requirement, although they could have more.

When you examine the source code for the AuthorizationPolicy class, you’ll find a collection for the requirements. The requirements for a policy can range from requiring that the user is authenticated, is a member of a role, has a claim, or any number of other possibilities. The list of requirements is read only, so once that list is created, you can’t add more. Generally you’ll just create a new policy if needed.

There is another collection in the AuthorizationPolicy class for AuthenticationSchemes. They allow you to specify which authentication methods are allowed when a policy is being evaluated. This means you can have a policy that requires that the user is authenticated with a bearer token, or another that applies to cookies.

Policy.AuthenticationSchemes.Add(JwtBearerDefaults.AuthenticationScheme);

In the case of this policy, it would only be evaluated against an identity that was created with JWTBearer tokens, because the authentication scheme was added to the policy.

Looking back at the “Blowdart” example, the syntax for creating the policies might not be familiar to you. We’ll dig deeper later, but it’s suffice to say for now that IServiceCollection extensions take in a dictionary of Action delegates, and use the AuthorizationPolicyBuilder to create the policies. The AuthorizationPolicyBuilder class has various methods to add requirements to a policy and combine policies together. In the end, the Build method is called, and the new policy is created.


At this point, it probably looks like a big collection of strings, and you might be wondering where the actual work gets done. This brings us to authorization requirements.

What really goes into an authorization requirement?

In order to evaluate a requirement, you’ll need some information about the user, a chunk of code that does the evaluation, and sometimes metadata about the resource being secured. In ASP.NET Core, this is done with a few pieces working together. For the sake of type safety, there is an interface, IAuthorizationRequirement, that has no methods or properties defined. If you browse through the source code, you’ll find that the predefined requirement classes implement this interface. But we still need a place to put that chunk of code that does the evaluation. That class is called the AuthorizationHandler, and there are two types. One is used to evaluate requirements, and the second is designed to deal with requirements that secure a resource. For now, let’s set aside securing a resource.

public abstract class AuthorizationHandler : IAuthorizationHandler
     where TRequirement : IAuthorizationRequirement

The handler class is a generic that implements the HandleAsync method. That method is provided with some context information, about the user, and in turn calls the HandleRequirementAsync method.

protected abstract Task HandleRequirementAsync(AuthorizationHandlerContext context, TRequirement requirement);

The logic to evaluate the requirement is found in the HandleRequirementAsync function. It takes in the needed information about the user in the form of the AuthorizationHandlerContext class. The requirement will in all likelihood have some state, so it needs to be passed into the evaluation function too. Looking at an example will help make sense of it all. There is a NameAuthorizationRequirement class that checks to make sure the name of the user is equal is one of the specified values.

protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, NameAuthorizationRequirement requirement)
{
     if (context.User != null)
     {
          if (context.User.Identities.Any(i =&gt; string.Equals(i.Name, requirement.RequiredName)))
          {
               context.Succeed(requirement);
          }
     }
     return Task.CompletedTask;
}

Here you can see that the context has a property with the user information, and in this case the requirement has a string, RequiredName, that needs to match the name of the user. When they match, the Succeed method on the context is called. The context actually stores the results of all the requirement evaluations and aggregates the result.

One of the benefits of this design is that it can be unit tested. Here is one of Microsoft’s unit tests found on GitHub. It employs some classes I have not talked about yet, but you can see that it lets you set up a test, and validate that the requirements are evaluated properly. Separating the authorization logic from the business logic, makes this testing so much easier.

[Fact]
public async Task CanRequireUserName()
{
     // Arrange
     var authorizationService = BuildAuthorizationService(services =>
     {
          services.AddAuthorization(options =>
          {
               options.AddPolicy("Hao", policy => policy.RequireUserName("Hao"));
          });
     });
     var user = new ClaimsPrincipal(
     new ClaimsIdentity(
          new Claim[] {
               new Claim(ClaimTypes.Name, "Hao"),
          },
          "AuthType")
     );

     // Act
     var allowed = await authorizationService.AuthorizeAsync(user, "Hao");

     // Assert
     Assert.True(allowed.Succeeded);
}

I’ve presented a somewhat simplified view of requirements and how they are evaluated. It’s worth while to learn more about how resources can be included, and how logical operations can be used with a policy’s requirements for complex scenarios. More on that in the next post.

Securing an API with JSON Web Tokens (Configuring the API)

To add JWT bearer authentication to an ASP.net Core site, you’ll need to add the JWTBearer middleware to the application. The middleware is found in the Microsoft.AspNetCore.Authentication.JwtBearer namespace, and will allow the service to validate a token, and create a ClaimsPrincipal with the claims in the token. To add the middleware to the service, we’ll start by adding authentication with the options DefaultAuthenticationScheme and DefaultChallengeScheme set to JwtBearerDefaults.AuthenticationScheme. So when the [Authorize] attribute is put on controllers or actions, they will default to use JwtBearer authentication. In the Startup.cs file, there should be a ConfigureServices function that provides you with a IServiceCollection interface to do the configuring.

public void ConfigureServices(IServiceCollection services)
{
     services.AddDbContext<RESTContext>();
     services.AddIdentity<IdentityUser, IdentityRole>()
          .AddEntityFrameworkStores<RESTContext>();

     services.AddAuthentication(options =>
     {
          options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
          options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
     })

...

}

JwtBearer Options

The next service we need to add is the JwtBearer service, which allows configuration with the JwtBearerOptions parameter. Here are a list of several of the options.

  • RequiredHttpsMetadata – JWT bearer tokens should never be passed around without using HTTPS. If someone were to intercept a token, they could use it to impersonate the owner of the token. Always set this option to true.
  • AutomaticAuthenticate – When set to true, it will cause the service to automatically authenticate the user defined in the token.
  • Audience – This value represents the service or resource that will receive the incoming token. Remember that list of registered claims that you can put in the payload of a token? Audience is one of them, and if the value in the token doesn’t match what is placed in this option, the token will be rejected.
  • Authority – The authority option is used to specify the address of the authentication server that issued the token. If you set this option, the middleware will use it to get the public key that is used to validate the token’s signature. It will also verify that the issuer claim found in the token matches this value.
     services.AddAuthentication(options =>
     {
          options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
          options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;

     }).AddJwtBearer(options =>
     {
          options.Audience = Configuration["Tokens:Issuer"];
          options.RequireHttpsMetadata = true;  
          
       

Take note that I did not set the Authority option. The code sample is running a web application that issues and authenticates tokens that it creates. It is not reaching out to an authentication server to validate the token’s signature. If you were going to use a third party service to provide authentication, than this option becomes important.

Validation Options

We will also need to set the parameters that are used to validate a token. In ASP.net Core 2, this is done with the TokenValidationParameters object.
These are a list of the relevant options.

  • ValidateIssuer(s) – Do you want to validate the issuer of the token? Generally this gets set to true.
  • ValidIssuer – If you’re going to validate the issuer of the token, this is the value should match the issuer claim in the token.
  • ValidateIssuerSigningKey – Do you want to validate the Issuer’s signing key?
  • IssuerSigningKey – This is the public key used to validate JWT tokens. When you put the key here, it means that the service won’t need access to the token issuing authentication server. It could come from a file, certificate store, or as in the example below a configuration file. BTW don’t use the example below, it’s not your best security option.
     services.AddAuthentication(options =>
     {
          options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
          options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;

     }).AddJwtBearer(options =>
     {
          options.Audience = Configuration["Tokens:Issuer"];
          options.RequireHttpsMetadata = true;  
          options.TokenValidationParameters = new TokenValidationParameters
          {
               ValidateIssuerSigningKey = true,
               ValidateIssuer = true,
               ValidIssuer = Configuration["Tokens:Issuer"],
               IssuerSigningKey = new SymetricSecurityKey(Encoding.UTF9.GetBytes(Configuration["Tokens:Key"])),
               ValidateLifetime = true
           };

Now the last thing we need to do here is handle the event that gets fired when authentication has failed.

               ValidateIssuer = true,
               ValidIssuer = Configuration["Tokens:Issuer"],
               IssuerSigningKey = new SymetricSecurityKey(Encoding.UTF9.GetBytes(Configuration["Tokens:Key"])),
               ValidateLifetime = true
           };
          options.Events = new JwtBearerEvents()
          {
               OnAuthenticationFailed = c =>
               {
                    c.NoResult();
                    c.Response.StatusCode = 500;
                    c.Response.ContentType = "text/plain";
                    return c.Response.WriteAsync("An error occurred processing your authentication.");
               }
          };

Applying the Attributes

Once the middleware is configured and added to the pipeline, you can use standard authorize attributes on your controllers.
You could also specify that a controller or action use JwtBearer authentication as part of the attribute if you need to be specific.

[Authorize(AuthenticationSchemess = JwtBearerDefaults.AuthenticationScheme)]

Securing an API with JSON Web Tokens (How Do I Create a JWT?)

The typical scenario for creating a JWT would be to have an action in a controller that authenticates a user and returns a token. That token could then be used to authenticate the user for other actions. We’re going to need the help of some classes built into the framework.

using System;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
using System.IdentityModel.Tokens.Jwt;

using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;

Several classes need to be initialized via dependency injection, so here is the constructor for the controller.

public AuthController(SignInManager<IdentityUser> signInManager,
                      UserManager<IdentityUser> userManager,
                      IPasswordHasher<IdentityUser> hasher,
                      IConfiguration configuration,
                      ILogger<AuthController> logger)
{
     _signInManager = signInManager;
     _userManager = userManager;
     _hasher = hasher;
     _configuration = configuration;
     _logger = logger;
}

With the groundwork set, let’s look at the function, that will create the JWT.

[ValidateModel]
[HttpPost]
public async Task<IActionResult> CreateToken([FromBody] CredentialModel model)
{
}

The action takes in a CredentialModel, which is just a class with two string properties (Username and Password). Both the properties are annotated with the [Required] attribute. The CreateToken action is decorated with the [ValidateModel], so the model can be checked for a valid model at the beginning of the function. If the model is not valid, we’ll just log it to the informational log, and return a bad request.

if(!ModelState.IsValid)
{
     _logger.LogInformation($"Invalid CredentialModel passed to CreateToken (UserName:{model.UserName} Password:{model.Password}");
     return BadRequest("Failed to create token.");
}

The next step is to authenticate the user with the UserManager from Microsoft.AspNetCore.Identity. One option would be to use an instance of SignInManager, and call the PasswordSignInAsync function. This function will check the user credentials, and create an authentication cookie. If you don’t want the cookie to be created, you can use the IPasswordHasher interface to verify the authentication credentials.

try
{
     var user = await _userManager.FindByNameAsync(model.UserName);

     if(user != null)
     {
          if (_hasher.VerifyHashedPassword(user, user.PasswordHash, model.Password) == PasswordVerificationResult.Success)
          {
               //Create Token
          }
     }
}
catch (Exception ex)
{
     _logger.LogError($"Exception thrown while creating JWT: {ex}");
}

Creating the token

Now let’s work on creating the token.

var userClaims = await = _userManager.GetClaimsAsync(user);

var claims = new[]
{
     new Claim(JwtRegisteredClaimNames.Sub, user.UserName),
     new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
     new Claim(JwtRegisteredClaimNames.Email, user.Email)
}.Union(userClaims);

var key = new SymetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["Tokens:Key"]));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

var token = new JwtSecurityToken(
     issuer: _configuration["Tokens:Issuer"],
     audience: _configuration["Tokens:Audience"],
     claims: claims,
     expires: DateTime.UtcNow.AddMinutes(15),
     signingCredentials: creds);

return Ok(new 
{
     token = new JwtSecurityTokenHandler().WriteToken(token),
     expiration = token.ValidTo
});

Remember that the payload of the JWT is made up of claims, so the first step is to build up a set of claims for the user. The UserManager will return an array of claims, and we can merge those with some commonly used Registered Claims. For example, Jti is the JWT ID claim that provides a unique identifier to prevent replay attacks.

The next step is to create a key and signing credentials. The key is created based on a string found in the config file. Getting this from a key store, or some other method is a MUCH better idea.

Microsoft uses the JwtSecurityToken class to represent JWTs. The constructor takes the elements of a JWT that were mentioned in part 1. Once we have the token, we can return it from the function.

In the last part of this series, I’ll tell you how you can consume the JWT as part of a REST service.

Securing an API with JSON Web Tokens (What is a JWT)?

JSON Web Token, prounced “jot”, is an open standard that lets you securely transmit information as a JSON object. The token can be signed with a secret using HMAC or a public/private key using RSA. This makes JWTs a great option for authentication. Each JWT is comprised of three parts separated by dots, which are the header, payload, and signature.

Here is an example of a JWT.

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.
eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.
TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ

Header

The header defines what kind of token it is, and the type of hashing algorithm that was used to create the token.

{
“alg”: “HS256”,
“typ”: “JWT”
}

The header is Base64URL encoded, which then becomes the first third of the JWT.

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9

Payload

The second part of the token is the payload, and contains claims and any other metadata about the user. In the example below, claims are included in the payload and then encrypted to create the payload.

{
“sub”: “1234567890”,
“name”: “John Doe”,
“admin”: true
}

eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9

The claims used in the payload are categorized into three groups.

Registered Claims are predefined claims that are defined in RFC 7519. An application should define which claims it uses, and when they are required or optional. The names of the claims are short, three letters, to keep the size of the token small.

  • “iss” : Issuer Claim – identifies the principal that issued the JWT.
  • “sub” : Subject Claim – identifies the principal that is the subject of the JWT.
  • “aud” : Audience Claim – identifies the recipients that the JWT is intended for.
  • “exp” : Expiration Time – identifies the expiration time on or after which the JWT must not be accepted.
  • “jti” : JWT ID Claim – provides a unique identifier for the JWT. The value can be used to prevent the JWT from being replayed.

Public Claims are defined by who ever is creating the token. The concern here is to choose a name that is not likely to collide with another claim name. Ideally, they should be registered in the IANA “JSON Web Token Claims” registry.

Private Claims are agreed to be used by the who ever produced the token, and those who consume the token. The names are not registered, and are likely to be subject to collisions.

Signature

The purpose of the signature is to verify that the sender is who they say they are, and to ensure that the token was not altered in transmission. The signature is created by combining the encoded header, the encoded payload, and a secret. The information is then encrypted.

How Are JWTs Used To Authenticate Users

Traditionally when a user logs into a server, the service will create a session in the server, and return a cookie. JWTs work a bit differently, because when the service authenticates a consumer, it will create the JWT and return it to the consumer, where it is stored locally. On subsequent calls to the service, the consumer includes the JWT in the Authorization header using the Bearer schema.

Authorization: Bearer

There are multiple benefits to this method. The authentication method is stateless, because there is no need to maintain a session on the server. Furthermore, the JWTs are self-contained, and don’t require additional calls to a database to validate the credentials. If you have a service that makes calls to other APIs, you can simple pass the JWT along. There is no restriction on what domain is serving the API, so CORS, Cross-Origin Resource Sharing, is not an issue.

Static Initializers vs. Static Constructors

Static types generally have static member variables that need to be initialized before an instance of the type can be used. There are a couple of common ways to do that. A static constructor can initialize those variables before they are accessed. They are a good option when you need to have logic built into the initialization process. Static initializers are useful when you only have to allocate the static member.

        private static readonly WeatherMan _instance = new WeatherMan();
        static WeatherMan()
        {
            _instance = new WeatherMan();
        }

If there is a reasonable chance that initializing a member variable could result in an exception, you may want to consider using a static constructor. You can’t catch an exception from a static initializer, with a static constructor you can. If an exception occurs in a static constructor, your program will terminate with an exception. If the caller of the static constructor tries to catch the exception, future attempts to create an instance of the type will fail until the AppDomain is unloaded. Ouch. So the only real option is to catch the exception in the static constructor, and add some recovery logic.

ASP.Net Core Claims Authorization

What are claims?
One of the significant changes to .NET Core is how user’s identity is modeled. In the past, .NET used the IPrincipal interface to access who the current user of an application was. Microsoft is moving to a Claims based model, which should help solve the problems developers are currently facing.

At the heart of the matter, a claim is a key-value pair that tells something about the user. ASP.NET Core uses claims as a way to model identity information. Those claims could come from any number of sources, such as an identity server, database, or even local storage. A claim doesn’t describe what a user can do. It tells something about who the user is. Each claim consists of two string properties, a Type and a Value. Generally the Type property will be populated with constants from the ClaimsType class. It’s also important to know who is providing the claim, so an Issuer can be included in the constructor.

const string Issuer = "https://fansgatherhere.com";
var claims = new List<Claim>();
claims.Add(new Claim(ClaimTypes.Name, "Jeff", ClaimValueTypes.String, Issuer));

What is the difference between a ClaimsIdentity and a ClaimsPrincipal?
In many ways, a ClaimsIdentity is like a passport. A passport can have information such as name, height, age, and a photo. Each piece of information is analogous to a claim. To create a new identity, we need to provide the constructor with an authentication type, then add the list of claims. The authentication type is just a string to remind you of what is required for the used to prove their identity.

var userIdentity = new ClaimsIdentity("SuperSecureLogin");
       userIdentity.AddClaims(claims)

With the ClaimsIdentity created, we can move on to the ClaimsPrincipal.

var userPrincipal = new ClaimsPrincipal(userIdentity);

When you examine the properties of the ClaimsPrincipal, you’ll find that there is a collection of ClaimsIdentity objects associated with it. Just like a person can have driver’s license and a passport, a user can have multiple ways identifying themselves. Those identities could come from Twitter, Facebook, Microsoft, or your own store.

Using Claims In Controllers:
Using claims in ASP.NET Core should feel very familiar to working with Authorization in classic ASP.NET. I’ll begin by adding a claim to the ClaimsPrincipal, which I’ll call BackStagePass.

claims.Add(new Claim(ClaimTypes.UserData, "BackStagePass"));

Normally this is something that you would get from a service, or your own data store, but for this example, I’ll just create it in code. Now that I know that the user has the claim, I need to add it to the Authorization service. In the Startup.cs file, I’ll add the Authorization service with a “PassHolders” policy that requires that the user has a “BackStagePass”.

services.AddAuthorization(options =>
       {
                options.AddPolicy("PassHolders", policy => policy.RequireClaim(ClaimTypes.UserData, "BackStagePass"));
        });

Once the policy is added to the authorization service, it can be used in declarative authorization checks. Those checks specify which claims the user must possess, and can require the values that those claims hold.

    [Authorize(Policy = "PassHolders")]
    public class DressingRoomController : Controller

In this example, accessing the controller’s actions will require that the user have a “BackStagePass” claim.

Entity Framework Core – Creating Schemas With the FluentAPI


What’s the difference between storing data in Excel and SQL Server? Schema.

A good schema can help maintain the integrity of your data, and improve the performance of your application.  Entity Framework makes it so easy to create a new database, that it’s easy to forget what’s going on under the hood.  I’ll present some techniques to make EF create databases with indexes, foreign keys, constraints, and inheritance using the Fluent API.

Entity Framework has three methods to create a database schema.  The default method is “convention”.  It uses built in rules based on the name of properties, and entity composition to create the schema.  It’s the method most people use to get started, but you don’t have any control over them.  Another way to configure the schema is to use annotations on the entity model to dictate how the schema is created.  The last and most powerful, is to use the Fluent API.  Configuration options you make using the Fluent API override annotations and conventions. Below is a common data model that I’ll use in my examples.

Identities and Constraints

EF will make the best choice it can when configuring the schema.  For example, if the primary key is an integer, it will make the column an identity column by default.  For every row that is added, the PK is set to the next highest integer in the column.  If you wanted to be explicit about this option, you could do that by overriding the OnModelCreating method of the DbContext object.

public class CRMContext : DbContext

{

     public DbSet<Address> Addresses {get; set;}

     public DbSet<Party> Party {get; set;}

     public DbSet<Person> People {get; set;}

     public DbSet<Organization> Organizations {get; set;}


     protected override void OnModelCreating(ModelBuilder modelBuilder)

     {

          modelBuilder.Entity<Party>()

           .Property(p => p.PartyID

           .UseSqlServerIdentityColumn();

     }
}

Another convention that EF uses, is to create NVARCHAR(MAX) columns to store string data.  It’s a safe guess because it’s flexible in the absence of knowledge about what kind of data will be stored.  If you know that a column will be storing the names of people, you could specify the maximum length the column will store, and improve performance.

modelBuilder.Entity<Party>()

.Property(p => p.DisplayName)

.HasMaxLength(128);

Foreign Keys

In this example, a person or organization inherits from a party.  Each has a collection of addresses that can be associated with them.  This relationship is defined by creating a foreign key property on the database schema.  Using the Fluent API, we begin by declaring the navigation properties of the relationship.  This can be defined as “HasOne” or “HasMany”, depending on the carnality of the relationship.  The inverse navigation can be chained to the definition by using “WithOne” or “WithMany”.

 

protected override void OnModelCreating(ModelBuilder modelBuilder)

{

     modelBuilder.Entity<Party>()

       .HasMany(p => p.Addresses)

       .WithOne(p => p.Party)

       .HasForeignKey(p => p.PartyID)

       .IsRequired()

       .OnDelete(DeleteBehavior.Cascade);

}

After establishing the relationship and its carnality, we need to tell Entity Framework what the foreign key field is.  This is done using HasForeignKey().  It doesn’t make sense to have an address that is not attached to a person or organization, so the foreign key should be required.  This is done with the IsRequired() method.  Because an address is tied to a party, when a party is deleted, we want the related addresses to be deleted as well.  Cascading deletes in SQL Server can handle this problem for us, so we’ll apply that behavior with the OnDelete method.

Indexes

The next step is to create some indexes on the entities to improve performance.  The HasIndex method is used to create an index based on one or more columns.  By default the indexes do not require that each “row” be unique.  That can be configured by using IsUnique.

protected override void OnModelCreating(ModelBuilder modelBuilder)

{

modelBuilder.Entity<Party>()

.HasIndex(p => new { p.PartyID, p.DisplayName })

.IsUnique();

}

Inheritance

Inheritance in a database can take on two distince flavors.  The table-per-hierarchy (TPH) pattern uses a single table to store all the data for all the types in the hierarchy.  The table-per-type (TPT) pattern creates a table for each type in the hierarchy.  Entity Framework currently only supports TPH.  Because data for multiple types will be stored in the same table, an additional piece of information is needed to identify a row’s type.  In EF, this column is called the discriminator.  It can be added to the schema with the HasDiscriminator method.  The values that can be placed in column are defined with the HasValue method.

protected override void OnModelCreating(ModelBuilder modelBuilder)

{

modelBuilder.Entity<Party>()

.HasDiscriminator<string>("PartyType")

.HasValue<Person>("Person")

.HasValue<Organization>("Organization");

}

Because EF is using TPH, the Person DbSet and the Organization DbSet are merged into a Party table. This does limit our ability to use SQL constraints to enforce data integerity. For example, if we need to record the schools that a person has attended, there will be no foreign key constraint that can limit this to people. To prevent an organization from attending a school, we would need to create a insert and update trigger on the School table. TPT modeling would let us avoid having to use a trigger. At this point EF doesn’t support TPT modeling, but it is on Microsoft’s roadmap.  Another thing to take note of is that the extensions needed to set the discriminator are in the Microsoft.EntityFrameworkCore.Relational package in NuGet.