HttpContext.User.Identity.Name is sometimes empty - c#

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" });
}

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);
}

How to read Claims from JWT Token .NET 4.5

I can't read token claims from Bearer JWT token. Login is working, the http request comes with a valid jwt token to the backend.
The application is self hosted on IIS7.
Here is my code on server side:
SecurityConfig.cs
app.UseOAuthAuthorizationServer(new OAuthAuthorizationServerOptions
{
TokenEndpointPath = new PathString("/token"),
AccessTokenExpireTimeSpan = TimeSpan.FromHours(24),
Provider = new AuthorizationServerProvider() ,
AccessTokenFormat = new JwtFormat(TimeSpan.FromHours(24))
});
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
AuthorizationServerProvider.cs
ClaimsIdentity id = new ClaimsIdentity(context.Options.AuthenticationType);
id.AddClaim(new Claim(InosysClaimTypes.UserId, Convert.ToString(appContext.UserId)));
id.AddClaim(new Claim(InosysClaimTypes.Username, context.UserName));
id.AddClaim(new Claim(InosysClaimTypes.Password, context.Password));
id.AddClaim(new Claim(InosysClaimTypes.FirNr, Convert.ToString(appContext.FirmenNummer)));
id.AddClaim(new Claim(InosysClaimTypes.FirNdl, Convert.ToString(appContext.Niederlassung)));
id.AddClaim(new Claim(InosysClaimTypes.Bereich, Convert.ToString(appContext.Bereich)));
id.AddClaim(new Claim(InosysClaimTypes.Sprache, Convert.ToString(appContext.Sprache)));
id.AddClaim(new Claim(InosysClaimTypes.SchiffNummern, appContext.SchiffNummern == null ? "" : string.Join(",", appContext.SchiffNummern)));
id.AddClaim(new Claim(InosysClaimTypes.Geschaeftsjahr, Convert.ToString(appContext.Geschaeftsjahr)));
var principal = new ClaimsPrincipal(id);
Thread.CurrentPrincipal = principal;
if (HttpContext.Current != null)
{
HttpContext.Current.User = principal;
}
context.Validated(id);
In the ApiController i try to get the caller's payload information like this:
ClaimsIdentity identity = User.Identity as ClaimsIdentity;
if (identity != null)
{
appContext.UserId = Convert.ToInt32(identity.FindFirst(InosysClaimTypes.UserId).Value);
appContext.Username = identity.FindFirst(InosysClaimTypes.Username).Value;
}
That is the identity variable debugged:
identity
I don't know what is going wrong with your AuthorizationServerProvider.cs ,
But from the moment you provide a jwt token in your request header i think it will work this way.
I process the Header with an AuthorizeAttribute on each Controller accepting JWT authorization to set the Current Principal for the request.
public class JwtAuthentication : AuthorizeAttribute
{
protected override bool IsAuthorized(HttpActionContext actionContext)
{
var authHeader=actionContext.Request.Headers.Authorization;
if (authHeader!=null&& !String.IsNullOrWhiteSpace(authHeader.Parameter))
System.Threading.Thread.CurrentPrincipal = JwtAuthenticationHandler.GetPrincipal(authHeader.Parameter);
return ClientAuthorize.Authorize(Roles);
}
}
Usage
[JwtAuthentication(Roles = "User")]
public class ChatBotController : ApiController
{}
Note i have been experiencing some issues with visual studio 2017 reading the Current Principal from the Thread.
You might have a look at if you still experience issues.
ClaimsPrincipal.Current Visual Studio 2017 different behavior
All I needed to do was to implement the unprotect function in the JWTFormat class
public AuthenticationTicket Unprotect(string protectedText)
{
try
{
var handler = new JwtSecurityTokenHandler();
AppContext = new AppContext(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString)
{
EventLogPriority = Properties.Settings.Default.EventLogPriority
};
SecurityToken validToken;
_validationParameters.IssuerSigningKey = new SymmetricSecurityKey(TextEncodings.Base64Url.Decode(Secret));
ClaimsPrincipal principal = handler.ValidateToken(protectedText, _validationParameters, out validToken);
var validJwt = validToken as JwtSecurityToken;
if (validJwt == null)
{
throw new ArgumentException("Invalid JWT");
}
ClaimsIdentity identity = principal.Identities.FirstOrDefault();
return new AuthenticationTicket(identity, new AuthenticationProperties());
}
catch (SecurityTokenException ex)
{
var msg = new HttpResponseMessage(HttpStatusCode.Unauthorized) { ReasonPhrase = "Access Token is manipulated" };
throw new HttpResponseException(msg);
}
}

Core 2 Razor Pages OnGetAsync Load Static File

Is there a way with Razor pages code behind to load a static file as I can do with a traditional MVC controller? I've been playing around with this for a few hours this morning and can't seem to find a way to accomplish this. Any input is appreciated!
Razor Page Code Behind:
public async void OnGetAsync()
{
var request = HttpContext.Request;
var sessionId = request.Query.FirstOrDefault().Value;
var session = await _httpService.ValidateSession(sessionId);
if (!string.IsNullOrEmpty(session?.UserId))
{
var claims = new List<Claim>()
{
new Claim(CustomClaimTypes.UserId, session.UserId),
new Claim(CustomClaimTypes.BuId, session.BuId),
new Claim(CustomClaimTypes.SecurityLevel, session.SecurityLevel)
};
var identity = new ClaimsIdentity(claims, "TNReadyEVP");
var principal = new ClaimsPrincipal(identity);
await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal,
new AuthenticationProperties { ExpiresUtc = DateTime.Now.AddMinutes(60), IsPersistent = true, AllowRefresh = false });
var isAuthenticated = principal.Identity.IsAuthenticated;
Redirect("~/wwwroot/index.html");## Heading ##
}
else
{
RedirectToPage("./Error");
}
MVC Controller
public async Task<IActionResult> SignIn()
{
var sessionId = HttpContext.Request.Query.FirstOrDefault().Value;
var session = await _httpService.ValidateSession(sessionId);
if (!string.IsNullOrEmpty(session?.UserId))
{
var claims = new List<Claim>()
{
new Claim(CustomClaimTypes.UserId, session.UserId),
new Claim(CustomClaimTypes.BuId, session.BuId),
new Claim(CustomClaimTypes.SecurityLevel, session.SecurityLevel)
};
var identity = new ClaimsIdentity(claims, "TNReadyEVP");
var principal = new ClaimsPrincipal(identity);
await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal,
new AuthenticationProperties { ExpiresUtc = DateTime.Now.AddMinutes(20), IsPersistent = true, AllowRefresh = false });
var isAuthenticated = principal.Identity.IsAuthenticated;
}
else
{
return Forbid();
}
return View("~/wwwroot/index.html");
}
First I'd like to say that Core 2 is absolutely terrible at reporting errors. Sometimes it does, sometimes code will fail with no Exception report. Aside from that Core 2 is great.
Here's the answer, you'll see I changed the method signature to return IActionResult which enables the use of RedirectToPage and File.
public async Task<IActionResult> OnGetAsync()
{
var request = HttpContext.Request;
var sessionId = request.Query.FirstOrDefault().Value;
var session = await _httpService.ValidateSession(sessionId);
if (!string.IsNullOrEmpty(sessionId))
{
var claims = new List<Claim>()
{
new Claim(CustomClaimTypes.UserId, session.UserId),
new Claim(CustomClaimTypes.BuId, session.BuId),
new Claim(CustomClaimTypes.SecurityLevel, session.SecurityLevel)
};
var identity = new ClaimsIdentity(claims, "TNReadyEVP");
var principal = new ClaimsPrincipal(identity);
await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal,
new AuthenticationProperties { ExpiresUtc = DateTime.Now.AddMinutes(60), IsPersistent = true, AllowRefresh = false });
var isAuthenticated = principal.Identity.IsAuthenticated;
return File("index.html", "text/html");
}
else
{
return RedirectToPage("Error");
}
}
I suspect the root of the problem is:
public async void OnGetAsync()
You are dispatching an asynchronous operation that is not being awaited, and the context will be disposed - see cannot access a disposed object asp net identitycore and aspnet Mvc issues 7011
FIX: Always use
public async Task OnGetAsync()
I echo above thoughts about need to report errors rather than sticking your head in the sand. In this case the failure of ASP.NET Core 2.2 to report the error means that you'll have lots of weird problems until you change the method signature.

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.

ASP.NET Core JWT mapping role claims to ClaimsIdentity

I want to protect ASP.NET Core Web API using JWT. Additionally, I would like to have an option of using roles from tokens payload directly in controller actions attributes.
Now, while I did find it out how to use it with Policies:
Authorize(Policy="CheckIfUserIsOfRoleX")
ControllerAction()...
I would like better to have an option to use something usual like:
Authorize(Role="RoleX")
where Role would be automatically mapped from JWT payload.
{
name: "somename",
roles: ["RoleX", "RoleY", "RoleZ"]
}
So, what is the easiest way to accomplish this in ASP.NET Core? Is there a way to get this working automatically through some settings/mappings (if so, where to set it?) or should I, after token is validated, intercept generation of ClaimsIdentity and add roles claims manually (if so, where/how to do that?)?
You need get valid claims when generating JWT. Here is example code:
Login logic:
[HttpPost]
[AllowAnonymous]
public async Task<IActionResult> Login([FromBody] ApplicationUser applicationUser) {
var result = await _signInManager.PasswordSignInAsync(applicationUser.UserName, applicationUser.Password, true, false);
if(result.Succeeded) {
var user = await _userManager.FindByNameAsync(applicationUser.UserName);
// Get valid claims and pass them into JWT
var claims = await GetValidClaims(user);
// Create the JWT security token and encode it.
var jwt = new JwtSecurityToken(
issuer: _jwtOptions.Issuer,
audience: _jwtOptions.Audience,
claims: claims,
notBefore: _jwtOptions.NotBefore,
expires: _jwtOptions.Expiration,
signingCredentials: _jwtOptions.SigningCredentials);
//...
} else {
throw new ApiException('Wrong username or password', 403);
}
}
Get user claims based UserRoles, RoleClaims and UserClaims tables (ASP.NET Identity):
private async Task<List<Claim>> GetValidClaims(ApplicationUser user)
{
IdentityOptions _options = new IdentityOptions();
var claims = new List<Claim>
{
new Claim(JwtRegisteredClaimNames.Sub, user.UserName),
new Claim(JwtRegisteredClaimNames.Jti, await _jwtOptions.JtiGenerator()),
new Claim(JwtRegisteredClaimNames.Iat, ToUnixEpochDate(_jwtOptions.IssuedAt).ToString(), ClaimValueTypes.Integer64),
new Claim(_options.ClaimsIdentity.UserIdClaimType, user.Id.ToString()),
new Claim(_options.ClaimsIdentity.UserNameClaimType, user.UserName)
};
var userClaims = await _userManager.GetClaimsAsync(user);
var userRoles = await _userManager.GetRolesAsync(user);
claims.AddRange(userClaims);
foreach (var userRole in userRoles)
{
claims.Add(new Claim(ClaimTypes.Role, userRole));
var role = await _roleManager.FindByNameAsync(userRole);
if(role != null)
{
var roleClaims = await _roleManager.GetClaimsAsync(role);
foreach(Claim roleClaim in roleClaims)
{
claims.Add(roleClaim);
}
}
}
return claims;
}
In Startup.cs please add needed policies into authorization:
void ConfigureServices(IServiceCollection service) {
services.AddAuthorization(options =>
{
// Here I stored necessary permissions/roles in a constant
foreach (var prop in typeof(ClaimPermission).GetFields(BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy))
{
options.AddPolicy(prop.GetValue(null).ToString(), policy => policy.RequireClaim(ClaimType.Permission, prop.GetValue(null).ToString()));
}
});
}
ClaimPermission:
public static class ClaimPermission
{
public const string
CanAddNewService = "Tự thêm dịch vụ",
CanCancelCustomerServices = "Hủy dịch vụ khách gọi",
CanPrintReceiptAgain = "In lại hóa đơn",
CanImportGoods = "Quản lý tồn kho",
CanManageComputers = "Quản lý máy tính",
CanManageCoffees = "Quản lý bàn cà phê",
CanManageBillards = "Quản lý bàn billard";
}
Use the similar snippet to get all pre-defined permissions and insert it to asp.net permission claims table:
var staffRole = await roleManager.CreateRoleIfNotExists(UserType.Staff);
foreach (var prop in typeof(ClaimPermission).GetFields(BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy))
{
await roleManager.AddClaimIfNotExists(staffRole, prop.GetValue(null).ToString());
}
I am a beginner in ASP.NET, so please let me know if you have better solutions.
And, I don't know how worst when I put all claims/permissions into JWT. Too long? Performance ? Should I store generated JWT in database and check it later for getting valid user's roles/claims?
This is my working code! ASP.NET Core 2.0 + JWT. Adding roles to JWT token.
appsettings.json
"JwtIssuerOptions": {
"JwtKey": "4gSd0AsIoPvyD3PsXYNrP2XnVpIYCLLL",
"JwtIssuer": "http://yourdomain.com",
"JwtExpireDays": 30
}
Startup.cs
// ===== Add Jwt Authentication ========
JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear(); // => remove default claims
// jwt
// get options
var jwtAppSettingOptions = Configuration.GetSection("JwtIssuerOptions");
services
.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(cfg =>
{
cfg.RequireHttpsMetadata = false;
cfg.SaveToken = true;
cfg.TokenValidationParameters = new TokenValidationParameters
{
ValidIssuer = jwtAppSettingOptions["JwtIssuer"],
ValidAudience = jwtAppSettingOptions["JwtIssuer"],
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtAppSettingOptions["JwtKey"])),
ClockSkew = TimeSpan.Zero // remove delay of token when expire
};
});
AccountController.cs
[HttpPost]
[AllowAnonymous]
[Produces("application/json")]
public async Task<object> GetToken([FromBody] LoginViewModel model)
{
var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, false, false);
if (result.Succeeded)
{
var appUser = _userManager.Users.SingleOrDefault(r => r.Email == model.Email);
return await GenerateJwtTokenAsync(model.Email, appUser);
}
throw new ApplicationException("INVALID_LOGIN_ATTEMPT");
}
// create token
private async Task<object> GenerateJwtTokenAsync(string email, ApplicationUser user)
{
var claims = new List<Claim>
{
new Claim(JwtRegisteredClaimNames.Sub, email),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
new Claim(ClaimTypes.NameIdentifier, user.Id)
};
var roles = await _userManager.GetRolesAsync(user);
claims.AddRange(roles.Select(role => new Claim(ClaimsIdentity.DefaultRoleClaimType, role)));
// get options
var jwtAppSettingOptions = _configuration.GetSection("JwtIssuerOptions");
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtAppSettingOptions["JwtKey"]));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var expires = DateTime.Now.AddDays(Convert.ToDouble(jwtAppSettingOptions["JwtExpireDays"]));
var token = new JwtSecurityToken(
jwtAppSettingOptions["JwtIssuer"],
jwtAppSettingOptions["JwtIssuer"],
claims,
expires: expires,
signingCredentials: creds
);
return new JwtSecurityTokenHandler().WriteToken(token);
}
Fiddler test GetToken method. Request:
POST https://localhost:44355/Account/GetToken HTTP/1.1
content-type: application/json
Host: localhost:44355
Content-Length: 81
{
"Email":"admin#admin.site.com",
"Password":"ukj90ee",
"RememberMe":"false"
}
Debug response token https://jwt.io/#debugger-io
Payload data:
{
"sub": "admin#admin.site.com",
"jti": "520bc1de-5265-4114-aec2-b85d8c152c51",
"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier": "8df2c15f-7142-4011-9504-e73b4681fb6a",
"http://schemas.microsoft.com/ws/2008/06/identity/claims/role": "Admin",
"exp": 1529823778,
"iss": "http://yourdomain.com",
"aud": "http://yourdomain.com"
}
Role Admin is worked!
For generating JWT Tokens we'll need AuthJwtTokenOptions helper class
public static class AuthJwtTokenOptions
{
public const string Issuer = "SomeIssuesName";
public const string Audience = "https://awesome-website.com/";
private const string Key = "supersecret_secretkey!12345";
public static SecurityKey GetSecurityKey() =>
new SymmetricSecurityKey(Encoding.ASCII.GetBytes(Key));
}
Account controller code:
[HttpPost]
public async Task<IActionResult> GetToken([FromBody]Credentials credentials)
{
// TODO: Add here some input values validations
User user = await _userRepository.GetUser(credentials.Email, credentials.Password);
if (user == null)
return BadRequest();
ClaimsIdentity identity = GetClaimsIdentity(user);
return Ok(new AuthenticatedUserInfoJsonModel
{
UserId = user.Id,
Email = user.Email,
FullName = user.FullName,
Token = GetJwtToken(identity)
});
}
private ClaimsIdentity GetClaimsIdentity(User user)
{
// Here we can save some values to token.
// For example we are storing here user id and email
Claim[] claims = new[]
{
new Claim(ClaimTypes.Name, user.Id.ToString()),
new Claim(ClaimTypes.Email, user.Email)
};
ClaimsIdentity claimsIdentity = new ClaimsIdentity(claims, "Token");
// Adding roles code
// Roles property is string collection but you can modify Select code if it it's not
claimsIdentity.AddClaims(user.Roles.Select(role => new Claim(ClaimTypes.Role, role)));
return claimsIdentity;
}
private string GetJwtToken(ClaimsIdentity identity)
{
JwtSecurityToken jwtSecurityToken = new JwtSecurityToken(
issuer: AuthJwtTokenOptions.Issuer,
audience: AuthJwtTokenOptions.Audience,
notBefore: DateTime.UtcNow,
claims: identity.Claims,
// our token will live 1 hour, but you can change you token lifetime here
expires: DateTime.UtcNow.Add(TimeSpan.FromHours(1)),
signingCredentials: new SigningCredentials(AuthJwtTokenOptions.GetSecurityKey(), SecurityAlgorithms.HmacSha256));
return new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken);
}
In Startup.cs add following code to ConfigureServices(IServiceCollection services) method before services.AddMvc call:
public void ConfigureServices(IServiceCollection services)
{
// Other code here…
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidIssuer = AuthJwtTokenOptions.Issuer,
ValidateAudience = true,
ValidAudience = AuthJwtTokenOptions.Audience,
ValidateLifetime = true,
IssuerSigningKey = AuthJwtTokenOptions.GetSecurityKey(),
ValidateIssuerSigningKey = true
};
});
// Other code here…
services.AddMvc();
}
Also add app.UseAuthentication() call to ConfigureMethod of Startup.cs before app.UseMvc call.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
// Other code here…
app.UseAuthentication();
app.UseMvc();
}
Now you can use [Authorize(Roles = "Some_role")] attributes.
To get user id and email in any controller you should do it like this
int userId = int.Parse(HttpContext.User.Claims.First(c => c.Type == ClaimTypes.Name).Value);
string email = HttpContext.User.Claims.First(c => c.Type == ClaimTypes.Email).Value;
Also userId can be retrived this way (this is due to claim type name ClaimTypes.Name)
int userId = int.Parse(HttpContext.User.Identity.Name);
It's better to move such code to some controller extension helpers:
public static class ControllerExtensions
{
public static int GetUserId(this Controller controller) =>
int.Parse(controller.HttpContext.User.Claims.First(c => c.Type == ClaimTypes.Name).Value);
public static string GetCurrentUserEmail(this Controller controller) =>
controller.HttpContext.User.Claims.First(c => c.Type == ClaimTypes.Email).Value;
}
The same is true for any other Claim you've added. You should just specify valid key.

Categories

Resources