Page 11 - MSDN Magazine, September 2017
P. 11

app.UseCookieAuthentication(new CookieAuthenticationOptions() {
AuthenticationScheme = "Cookies",
LoginPath = new PathString("/Account/Login/"), AutomaticAuthenticate = true
The login process in ASP.NET Core passes through three classes: Claim, ClaimIdentity and ClaimsPrincipal.
Collecting the list of claims is a simple matter of populating an array of Claim objects:
});
app.UseIdentityServerAuthentication(new IdentityServerAuthenticationOptions {{
AuthenticationScheme = "Bearer",
AutomaticAuthenticate = true }
Be aware that there are constants to be used in place of magic strings like “Cookies” just to limit typos. In particular, the string “Cookies” can be replaced as below:
AuthenticationScheme = CookieAuthenticationDefaults.AuthenticationScheme
Note that UseIdentityServerAuthentication isn’t part of the ASP.NET Core framework but belongs to the Identity Server framework (see github.com/IdentityServer). To choose the authentica- tion scheme on a per-request basis, you use a new attribute on the Authorize attribute that in ASP.NET MVC marks actions as subject to authentication and authorization:
[Authorize(ActiveAuthenticationSchemes = "Bearer")] public class ApiController : Controller
{
// Your API action methods here
... }
The net effect of the code snippet is that all public endpoints of the sample ApiController class are subject to the identity of the user as authenticated by the bearer token.
Modeling the User Identity
In ASP.NET, the IPrincipal interface defines the software contract that defines the core of the user identity. The logged user is exposed through the User property of the HttpContext controller property. IPrincipal has the same implementation in ASP.NET 4.x (including ASP.NET MVC) and ASP.NET Core. However, in ASP.NET Core the default principal object isn’t GenericPrincipal, but the new ClaimsPrincipal type. The difference is relevant.
GenericPrincipal wraps up one key piece of user information— the user name—even though custom user data can be added to the authentication ticket encrypted in the cookie. Over the years, the sole user name has become too little for the needs of modern applications. The role of the user, as well as some other chunks of information, most noticeably picture and display name, appear absolutely required today, forcing every realistic application to create its own custom principal type or query user informa- tion for each and every request using the user name as the key. ClaimsPrincipal just brilliantly solves the problem.
A claim is a key/value pair that describes a property of the logged user. The list of properties is up to the application, but includes name and role at the very minimum. Claims, in other words, are theASP.NETCorewaytomodelidentityinformation.Claimscan be read from any source, whether databases, cloud or local storage, even hardcoded. The Claim class is as simple as this:
public class Claim {
public string Type { get; } public string Value { get; }
// More properties ... }
public Claims[] LoadClaims(User user)
var claims = new[] {
new Claim(ClaimTypes.Name, user.UserName), new Claim(ClaimTypes.Role, user.Role), new Claim("Picture", user.Picture)
};
return claims; }
The name of the claim is a plain descriptive name rendered as a string. However, most common claim types have been grouped as constants into the ClaimTypes class. Before you create the principal, which is required to call the authentication workflow completed, you must get hold of an identity object:
var identity = new ClaimsIdentity(claims, "Password");
The first argument is self-explanatory—the list of claims asso- ciated with the identity being created. The second argument is a string that refers to the authentication scheme required to verify the identity. The string “Password” is a reminder of what will be required by the system for a user to prove her identity. The string “Password” is informational only and not a syntax element.
Figure 2 Cookie Authentication Options
Property
Description
AccessDeniedPath
Indicates the path where an authenticated user will be redirected if the provided identity doesn’t have permission to view the requested resource. The same as getting an HTTP 403 status code.
AutomaticAuthenticate
Indicates the middleware runs on every request and attempts to validate cookie and build an identity object from content.
AutomaticChallenge
Indicates the middleware redirects the browser to a login page if the user isn’t authenticated or to the access denied page if the user is authenticated but not authorized on the requested resource.
AuthenticationScheme
Name of the middleware. This property works in conjunction with AutomaticChallenge
to selectively pick up the authentication middleware on a per-request basis.
CookieName
Name of the authentication cookie being created.
ExpireTimeSpan
Sets the expiration time of the authentication cookie. Whether the time has to be intended as absolute or relative is determined by the value of the SlidingExpiration property.
LoginPath
Indicates the path where an anonymous user will be redirected to sign in with her own credentials.
ReturnUrlParameter
Name of the parameter being used to pass the originally requested URL that caused the redirect to the login page in case of anonymous users.
SlidingExpiration
Indicates whether the ExpireTimeSpan value is absolute or relative. In the latter case, the value is considered as an interval and the middleware will reissue the cookie if more than half the interval has elapsed.
msdnmagazine.com
September 2017 7











































   9   10   11   12   13