Reputation: 589
I have a method like this :
public string GenerateJwtToken(User user, Transaction? transaction)
{
// generate token that is valid for time from app.config
var tokenHandler = new JwtSecurityTokenHandler();
var key = Encoding.ASCII.GetBytes(_appSettings.Secret);
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(new[] {
new Claim(Constants.JWT_CLAIMS_USER_ID, user.Id.ToString()),
}),
IssuedAt = DateTime.UtcNow,
Issuer = Constants.JWT_ISSUER,
Expires = DateTime.UtcNow.AddSeconds(_appSettings.JwtTokenExpirationTime),
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
};
// Some Stuff
}
Is it possible to add a claim if transaction is not null ? I'm looking for the equivalent of :
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(new[] {
new Claim(Constants.JWT_CLAIMS_USER_ID, user.Id.ToString()),
HERE --> transaction != null ? new Claim(Constants.JWT_CLAIMS_TRANSACTION_GUID : /*DO NOTHING */, transaction.Guid.ToString()),
}),
IssuedAt = DateTime.UtcNow,
Issuer = Constants.JWT_ISSUER,
Expires = DateTime.UtcNow.AddSeconds(_appSettings.JwtTokenExpirationTime),
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
};
It seems to be a simple question, but I don't know the answer...
Upvotes: 0
Views: 72
Reputation: 218828
Not everything has to be shortened to a single line.
Create your list of Claim
objects:
var claims = new List<Claim> { new Claim(Constants.JWT_CLAIMS_USER_ID, user.Id.ToString()) };
Conditionally append to it:
if (transaction != null)
claims.Add(new Claim(Constants.JWT_CLAIMS_TRANSACTION_GUID));
Use the list:
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(claims.ToArray()),
//...
};
Upvotes: 1