Skip to content

Instantly share code, notes, and snippets.

@dstegelman
Created February 17, 2018 15:28
Show Gist options
  • Save dstegelman/375d07c3d44a1818e751aab5d13501e0 to your computer and use it in GitHub Desktop.
Save dstegelman/375d07c3d44a1818e751aab5d13501e0 to your computer and use it in GitHub Desktop.
Dot Net MVC Core with Shib
using System.Security.Claims;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
namespace MyApp.Controllers
{
[AllowAnonymous]
public class AuthController : Controller
{
private readonly AppSettings _appSettings;
public AuthController(IOptions<AppSettings> appSettings)
{
this._appSettings = appSettings.Value;
}
/// <summary>
/// Login View, this is the main entry point for establishing an identity,
/// in the case that Shib is disabled, you'll set the user object here.
/// </summary>
/// <returns></returns>
public IActionResult Login()
{
IShibClaim shib = new ShibClaim();
ClaimsPrincipal principal;
if (this._appSettings.EnableShib)
{
principal = shib.BuildClaimsPrincipal(HttpContext.Request.Headers["myheadername"]);
}
else
{
principal = shib.BuildClaimsPrincipal("derekst"); /// THis can be used in debug to set a username
}
HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal);
return RedirectToAction("Index", "Home");
}
/// <summary>
/// </summary>
/// <returns></returns>
public IActionResult Logout()
{
HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
return RedirectToAction("Index", "Home");
}
[AllowAnonymous]
public IActionResult UnAuthorized()
{
return View();
}
}
}
using System.Security.Claims;
namespace MyApp.Auth
{
public interface IShibClaim
{
ClaimsPrincipal BuildClaimsPrincipal(string username);
}
}
using System.Collections.Generic;
using System.Security.Claims;
namespace MyApp.Auth
{
public class ShibClaim : IShibClaim
{
private List<Claim> _userClaims;
private const string issuer = "https://www.mysite.edu";
public ShibClaim()
{
this._userClaims = new List<Claim>();
}
/// <summary>
/// Formal method for adding teh generic username claim to the identity. This is where
/// other claims can be added as well.
/// </summary>
/// <param name="username"></param>
private void BuildUserClaim(string username)
{
this._userClaims.Add(new Claim(ClaimTypes.Name, username, ClaimValueTypes.String, issuer));
}
/// <summary>
/// Main entry point for establishing a principal.
/// </summary>
/// <param name="username"></param>
/// <returns></returns>
public ClaimsPrincipal BuildClaimsPrincipal(string username)
{
this.BuildUserClaim(username);
var userIdentity = new ClaimsIdentity(this._userClaims, "Passport");
return new ClaimsPrincipal(userIdentity);
}
}
}
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace MyApp
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddRouting(options => options.AppendTrailingSlash = true);
services.AddRouting(options => options.LowercaseUrls = true);
// Shib Cookie components
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options =>
{
options.LoginPath = new PathString("/auth/login");
options.LogoutPath = new PathString("/auth/logout");
options.AccessDeniedPath = new PathString("/auth/unauthorized/");
});
var appSettings = Configuration.GetSection("AppSettings");
services.Configure<AppSettings>(appSettings);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment() || env.IsStaging())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStatusCodePages();
app.UseAuthentication();
app.UseStaticFiles();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment