management problem of a NullReferenceException - c#

I have an issue in the Try Catch block of my code below.
In function SetUser, I use the getId function that returns an Id if the user exists in DB otherwise, I get a NullReferenceException.
I call this function in the try catch block in Login. I have a problem with the catch because when the exception is generated, I would like the user to be redirected to the register page. But when I try to execute my code with a non-existing user, I think that I have a kind of infinite loop because my page doesn't stop loading. I don't understand what I'm doing wrong. Need help please
function Login:
public static void Login(HttpRequest Request, HttpResponse Response, string redirectUri)
{
if (Request.IsAuthenticated)
return;
if (!Request.Form.AllKeys.Contains("id_token"))
return;
string value = Request.Form.Get("id_token");
JObject id_token = JwtDecode(value);
string upn = id_token.GetValue("upn").ToString();
DateTime expiretime = GetExpireTime(id_token);
try
{
SetUser(id_token);
}
catch (Exception ex)
{
Response.Redirect("~/register.aspx");
}
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, upn, DateTime.UtcNow, expiretime, false, id_token.ToString(), FormsAuthentication.FormsCookiePath);
string encryptedcookie = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedcookie);
cookie.Expires = expiretime;
Response.Cookies.Add(cookie);
redirectUri = GetRedirectUrl(Request, redirectUri);
Response.Redirect(redirectUri, true);
}
function setUser:
private static void SetUser(JObject id_token)
{
string email = id_token.GetValue("unique_name").ToString();
string name = id_token.GetValue("given_name").ToString();
DataSet ds;
List<Claim> claims = new List<Claim>()
{
new Claim(ClaimTypes.Email, email),
new Claim(ClaimTypes.Name, GetId(email))
};
string roles= "SELECT name FROM AspNetRoles;
ds = GetDataSet(roles);
if (ds.Tables.Count > 0)
{
foreach (var row in ds.Tables(0).Rows)
claims.Add(new Claim(ClaimTypes.Role, row("name")));
}
ClaimsIdentity claimsIdentity = new ClaimsIdentity(claims, "Cookies");
ClaimsPrincipal principal = new ClaimsPrincipal(claimsIdentity);
HttpContext.Current.GetOwinContext().Authentication.User = principal;
Thread.CurrentPrincipal = principal;
}
function getId:
public static string getId(string email)
{
return ((new UserManager()).FindByEmail(email)).Id;
}

Related

JWT Refresh Token not working properly when trying refresh after long time?

