MailSharp / MailSharp.MailClient / Extensions / ServiceCollectionExtensions.cs
Code · 49 lines · 1851 bytes
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
47
48
49using MailSharp.MailClient.Models;
using MailSharp.MailClient.Services;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.DataProtection;

namespace MailSharp.MailClient.Extensions;

public static class ServiceCollectionExtensions
{
	// Data Protection and cookie authentication are configured together because one exists to
	// support the other: the cookie's payload is protected using Data Protection keys, and
	// persisting those keys to disk (instead of the ephemeral default) is what lets a previously
	// issued auth cookie stay valid across an app/server restart.
	public static IServiceCollection AddMailSharpAuthentication(this IServiceCollection services, MailSettings settings)
	{
		Directory.CreateDirectory(settings.DataProtectionKeysPath);
		services.AddDataProtection()
			.PersistKeysToFileSystem(new DirectoryInfo(settings.DataProtectionKeysPath))
			.SetApplicationName("MailSharp");

		services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
			.AddCookie(options =>
			{
				options.Cookie.Name = "MailSharpAuth";
				options.Cookie.HttpOnly = true;
				options.Cookie.SameSite = SameSiteMode.Lax;
				options.ExpireTimeSpan = TimeSpan.FromHours(settings.SessionIdleTimeoutHours);
				options.SlidingExpiration = true;
				options.LoginPath = "/Account/Login";
				options.Events.OnRedirectToLogin = context =>
				{
					if (context.Request.Path.StartsWithSegments("/api"))
					{
						context.Response.StatusCode = StatusCodes.Status401Unauthorized;
						return Task.CompletedTask;
					}
					context.Response.Redirect(context.RedirectUri);
					return Task.CompletedTask;
				};
			});

		services.AddAuthorization(options =>
		{
			options.AddPolicy("AdminOnly", policy => policy.RequireClaim(SessionAccountManager.AdminClaimType, "true"));
		});

		return services;
	}
}