Friday, April 24, 2020

Global error handling in ASPNETCore

Add the following to the StartUp.cs

if (env.IsDevelopment())
{
    app.UseDeveloperExceptionPage();
}
else
{
    app.UseExceptionHandler("/Error");
    app.UseHsts();
}

In the controller add the following:

[AllowAnonymous]
public IActionResult Error()
{
    return View(new ErrorViewModel 
        { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}

For access to the exception, use the IExceptionHandlerPathFeature as in the following code:

var exceptionHandlerPathFeature =
    HttpContext.Features.Get<IExceptionHandlerPathFeature>();
if (exceptionHandlerPathFeature?.Error is FileNotFoundException)
{
    ExceptionMessage = "File error thrown";
}
if (exceptionHandlerPathFeature?.Path == "/index")
{
    ExceptionMessage += " from home page";
}

External Authentication in ASPMVC Net Core

In the StartUp.cs file a few additions are needed to make external authorization work. First, this section needs to be added to the ConfigureServices method:

services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options => {
    options.LoginPath = "/auth";
    options.ReturnUrlParameter = "ReturnUrl";
})
.AddGoogle(options => {
    options.ClientId = "[yourclientid]";
    options.ClientSecret = "[yoursecret]";
    options.CallbackPath = "/auth/signin-google";
    options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
})

And later on in the Configure method make sure these lines are added.

app.UseAuthentication();
app.UseAuthorization();

Note that /auth/signin-google is not a path supplied by the application. Instead the mvc middleware handles this return and hands control over to /auth/afterauth (as specified in the RedirectUri of the Challenge result. This section goes in the auth controller:

public IActionResult GoogleLogin(string returnUrl= "/")
{
    return new ChallengeResult("Google", new AuthenticationProperties {
        RedirectUri = Url.Content($"/auth/afterauth?provider=Google&returnUrl={returnUrl}")
    });
}

Saturday, April 18, 2020

Easily adding Roles to ASP.NET Core

In the Startup.cs file add the basic authorization middleware. For options, add a new policy. This policy will check for the presence of the admin role claim.

services.AddAuthorization(options => {
   options.AddPolicy("admin", policy => policy.RequireClaim(ClaimTypes.Role,"admin"));
});

In the authentication controller, add the claims to the user.

claims.AddRange(user.Roles.Select(r => new Claim(ClaimTypes.Role, r)));

In the controller you want to secure, add the header to check the policy.

[Authorize("admin")]
public class AdminController : Controller {}