I am create a JWT access token and refresh token on login of valid user, access token is short lived and refresh token is with expiration time of 7 days, When I am trying to generate new access token after expiry using refresh token it is working fine and response with new access token and refresh token but after long time such as after 3 or 4 hours when I am trying it is not working. I am also comment in Refresh token method code where I am getting error.
Please see my code:
Controller:
public IActionResult RefreshToken([FromBody] RefreshTokenRequest request)
{
try
{
if (string.IsNullOrWhiteSpace(request.RefreshToken))
{
return Unauthorized();
}
var jwtResult = _jwtAuthManager.Refresh(request.RefreshToken, request.AccessToken, DateTime.Now);
var userName = jwtResult.RefreshToken.UserName;
var role = _userService.GetUserRole(userName);
var claims = new[]
{
new Claim(ClaimTypes.Role, role)
};
_logger.LogInformation($"User [{userName}] has refreshed JWT Token");
if (jwtResult == null)
{
return BadRequest();
}
return Ok(new
{
UserName = userName,
Role= role,
AccessToken = jwtResult.AccessToken,
RefreshToken = jwtResult.RefreshToken.TokenString,
Status = "Success",
Message = "New access token generated successfully"
});
}
catch (SecurityTokenException e)
{
return Unauthorized(e.Message); // return 401 so that the client side can redirect the user to login page
}
}
Generate token method:
public JwtAuthResult GenerateTokens(string username, Claim[] claims, DateTime now)
{
var shouldAddAudienceClaim = string.IsNullOrWhiteSpace(claims?.FirstOrDefault(x => x.Type == JwtRegisteredClaimNames.Aud)?.Value);
var jwtToken = new JwtSecurityToken(
_jwtTokenConfig.Issuer,
shouldAddAudienceClaim ? _jwtTokenConfig.Audience : string.Empty,
claims,
expires: now.AddMinutes(_jwtTokenConfig.AccessTokenExpiration),
signingCredentials: new SigningCredentials(new SymmetricSecurityKey(_secret), SecurityAlgorithms.HmacSha256Signature));
var accessToken = new JwtSecurityTokenHandler().WriteToken(jwtToken);
var refreshToken = new RefreshToken
{
UserName = username,
TokenString = GenerateRefreshTokenString(),
ExpireAt = now.AddMinutes(_jwtTokenConfig.RefreshTokenExpiration),
};
_usersRefreshTokens.AddOrUpdate(refreshToken.TokenString, refreshToken, (s, t) => refreshToken);
return new JwtAuthResult
{
AccessToken = accessToken,
RefreshToken = refreshToken
};
}
Refresh Token Method:
public JwtAuthResult Refresh(string refreshToken, string accessToken, DateTime now)
{
var (principal, jwtToken) = DecodeJwtToken(accessToken);
if (jwtToken == null || !jwtToken.Header.Alg.Equals(SecurityAlgorithms.HmacSha256Signature))
{
throw new SecurityTokenException("Invalid token");
}
var userName = principal.Identity?.Name;
if (!_usersRefreshTokens.TryGetValue(refreshToken, out var existingRefreshToken))
{
throw new SecurityTokenException("Invalid token not found");
}
var result = existingRefreshToken;
if (existingRefreshToken.UserName != userName || existingRefreshToken.ExpireAt <= now) //After 3 or 4 hours I am getting error in this condition.
{
throw new SecurityTokenException("Invalid UserName or refresh token expired");
}
return GenerateTokens(userName, principal.Claims.ToArray(), now); // need to recover the original claims
}
Claim Principal Method:
public (ClaimsPrincipal, JwtSecurityToken) DecodeJwtToken(string token)
{
if (string.IsNullOrWhiteSpace(token))
{
throw new SecurityTokenException("Invalid token");
}
var principal = new JwtSecurityTokenHandler()
.ValidateToken(token,
new TokenValidationParameters
{
ValidateIssuer = true,
ValidIssuer = _jwtTokenConfig.Issuer,
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(_secret),
ValidAudience = _jwtTokenConfig.Audience,
ValidateAudience = true,
ValidateLifetime = false,
ClockSkew = TimeSpan.FromMinutes(1)
},
out var validatedToken);
return (principal, validatedToken as JwtSecurityToken);
}

User Claims seem to be getting replaced somewhere along the pipeline

**Edit: If anyone has any clue how i can better ask or inform you guys about this problem please let me know.
So I am creating custom claims and trying to add them to my user. I see the claims in the User.Identity right after I add them and slightly down the line in the pipeline but by the time it gets to my Global.asax the User.Identity has lost all but one of my claims. I also think the user is changing from a claimsPrinciapl to a GenericPrincipal during the same time. I dont know if I am understanding this or explaining this very well. Not even sure what all code to post but I will post some below.
This is where my user is Authenticated and cookies and claims are create. Note i have been trying a lot of stuff so this might have some weird code:
private AuthenticationResponse AuthenticateUserByService(string userName, string password, bool rememberMe)
{
Authenticator auth = new Authenticator(AppInfo.AuthServiceAddress, AppInfo.ClientId, AppInfo.Secret);
AppInfo.rememberMe = rememberMe;
AuthenticationResponse response = auth.Authenticate(userName, password);
if (response.IsError)
{
// MessageBox.Show(response.ErrorDescription);
return null;
}
if (response.AppUser == null)
{
//MessageBox.Show("No error or user! Unknown reason.");
return null;
}
var cookieHelper = new Helpers.CookieHelper();
//FormsAuthenticationTicket authtick = new FormsAuthenticationTicket(1, response.AppUser.Username, DateTime.Now, DateTime.Now.AddSeconds(response.AppUser.ExpiresIn *2), true, response.AppUser.RefreshToken);
var authtick = cookieHelper.CreateAuthTicket(response.AppUser, true);
var authCookie = cookieHelper.CreateAuthCookie(authtick);
Response.Cookies.Add(authCookie);
var tokenCookie = cookieHelper.CreateTokenCookie(response.AppUser, true);
Response.Cookies.Add(tokenCookie);
// If caching roles in userData field then extract
string[] roles = response.AppUser.Permissions.Select(x => x.PermissionName).ToArray(); // = authTicket.UserData.Split(new char[] { '|' });
// Create the IIdentity instance
IIdentity id = new FormsIdentity(authtick);
var newIdent = new ClaimsIdentity(id);
foreach (var item in roles)
{
newIdent.AddClaim(new Claim(ClaimTypes.Role, item));
}
ClaimsPrincipal cp = new ClaimsPrincipal(newIdent);
// Create the IPrinciple instance
IPrincipal principal = cp; //new GenericPrincipal(id, roles);
Thread.CurrentPrincipal = cp;
AppDomain.CurrentDomain.SetThreadPrincipal(cp);
// Set the context user
HttpContext.User = principal;
//IOwinContext context = Request.GetOwinContext();
//var authManager = context.Authentication;
//authManager.SignIn(newIdent);
this.AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = true }, newIdent);
return response;
In the above code, I can see my user and his claims right after I set the HttpContext.User.
Below is just me checking out the User to make sure it was successful:
private AppUser AuthenticateUser(string userName, string password, bool rememberMe)
{
//bool userAuthenticated = false;
AuthenticationResponse userAuthenticated = null;
bool success = false;
try
{
userAuthenticated = AuthenticateUserByService(userName, password, rememberMe);
var c = User.Identity;
success = !userAuthenticated.IsError;
}
catch { }
}
At one point the claims disappeared by the time I set c to the user.
And i figured this might be important so below is where i create my cookies and tickets:
internal class CookieHelper
{
internal FormsAuthenticationTicket CreateAuthTicket(AppUser appUser, bool isPersistent)
{
return new FormsAuthenticationTicket(
1,
appUser.Username,
DateTime.Now,
DateTime.Now.AddSeconds((appUser.ExpiresIn * 2)),
isPersistent,
appUser.RefreshToken == null ? "" : appUser.RefreshToken,
FormsAuthentication.FormsCookiePath);
}
internal HttpCookie CreateAuthCookie(FormsAuthenticationTicket authTicket)
{
// Encrypt the ticket.
string encAuthTicket = FormsAuthentication.Encrypt(authTicket);
// Create the cookie.
HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encAuthTicket);
authCookie.Expires = authTicket.Expiration;
return authCookie;
}
internal HttpCookie CreateTokenCookie(AppUser appUser, bool isPersistent)
{
// Create token ticket
FormsAuthenticationTicket tokenTicket = new FormsAuthenticationTicket(
1,
appUser.Username,
DateTime.Now,
DateTime.Now.AddSeconds(appUser.ExpiresIn),
isPersistent,
appUser.AccessToken);
// Encrypt the ticket.
string encTokenTicket = FormsAuthentication.Encrypt(tokenTicket);
// Create the cookie.
HttpCookie tokenCookie = new HttpCookie("Mellon", encTokenTicket);
tokenCookie.Secure = false;
tokenCookie.Name = "Mellon";
//tokenCookie.Path = Request.ApplicationPath;
tokenCookie.Expires = tokenTicket.Expiration;
return tokenCookie;
}
}
I feel like questions will need to be asked of me to get the right info for help. I am just lost and at this point my tunnel vision is killing me. Any insight or hints or jsut some love at this point would help. Thanks in advance.
Update
This is where I check if cookie is still valid and perform a refresh if its still valid.
protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
HttpCookie tokenCookie = Request.Cookies["Mellon"];
if (authCookie == null)
{
FormsAuthentication.SignOut();
HttpContext.Current.User = new GenericPrincipal(new GenericIdentity(string.Empty), null);
return;
}
// Extract the forms authentication cookie
FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
if (authTicket == null || authTicket.Expired)
{
FormsAuthentication.SignOut();
HttpContext.Current.User = new GenericPrincipal(new GenericIdentity(string.Empty), null);
return;
}
// Extract the forms authentication cookie
//FormsAuthenticationTicket newAuthTicket;
if (tokenCookie == null)
{
RefreshCookies(authTicket);
return;
}
else
{
FormsAuthenticationTicket tokenTicket = FormsAuthentication.Decrypt(tokenCookie.Value);
// If the access token is stil good, then continue on.
if (tokenTicket.Expired)
{
RefreshCookies(authTicket);
return;
}
}
var tick = (FormsIdentity)HttpContext.Current.User.Identity;
if (tick == null)
{
FormsAuthentication.SignOut();
HttpContext.Current.User = new GenericPrincipal(new GenericIdentity(string.Empty), null);
return;
}
if (authTicket.UserData != tick.Ticket.UserData) // .Ticket.UserData)
{
RefreshCookies(authTicket);
}
}
Basically what I have is my AuthToken which holds me refresh token and a second cookie that holds me AccessToken. Those are created in the AuthenticateUserByService method which gets all that info from our webapi and is returned in response.AppUser. So I can't use forms.setauthcookie because that would overwrite what is already in there.
Image proof of whats going on:
As I said in my comment, it's rather tough to digest the snippets you have posted, So I'll break down into smaller logical chunks.
Let's start of with an Authentication Service Class:
Authentication Service calls the client repository and returns a User
public class AuthenticationService
{
IUserRepository _userRepo;
public AuthenticationService()
{
_userRepo = new UserRepository();
}
public User GetUser(string username, string password)
{
return _userRepo.FindByCredentials(username, password);
}
public User GetUserByUserName(string username)
{
return _userRepo.FindByUserName(username);
}
}
In the Global.asax we need to authenticate with pre-flight request.
protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
//Check the request for a cookie
var authCookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
if (authCookie != null)
{
//Decrypt the Auth Cookie vale
var ticket = FormsAuthentication.Decrypt(authCookie.Value);
//Instantiate Auth Service
var _authService = new AuthenticationService();
//Get user by encrypted name stored in ticket
var user = _authService.GetUserByUserName(ticket.Name);
if (user != null)
{
// Create a ClaimsIdentity with all the claims for this user.
Claim emailClaim = new Claim("Email", (!string.IsNullOrWhiteSpace(user.Email)) ? user.Email: "");
Claim AddressClaim = new Claim("Address", (!string.IsNullOrWhiteSpace(user.Address)) ? user.Address: "");
Claim userNameClaim = new Claim(ClaimTypes.Name, (!string.IsNullOrWhiteSpace(user.Username)) ? user.Username : "");
//Add claims to a collection of claims
List<Claim> claims = new List<Claim>
{
emailClaim ,
AddressClaim ,
userNameClaim
};
//Create forms Identity
FormsIdentity formsIdentity = new FormsIdentity(ticket);
//Create Claims Identity
ClaimsIdentity claimsIdentity = new ClaimsIdentity(formsIdentity);
//Add Claims
claimsIdentity.AddClaims(claims);
//Create Claims Principal
ClaimsPrincipal claimsPrincipal = new ClaimsPrincipal(claimsIdentity);
//Assign principal to current user
HttpContext.Current.User = claimsPrincipal;
}
}
}
Login Controller:
[HttpPost]
[AllowAnonymous]
public ActionResult Login(LoginModel model)
{
if (ModelState.IsValid)
{
var user = _authService.GetUser(model.UserName, model.password);
if (user != null)
{
FormsAuthentication.SetAuthCookie(model.UserName,model.RememberMe);
return Redirect(model.ReturnUrl); }
}
}
ModelState.AddModelError("", "The user name or password provided is incorrect.");
return View(model);
As I've said this is a naïve attempt, please consider a little more security, but this is working sln I've quickly put together and I can access the claims.
Having looked at your code, it feels that your just missing adding the Claims of the user.
Basically what is happening is the claims are getting overwritten in my global.asax. My fix so far has been to just rebuild my claims in my global.asax.

