Hrides Thakur

Hrides Thakur

  • NA
  • 292
  • 47.8k

How to add Jwt token authentication in Web API

May 7 2019 3:29 AM
I have created web api project by selecting an empty project in vs.
 
I want to use jwt token-based authentication, I have installed nugate package IdentityModel.Tokens.Jwt.
 
I have added Authentication filter (created a custom class AuthenticatAtribue and implement iAuthenticationFilter)
 
please provide code for below methods
  1. public async Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken)  
  2. {  
  3. // 1. Look for credentials in the request.  
  4. HttpRequestMessage request = context.Request;  
  5. AuthenticationHeaderValue authorization = request.Headers.Authorization;  
  6. // 2. If there are no credentials, do nothing.  
  7. if (authorization == null)  
  8. {  
  9. return;  
  10. }  
  11. // 3. If there are credentials but the filter does not recognize the  
  12. // authentication scheme, do nothing.  
  13. if (authorization.Scheme != "Basic"// is basic ok here i want token based authentication  
  14. {  
  15. return;  
  16. }  
  17. // 4. If there are credentials that the filter understands, try to validate them.  
  18. // 5. If the credentials are bad, set the error result.  
  19. if (String.IsNullOrEmpty(authorization.Parameter))  
  20. {  
  21. context.ErrorResult = "what should write here"  
  22. return;  
  23. }  
  24. Tuple<stringstring> userNameAndPassword = null;// ExtractUserNameAndPassword(authorization.Parameter);  
  25. if (userNameAndPassword == null)  
  26. {  
  27. //context.ErrorResult = new AuthenticationFailureResult("Invalid credentials", request);  
  28. context.ActionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized);  
  29. }  
  30. // string userName = userNameAndPassword.Item1;  
  31. // string password = userNameAndPassword.Item2;  
  32. var identity = new GenericIdentity(); what should i write here  
  33. IPrincipal principal= new GenericPrincipal(identity, null);//// await AuthenticateAsync(userName, password, cancellationToken);  
  34. if (principal == null)  
  35. {  
  36. context.ErrorResult = null;// new AuthenticationFailureResult("Invalid username or password", request);  
  37. }  
  38. // 6. If the credentials are valid, set principal.  
  39. else  
  40. {  
  41. context.Principal = principal;  
  42. }  
  43. }  
  44. public Task ChallengeAsync(HttpAuthenticationChallengeContext context, CancellationToken cancellationToken)  
  45. {  
please provide code for this section

Answers (1)