· 7 years ago · Jun 01, 2018, 02:48 PM
1 public static void AddOAuthAuthorization(this IServiceCollection services, string secretKey)
2 {
3 var decodedKey = Encoding.UTF8.GetString(Convert.FromBase64String(secretKey));
4 services.AddAuthentication(
5 options =>
6 {
7 options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
8 options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
9 }).AddJwtBearer(
10 options =>
11 {
12 options.TokenValidationParameters =
13 new TokenValidationParameters
14 {
15 ValidateIssuer = false,
16 ValidateAudience = false,
17 ValidateLifetime = true,
18 ValidateIssuerSigningKey = true,
19 IssuerSigningKey = JwtSecurityKey.Create(decodedKey)
20 };
21 });
22
23
24 services.AddAuthorization(
25 options =>
26 {
27 var policies = Proxies
28 .SelectMany(p => p.GetCustomAttributes<AuthorizeAttribute>())
29 .Union(Proxies.SelectMany(p =>
30 p.GetMethods().SelectMany(m => m.GetCustomAttributes<AuthorizeAttribute>())))
31 .Select(a => a.Policy).Where(a => !string.IsNullOrWhiteSpace(a));
32 foreach (var pol in policies)
33 options.AddPolicy(pol, policy =>
34 policy.Requirements.Add(new ClaimOperationRequirement(pol)));
35 });
36 services.AddSingleton<IAuthorizationHandler, ClaimHandler>();
37 }