MVC FormsAuthentication IsInRole in View not working

I am authenticating a user:
[Route("Login"), HttpPost, AllowAnonymous]
public LoginViewModelResponse Login(LoginViewModelRequest data)
{
if(!Membership.ValidateUser(data.Username, data.Password))
{
return new LoginViewModelResponse
{
DisplayMessage = "Invalid Username/Password!",
IsSuccess = false,
RedirectUrl = "/Home/"
};
}
FormsAuthentication.SetAuthCookie(data.Username, false);
ClaimsIdentity identity = new GenericIdentity(data.Username);
var roles = "Administrator,User".Split(',');
// var client = AuthorisationService.instance.GetAuthenticatedUser();// new ClientService().GetClientById(1);
var principle = new GenericPrincipal(identity, roles);
HttpContext.Current.User = principle;
System.Threading.Thread.CurrentPrincipal = principle;
if (User.IsInRole("Administrator"))
{
var b = 1;
}
return new LoginViewModelResponse
{
IsSuccess = true,
DisplayMessage = "OK",
RedirectUrl = "/Home/"
};
}
And the test for 'IsInRole' is working.
However, I have the following in my View (_layout), and the check for Administrator fails.
if (ViewContext.HttpContext.User.IsInRole("Administrator"))
{
<li class="dropdown">
...
Is there something I need to do to allow the View to understand "IsInRole"?
This works:
#if (ViewContext.HttpContext.User.Identity.IsAuthenticated == false)
But 'IsInRole' always evaluated to false.
Since you set FormsAuthentication cookie by yourself, you'll need to create Principle object and assign it to current thread on every request inside AuthenticateRequest event.
Global.asax.cs
public class Global : HttpApplication
{
protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
HttpCookie decryptedCookie =
Context.Request.Cookies[FormsAuthentication.FormsCookieName];
if (decryptedCookie != null)
{
FormsAuthenticationTicket ticket =
FormsAuthentication.Decrypt(decryptedCookie.Value);
var identity = new GenericIdentity(ticket.Name);
var roles = ticket.UserData.Split(',');
var principal = new GenericPrincipal(identity, roles);
HttpContext.Current.User = principal;
Thread.CurrentPrincipal = HttpContext.Current.User;
}
}
}
Sign-In method
public void SignIn(string username, bool createPersistentCookie)
{
var now = DateTime.UtcNow.ToLocalTime();
TimeSpan expirationTimeSpan = FormsAuthentication.Timeout;
var ticket = new FormsAuthenticationTicket(
1 /*version*/,
username,
now,
now.Add(expirationTimeSpan),
createPersistentCookie,
"" /*userData*/,
FormsAuthentication.FormsCookiePath);
var encryptedTicket = FormsAuthentication.Encrypt(ticket);
var cookie = new HttpCookie(FormsAuthentication.FormsCookieName,
encryptedTicket)
{
HttpOnly = true,
Secure = FormsAuthentication.RequireSSL,
Path = FormsAuthentication.FormsCookiePath
};
if (ticket.IsPersistent)
{
cookie.Expires = ticket.Expiration;
}
if (FormsAuthentication.CookieDomain != null)
{
cookie.Domain = FormsAuthentication.CookieDomain;
}
Response.Cookies.Add(cookie);
}

