-
Notifications
You must be signed in to change notification settings - Fork 4
/
StartupAuth.cs
46 lines (40 loc) · 1.79 KB
/
StartupAuth.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace msal_netcore_angular
{
public static class StartupAuth
{
const string metaDataAddressFormatter = "https://login.microsoftonline.com/{0}/v2.0/.well-known/openid-configuration?p={1}";
const string tenantFormatter = "{0}.onmicrosoft.com";
public static void AddAzureB2CAuthentication(this IServiceCollection services, string policy, string tenant, string audience, bool isDevelopment)
{
var myTenant = string.Format(tenantFormatter, tenant);
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(o =>
{
o.MetadataAddress = string.Format(metaDataAddressFormatter, myTenant, policy);
o.Audience = audience;
o.Events = new JwtBearerEvents()
{
OnAuthenticationFailed = c =>
{
c.NoResult();
c.Response.StatusCode = 500;
c.Response.ContentType = "text/plain";
if (isDevelopment)
{
return c.Response.WriteAsync(c.Exception.ToString());
}
return c.Response.WriteAsync("An error occured processing your authentication.<br/>\r\n" + c.Exception.ToString());
}
};
});
}
}
}