Changeset 13f1472 for resTools_backend/backend/Helpers/JwtMiddleware.cs
- Timestamp:
- 09/18/22 18:09:53 (2 years ago)
- Branches:
- master
- Parents:
- 49b0bbd
- File:
-
- 1 edited
Legend:
- Unmodified
- Added
- Removed
-
resTools_backend/backend/Helpers/JwtMiddleware.cs
r49b0bbd r13f1472 6 6 using backend.Services; 7 7 using backend.Helpers; 8 using Google.Apis.Auth; 9 using System.Text.Json; 10 using Newtonsoft.Json; 8 11 9 12 public class JwtMiddleware … … 11 14 private readonly RequestDelegate _next; 12 15 private readonly AppSettings _appSettings; 16 private static readonly HttpClient client = new HttpClient(); 17 13 18 14 19 public JwtMiddleware(RequestDelegate next, IOptions<AppSettings> appSettings) … … 22 27 var token = context.Request.Headers["Authorization"].FirstOrDefault()?.Split(" ").Last(); 23 28 24 if (token != null )25 a ttachUserToContext(context, userService, token);29 if (token != null && token != "null") 30 await attachUserToContext(context, userService, token); 26 31 27 32 await _next(context); 28 33 } 29 34 30 private voidattachUserToContext(HttpContext context, IUserService userService, string token)35 private async Task attachUserToContext(HttpContext context, IUserService userService, string token) 31 36 { 32 37 try 33 38 { 39 var fbResult = await this.ValidateFacebookToken(token); 40 if (fbResult != null) 41 { 42 context.Items["User"] = fbResult; 43 return; 44 } 45 34 46 var tokenHandler = new JwtSecurityTokenHandler(); 35 47 var key = System.Text.Encoding.ASCII.GetBytes(_appSettings.Secret); … … 47 59 48 60 context.Items["User"] = userId; 61 49 62 } 50 63 catch 51 64 { 52 // do nothing if jwt validation fails 65 try 66 { 67 var result = await GoogleJsonWebSignature.ValidateAsync(token); 68 context.Items["User"] = result.Email; 69 } 70 catch 71 { 72 // do nothing 73 } 53 74 } 54 75 } 76 77 private async Task<string> ValidateFacebookToken(string token) 78 { 79 try 80 { 81 var stringTask = await client.GetStringAsync("https://graph.facebook.com/me?fields=email&access_token=" + token); 82 var obj = JsonConvert.DeserializeObject<FacebookResult>(stringTask); 83 return obj.email; 84 } 85 catch 86 { 87 return null; 88 } 89 } 90 91 internal class FacebookResult 92 { 93 public string email { get; set; } 94 public string id { get; set; } 95 } 55 96 }
Note:
See TracChangeset
for help on using the changeset viewer.