HttpContext.User.Identity.Name is sometimes empty

I'm using OWIN for authentication in ASP.NET MVC 5.
My project works perfectly in localhost with IIS Express. The problem is when I upload the project in a web server.
I log in and the application works fine for a moment. Then, it seems as if the session has expired. The HttpContext.User.Identity.Name is empty.
This is my action filter:
public override void OnActionExecuting(ActionExecutingContext context)
{
if (string.IsNullOrEmpty(context.HttpContext.User.Identity.Name))
{
context.Result = new RedirectResult("authentication");
return;
}
}
and this is my login
public JsonResult Login(LoginModel input)
{
if (ModelState.IsValid)
{
if(_AuthenticationLogica.ChecarUsuario(input.User, input.Pass))
{
int idUser = _AuthenticationLogica.GetIdUser(input.User);
var identity = new ClaimsIdentity(new[] { new Claim(ClaimTypes.Name, input.Usuario), new Claim(ClaimTypes.Sid, idUsuario+"") },DefaultAuthenticationTypes.ApplicationCookie,ClaimTypes.Name, ClaimTypes.Role);
foreach (var item in _UsuariosLogica.GetPermissionUser(idUser))
{
identity.AddClaim(new Claim(ClaimTypes.Role, item.IdDerecho + ""));
}
var claimsPrincipal = new ClaimsPrincipal(identity);
// Set current principal
Thread.CurrentPrincipal = claimsPrincipal;
// if you want roles, just add as many as you want here (for loop maybe?)
identity.AddClaim(new Claim(ClaimTypes.Role, "guest"));
// tell OWIN the identity provider, optional
// identity.AddClaim(new Claim(IdentityProvider, "Simplest Auth"));
int id = _AuthenticationLogica.ObtenerIdUsuario("jcsoto");
Authentication.SignIn(new AuthenticationProperties
{
IsPersistent = true
}, identity);
FormsAuthentication.SetAuthCookie(input.Usuario, true);
return Json(new { Resultado = 0, Mensaje = "Ready", IdUser = idUser });
}
}
return Json(new { Resultado = 1, Mensaje = "User or pass wrong" });
}

