Skip to content

Instantly share code, notes, and snippets.

@tagr
Created December 11, 2024 22:50
Show Gist options
  • Save tagr/1dcc033fe21e76ef58e76fb7ddc7d419 to your computer and use it in GitHub Desktop.
Save tagr/1dcc033fe21e76ef58e76fb7ddc7d419 to your computer and use it in GitHub Desktop.
Oidc Auth Azure B2c
using System;
using System.IdentityModel.Claims;
using System.IdentityModel.Tokens;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using Microsoft.IdentityModel.Protocols;
using Microsoft.IdentityModel.Protocols.OpenIdConnect;
using Microsoft.IdentityModel.Tokens;
using Microsoft.Owin;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.Cookies;
using Microsoft.Owin.Security.OpenIdConnect;
using Owin;
[assembly: OwinStartup(typeof(YourNamespace.Startup))]
namespace YourNamespace
{
public class Startup
{
private static string clientId = "<Your-Client-Id>"; // Application (client) ID
private static string tenant = "<Your-Tenant-Name>.onmicrosoft.com"; // Tenant Name
private static string policy = "<Your-Policy-Name>"; // B2C policy, e.g., B2C_1_SignUpSignIn
private static string redirectUri = "https://<Your-Site>/"; // Redirect URI for the app
private static string clientSecret = "<Your-Client-Secret>"; // Optional: Use if needed for confidential clients
private static string metadataEndpoint = $"https://{tenant}/tfp/{policy}/v2.0/.well-known/openid-configuration";
public void Configuration(IAppBuilder app)
{
app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
app.UseCookieAuthentication(new CookieAuthenticationOptions());
app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
{
ClientId = clientId,
RedirectUri = redirectUri,
Authority = $"https://{tenant}/{policy}",
PostLogoutRedirectUri = redirectUri,
Scope = "openid profile", // Add additional scopes if needed
ResponseType = "id_token",
TokenValidationParameters = new TokenValidationParameters
{
NameClaimType = "name", // Adjust claim type mapping as necessary
},
Notifications = new OpenIdConnectAuthenticationNotifications
{
AuthenticationFailed = context =>
{
context.HandleResponse();
context.Response.Redirect("/Home/Error?message=" + context.Exception.Message);
return System.Threading.Tasks.Task.FromResult(0);
},
RedirectToIdentityProvider = context =>
{
if (context.ProtocolMessage.RequestType == OpenIdConnectRequestType.LogoutRequest)
{
var logoutUri = $"https://{tenant}/{policy}/oauth2/v2.0/logout?post_logout_redirect_uri={redirectUri}";
context.ProtocolMessage.IssuerAddress = logoutUri;
}
return System.Threading.Tasks.Task.FromResult(0);
}
}
});
}
}
public class HomeController : Controller
{
[Authorize]
public ActionResult Index()
{
return View();
}
public ActionResult Login()
{
if (!Request.IsAuthenticated)
{
HttpContext.GetOwinContext().Authentication.Challenge(new AuthenticationProperties { RedirectUri = "/" }, OpenIdConnectAuthenticationDefaults.AuthenticationType);
return new HttpUnauthorizedResult();
}
return RedirectToAction("Index");
}
public ActionResult Logout()
{
HttpContext.GetOwinContext().Authentication.SignOut(OpenIdConnectAuthenticationDefaults.AuthenticationType, CookieAuthenticationDefaults.AuthenticationType);
return RedirectToAction("Index");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment