aboutsummaryrefslogtreecommitdiff
path: root/src/Web/DevHive.Web/Configurations/Extensions/ConfigureJwt.cs
blob: 03d4b114d852ee6fd62d3abb661d6251e8f6cc52 (plain) (blame)
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
49
50
51
52
53
54
using System.Text;
using System.Threading.Tasks;
using DevHive.Services.Options;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;

namespace DevHive.Web.Configurations.Extensions
{
	public static class ConfigureJwt
	{
		public static void JWTConfiguration(this IServiceCollection services, IConfiguration configuration)
		{
			services.AddSingleton(new JwtOptions(configuration
						.GetSection("AppSettings")
						.GetSection("Secret")
						.Value));

			// Get key from appsettings.json
			var key = Encoding.ASCII.GetBytes(configuration
						.GetSection("AppSettings")
						.GetSection("Secret")
						.Value);

			// Setup Jwt Authentication
			services.AddAuthentication(x =>
			{
				x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
				x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
			})
			.AddJwtBearer(x =>
			{
				x.Events = new JwtBearerEvents
				{
					OnTokenValidated = context =>
					{
						// TODO: add more authentication
						return Task.CompletedTask;
					}
				};
				x.RequireHttpsMetadata = false;
				x.SaveToken = true;
				x.TokenValidationParameters = new TokenValidationParameters
				{
					//ValidateIssuerSigningKey = false,
					IssuerSigningKey = new SymmetricSecurityKey(key),
					ValidateIssuer = false,
					ValidateAudience = false
				};
			});
		}
	}
}