WebApi calling Async method hangs on the inner Async call

I am calling Async method in a non-async method in the below way in WebApi authentication handler. And it hangs when it executes the inner external Async method. I need to set the claims before the subsequent code executes. So I am setting the return value to the Thread.CurrentPrincipal. Please advise.
I have tried the below and none of them worked.
Task.Run(() => Thread.CurrentPrincipal = this.ValidateTokenAsync(accessToken).GetAwaiter().GetResult()); - this works but the subsequent code execution does not wait on this and so the claims are not utilized there.
Thread.CurrentPrincipal = this.ValidateTokenAsync(accessToken).Result;
Task<ClaimsPrincipal> claimsPrincipalTask = this.ValidateTokenAsync(accessToken);
Task.WaitAll(claimsPrincipalTask);
Thread.CurrentPrincipal = Thread.CurrentPrincipal.GetAwaiter().GetResult();
Thread.CurrentPrincipal = this.ValidateTokenAsync(accessToken).GetAwaiter().GetResult();
private async Task<ClaimsPrincipal> ValidateTokenAsync(string accessToken)
{
LoggingUtilities.Logger.TraceInformation("Validating JWT.");
ClaimsPrincipal principal = ClaimsPrincipal.Current;
if (principal == null || principal.Identity == null || !principal.Identity.IsAuthenticated)
{
principal = await JwtValidator.ValidateTokenAsync(accessToken).ConfigureAwait(false);
}
return principal;
}
The JwtValidator.ValidateTokenAsync method:
public static async Task<ClaimsPrincipal> ValidateTokenAsync(string accessToken)
{
string authority = string.Format(CultureInfo.InvariantCulture, aadInstance, tenant);
string issuer = null;
string stsDiscoveryEndpoint = string.Format(CultureInfo.InvariantCulture, "{0}/.well-known/openid-configuration", authority);
List<SecurityToken> signingTokens = null;
try
{
// The issuer and signingTokens are cached for 24 hours. They are updated if any of the conditions in the if condition is true.
if (DateTime.UtcNow.Subtract(stsMetadataRetrievalTime).TotalHours > 24
|| string.IsNullOrEmpty(globalIssuer)
|| globalSigningTokens == null)
{
// Get tenant information that's used to validate incoming jwt tokens
ConfigurationManager<OpenIdConnectConfiguration> configManager = new ConfigurationManager<OpenIdConnectConfiguration>(stsDiscoveryEndpoint);
OpenIdConnectConfiguration config = await configManager.GetConfigurationAsync().ConfigureAwait(false);
globalIssuer = config.Issuer;
globalSigningTokens = config.SigningTokens.ToList();
stsMetadataRetrievalTime = DateTime.UtcNow;
}
issuer = globalIssuer;
signingTokens = globalSigningTokens;
}
catch (Exception)
{
LoggingUtilities.Logger.TraceWarning("Failed to get signing tokens.");
throw;
}
JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler();
TokenValidationParameters validationParameters = new TokenValidationParameters
{
ValidAudience = audience,
ValidIssuer = issuer,
IssuerSigningTokens = signingTokens,
CertificateValidator = X509CertificateValidator.None
};
ClaimsPrincipal principal;
try
{
// Validate token.
SecurityToken validatedToken;
principal = tokenHandler.ValidateToken(
accessToken,
validationParameters,
out validatedToken);
}
catch (SecurityTokenValidationException)
{
LoggingUtilities.Logger.TraceWarning("Failed to validate the JWT.");
throw;
}
catch (Exception)
{
LoggingUtilities.Logger.TraceWarning("Failed to validate the JWT.");
throw;
}
return principal;
}

Categories

Resources