Role based Authorization with Identity in .Net Core 1.1 - authorization

I have implemented JWT bearer token based authentication and authorization in .Net core 1.1. I also implemented Usermanager for login and register. I am matching user password with PasswordHash using below code.
var userDetails = await _userManager.FindByNameAsync(username);
var result = await _signInManager.CheckPasswordSignInAsync(userDetails, password, lockoutOnFailure: false);
I am getting issue in Role based Authorization. When i am generation JWT token with User(User type role), it's working fine and access only [Authorize(Roles = "User")] attribute methods or Actions. But when i am using [Authorize(Roles = "Administrator")] attribute it is accessing by both User and Admin Role Type. below the sample code:
[Authorize(Roles = "Administrator, User")]
public class AnswersController : Controller
{
private readonly IAnswerService answerServices = null;
public AnswersController(IAnswerService _answerServices)
{
answerServices = _answerServices;
}
[Authorize(Roles = "Administrator")]
// GET: api/Answers
[HttpGet]
public async Task<IActionResult> Get()
{
var result = await answerServices.GetAll();
if (result == null)
{
return NotFound();
}
return Ok(result);
}
[Authorize(Roles = "User")]
// GET: api/Answers/5
[HttpGet("{id}")]
public async Task<IActionResult> Get([FromRoute] int id)
{
var result = await answerServices.GetByID(id);
if (result == null)
{
return NotFound();
}
return Ok(result);
}
}
}

Related

ArgumentNullException: Value cannot be null. (Parameter 'value')

I am having trouble with loging in from postman to my API. I get the roles back no problem but when they are used as parameters in the tokenservice they just stop working I get the following error :
Error
This is my endpoint :
[HttpPost("login")]
public async Task<IActionResult> Login(LoginUser loginData)
{
var userFromDb = await _userManager.FindByNameAsync(loginData.UserName);
if (userFromDb == null) return NotFound();
var result = await _signinManager.CheckPasswordSignInAsync(userFromDb, loginData.Password, false);
if (result == null) return BadRequest("Invalid Password");
var role = await _userManager.GetRolesAsync(userFromDb);
return Ok(
new
{
result = result,
username = userFromDb.UserName,
email = userFromDb.Email,
token = _tokenService.GenerateToken(userFromDb, role)
}
);
}
And this is the Token Service :
public class TokenService : ITokenService
{
private readonly IConfiguration _config;
public TokenService(IConfiguration config)
{
_config = config;
}
public string GenerateToken(IdentityUser user, IList<string> roles)
{
var claims = new List<Claim>
{
new Claim(JwtRegisteredClaimNames.GivenName, user.UserName),
new Claim(JwtRegisteredClaimNames.Email, user.Email)
};
if (roles != null)
{
foreach (var role in roles)
{
claims.Add(new Claim(ClaimTypes.Role, role));
}
}
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Token:Key"]));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256Signature);
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(claims),
Expires = DateTime.Now.AddDays(7),
SigningCredentials = creds,
Issuer = _config["Token:Issuer"],
};
var tokenHandler = new JwtSecurityTokenHandler();
var token = tokenHandler.CreateToken(tokenDescriptor);
return tokenHandler.WriteToken(token);
I have tried to rewrite my code and espacially this part :
if (roles != null)
{
foreach (var role in roles)
{
claims.Add(new Claim(ClaimTypes.Role, role));
}
}
because when I put an entry point in the token service it tells me that role is null
I checked your code on my application, the code works well, check the following screenshot:
The issue might relates the userFromDb, role value or the configuration value, I suggest you could set some break point to check the userFromDb and role value in the Login method and set break point in the TokenService to check whether the token generated success, refer to the following image:
Update:
the LoginUser:
public class LoginUser
{
public string UserName { get; set; }
public string Password { get; set; }
public string EmailAddress { get; set; }
}
For the IdentityUser, I'm using the Asp.net core Identity default IdentityUser model. because in your code, the GenerateToken method also use the IdentityUser Model.
I think you it is because I am using my own user instead of
IdentityUser
You can check the GenerateToken method and check the userFromDb, might the issue relate it, in the GenerateToken method, you might need to change your code to use your custom user model, instead of the IdentityUser model.

Force 2 Factor Authentication for new users when they login for the first time .NET Core

I am trying to configure the 2FA when users log in for the first time in .net core. So I added an if condition for checking if 2FA is not enabled then redirecting to creating MFA, however, a major flaw here is that the users can change the URL link on the browser to skip 2FA creation, how can I avoid this? Below are my Account Controller Codes:
Login Controller Methods
[HttpGet]
[AllowAnonymous]
public IActionResult Login(string? returnurl = null)
{
ViewData["ReturnUrl"] = returnurl;
return View();
}
[HttpPost]
[AllowAnonymous]
public async Task<IActionResult> Login(LoginViewModel model, string? returnurl = null)
{
ViewData["ReturnUrl"] = returnurl;
returnurl ??= Url.Content("~/");
if (ModelState.IsValid)
{
var user = await _userManager.FindByNameAsync(model.UserName);
var result = await _signInManager.PasswordSignInAsync(model.UserName, model.Password, model.RememberMe, lockoutOnFailure: true);
if (result.Succeeded)
{
if (user.TwoFactorEnabled==false)
{
return RedirectToAction(nameof(EnableAuthenticator), new { returnurl, model.RememberMe });
}
return LocalRedirect(returnurl);
}
if (result.RequiresTwoFactor)
{
return RedirectToAction(nameof(VerifyAuthenticatorCode), new { returnurl, model.RememberMe });
}
if (result.IsLockedOut)
{
return View("Lockout");
}
else
{
ModelState.AddModelError(string.Empty, "Invalid login attempt.");
return View(model);
}
}
return View(model);
}
Enable 2FA Controller Methods
[HttpGet]
public async Task<IActionResult> EnableAuthenticator()
{
string AuthenticatorUriFormat = "MY-OTP-SECRET-HERE";
var user = await _userManager.GetUserAsync(User);
await _userManager.ResetAuthenticatorKeyAsync(user);
var token = await _userManager.GetAuthenticatorKeyAsync(user);
string AuthenticatorUri = string.Format(AuthenticatorUriFormat, _urlEncoder.Encode("My-App-Name-Here"),
_urlEncoder.Encode(user.Email), token);
var model = new MFAViewModel() { Token = token, QRCodeUrl = AuthenticatorUri };
return View(model);
}
[HttpPost]
public async Task<IActionResult> EnableAuthenticator(MFAViewModel model)
{
if (ModelState.IsValid)
{
var user = await _userManager.GetUserAsync(User);
var succeeded = await _userManager.VerifyTwoFactorTokenAsync(user, _userManager.Options.Tokens.AuthenticatorTokenProvider, model.Code);
if (succeeded)
{
await _userManager.SetTwoFactorEnabledAsync(user, true);
}
else
{
ModelState.AddModelError("Verify", "Your two factor auth code could not be validated.");
return View(model);
}
}
return RedirectToAction(nameof(AuthenticatorConfirmation));
}
As mentioned in my comment, you could consider configuring the application use Claims-based authorization, after user login with 2FA successfully, you could add a claim store the 2FA login result and add it to the login user. After that, in your application, create a policy which requires the claim, and add the Authorize attribute on each controller.
Besides, you could also add the user's claims after 2FA , then create a custom middleware/Authorize attribute to validate each request and check whether the current user contains the claims or not. You can refer to the following links: Custom Authorization attributes and How To Override Attribute Class To Do Custom Authorization In .NET Core.

Blazor wasm get additional information and add to user claims

I am using identityserver4 for authentication and it's laid out something like this: identity server4 -> Web Api -> Blazor WASM Client(Standalone). everything is getting authenticated and working great. I get the authenticated user claims all the way to the wasm client.
I am now trying to add more claims which come directly from the database. I could have added the claims to the identityserver token but the token gets too big (> 2kb) and then identityserver stops working. apparently this is a known issue.
So iwant to build authorization and trying to keep the jwt token from identityserver small.
in the program.cs file i have a http client like so
builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });
builder.Services.AddOidcAuthentication(options =>// Configure your authentication provider options here.
// For more information, see https://aka.ms/blazor-standalone-auth
//builder.Configuration.Bind("Local", options.ProviderOptions);
... provider options
options.ProviderOptions.ResponseType = "code";
options.UserOptions.RoleClaim = "role";
}).AddAccountClaimsPrincipalFactory<CustomAccountClaimsPrincipalFactory>();
await builder.Build().RunAsync();
in the file CustomAccountClaimsPrincipalFactory i have this
public class CustomAccountClaimsPrincipalFactory
: AccountClaimsPrincipalFactory<RemoteUserAccount>
{
private const string Planet = "planet";
[Inject]
public HttpClient Http { get; set; }
public CustomAccountClaimsPrincipalFactory(IAccessTokenProviderAccessor accessor)
: base(accessor) {
}
public async override ValueTask<ClaimsPrincipal> CreateUserAsync(
RemoteUserAccount account,
RemoteAuthenticationUserOptions options)
{
var user = await base.CreateUserAsync(account, options);
if (user.Identity.IsAuthenticated)
{
var identity = (ClaimsIdentity)user.Identity;
var claims = identity.Claims.Where(a => a.Type == Planet);
if (!claims.Any())
{
identity.AddClaim(new Claim(Planet, "mars"));
}
//get user roles
//var url = $"/Identity/users/112b7de8-614f-40dc-a9e2-fa6e9d2bf85a/roles";
var dResources = await Http.GetFromJsonAsync<List<somemodel>>("/endpoint");
foreach (var item in dResources)
{
identity.AddClaim(new Claim(item.Name, item.DisplayName));
}
}
return user;
}
}
this is not working as the httpclient is not biolt when this is called and the http client uses the same builder which is building the base http client.
How do i get this to work?
You can create a IProfileService and customise it however you need:
var builder = services.AddIdentityServer(options =>
...
.AddProfileService<IdentityProfileService>();
public class IdentityProfileService : IProfileService
{
private readonly IUserClaimsPrincipalFactory<ApplicationUser> _claimsFactory;
private readonly UserManager<ApplicationUser> _userManager;
public IdentityProfileService(IUserClaimsPrincipalFactory<ApplicationUser> claimsFactory, UserManager<ApplicationUser> userManager)
{
_claimsFactory = claimsFactory;
_userManager = userManager;
}
public async Task GetProfileDataAsync(ProfileDataRequestContext context)
{
var sub = context.Subject.GetSubjectId();
var user = await _userManager.FindByIdAsync(sub);
if (user == null)
{
throw new ArgumentException("");
}
var principal = await _claimsFactory.CreateAsync(user);
var claims = principal.Claims.ToList();
//Add more claims like this
//claims.Add(new System.Security.Claims.Claim("MyProfileID", user.Id));
context.IssuedClaims = claims;
}
public async Task IsActiveAsync(IsActiveContext context)
{
var sub = context.Subject.GetSubjectId();
var user = await _userManager.FindByIdAsync(sub);
context.IsActive = user != null;
}
}
Keep the access token small and only include the necessary claims to get past the JwtBearer authentication step.
Then in the API that receives an access token, you can simply create an authorization policy that do lookup the users additional claims and evaluate if he have access or not.
You can do that in the simple policy definitions or the more advanced authorization handlers like the code below:
public class CheckIfAccountantHandler : AuthorizationHandler<CanViewReportsRequirement>
{
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context,
CanViewReportsRequirement requirement)
{
bool result = CallTheCheckIfAccountantService();
if(result)
context.Succeed(requirement);
return Task.CompletedTask;
}
}
A sample requirement can be defined as:
public class CanViewReportsRequirement : IAuthorizationRequirement
{
public int StartHour { get; }
public int EndHour { get; }
public CanViewReportsRequirement(int startHour, int endHour)
{
StartHour = startHour;
EndHour = endHour;
}
}
The important thing is to keep the complexity of the application low and not try to make it harder than it has to be. Just to make the system easy to reason about!

IdentityServer4 requesting a JWT / Access Bearer Token using the password grant in asp.net core

I've searched all over on requesting a JWT / Access Bearer Token using the password grant using IdentityServer4 in asp.net core, but I cant seem to find the right way to do it.
Below is the POST Request from which I register my user.
http://localhost:52718/account/register
Below is the Bearer Token GET Request from which I can get JWT Token using IdentityServer4
http://localhost:52718/connect/token
Below is the POST Request from which I Login my user
http://localhost:52718/account/signin
Now, what I'm trying to do is when I login my user then I want a JWT / Bearer Token same as I get from here http://localhost:52718/connect/token. When I hit this URL.
Here is my AccountController Code:
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Server.Models;
using Server.Models.AccountViewModels;
using Server.Models.UserViewModels;
namespace Server.Controllers
{
public class AccountController : Controller
{
private readonly UserManager<ApplicationUser> _userManager;
private readonly RoleManager<IdentityRole> _roleManager;
public AccountController(
UserManager<ApplicationUser> userManager,
RoleManager<IdentityRole> roleManager
)
{
_userManager = userManager;
_roleManager = roleManager;
}
[HttpPost]
public async Task<IActionResult> Register([FromBody]RegisterViewModel model)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var user = new ApplicationUser { UserName = model.UserName, FirstName = model.FirstName, LastName = model.LastName, Email = model.Email };
var result = await _userManager.CreateAsync(user, model.Password);
string role = "Basic User";
if (result.Succeeded)
{
if (await _roleManager.FindByNameAsync(role) == null)
{
await _roleManager.CreateAsync(new IdentityRole(role));
}
await _userManager.AddToRoleAsync(user, role);
await _userManager.AddClaimAsync(user, new System.Security.Claims.Claim("userName", user.UserName));
await _userManager.AddClaimAsync(user, new System.Security.Claims.Claim("firstName", user.FirstName));
await _userManager.AddClaimAsync(user, new System.Security.Claims.Claim("lastName", user.LastName));
await _userManager.AddClaimAsync(user, new System.Security.Claims.Claim("email", user.Email));
await _userManager.AddClaimAsync(user, new System.Security.Claims.Claim("role", role));
return Ok(new ProfileViewModel(user));
}
return BadRequest(result.Errors);
}
public async Task<IActionResult> Signin([FromBody]LoginViewModel model)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var result = await _userManager.FindByNameAsync(model.UserName);
if (result != null && await _userManager.CheckPasswordAsync(result, model.Password))
{
return Ok(new ProfileViewModel(result));
}
return BadRequest("Invalid username or password.");
}
}
}
When I hit signin method I successfully get the data of user.
But I also need a jwt / access token when user login my app.
Now my actual question is:
What can I do in my signin method so when user login it returns me token along with other user data. I hope I briefly explain my question.
Thanks
I've found my own question answer. Before starting I show you my that code where I'm Defining the client.
public static IEnumerable<Client> GetClients()
{
// client credentials client
return new List<Client>
{
// resource owner password grant client
new Client
{
ClientId = "ro.angular",
AllowedGrantTypes = GrantTypes.ResourceOwnerPassword,
ClientSecrets =
{
new Secret("secret".Sha256())
},
AllowedScopes = {
IdentityServerConstants.StandardScopes.OpenId,
IdentityServerConstants.StandardScopes.Profile,
IdentityServerConstants.StandardScopes.Email,
IdentityServerConstants.StandardScopes.Address,
"api1"
}
}
};
}
Now what I do in my Signin Method is to use the TokenClient class to request the token. To create an instance you need to pass in the token endpoint address, client id and secret.
Next I'm using Requesting a token using the password grant to allows a client to send username and password to the token service and get an access token back that represents that user.
Here is my Signin Code which I need to modify:
public async Task<IActionResult> Signin([FromBody]LoginViewModel model)
{
var disco = await DiscoveryClient.GetAsync("http://localhost:52718");
if (disco.IsError)
{
return BadRequest(disco.Error);
}
var tokenClient = new TokenClient(disco.TokenEndpoint, "ro.angular", "secret");
var tokenResponse = await tokenClient.RequestResourceOwnerPasswordAsync(model.UserName, model.Password, "api1 openid");
if (tokenResponse.IsError)
{
return BadRequest(tokenResponse.Error);
}
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var user = _userManager.FindByNameAsync(model.UserName);
var result = await _userManager.FindByNameAsync(model.UserName);
if (result != null && await _userManager.CheckPasswordAsync(result, model.Password))
{
return Ok(new ProfileViewModel(result, tokenResponse));
}
return BadRequest("Invalid username or password.");
}
Also I modify ProfileViewModel Class and add two new Token & Expiry:
public class ProfileViewModel
{
public string Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public string Token { get; set; }
public int Expiry { get; set; }
public ProfileViewModel()
{
}
public ProfileViewModel(ApplicationUser user, TokenResponse UToken = null)
{
Id = user.Id;
FirstName = user.FirstName;
LastName = user.LastName;
Email = user.Email;
Token = UToken.AccessToken;
Expiry = UToken.ExpiresIn;
}
public static IEnumerable<ProfileViewModel> GetUserProfiles(IEnumerable<ApplicationUser> users)
{
var profiles = new List<ProfileViewModel> { };
foreach (ApplicationUser user in users)
{
profiles.Add(new ProfileViewModel(user));
}
return profiles;
}
}
Now Here is my desire output. Hope this answer help others.

How to know if the user is Already SignedIn and thus prevent displaying the Login page in asp dot net core 2.0 Cookie based authentication?

This is the basic code snippet !!
Show me the Login page if none of the user is signedIn. If any user is active it should redirect to Index Page of Home Controller and should not show Login page !!
public class AccountController : CommonController
{
public AccountController(IOptions<ConnectionSetting> connString) : base(connString)
{
}
public IActionResult Index()
{
return RedirectToAction("Index", "Home");
}
[HttpGet]
[AllowAnonymous]
public IActionResult Login()
{
return View();
}
[HttpPost]
public async Task<IActionResult> Login(User user)
{
if (ValidateUser(user.UserName , user.Password))
{
var claims = new List<Claim>
{
new Claim(ClaimTypes.Name , user.UserName)
};
//Now Create an ClaimIdentity
var claimsIdentity = new ClaimsIdentity(claims, "BloggingCookie");
//Create Claim Principal using that Identity
ClaimsPrincipal principal = new ClaimsPrincipal(claimsIdentity);
await HttpContext.SignInAsync("BloggingCookie", principal );
return RedirectToAction("Index", "Home");
}
else
{
ViewData["Status"] = "Invalid Username or Password";
return View();
}
}
}
All you need is to add something like the following to the top of your login action:
if (User.Identity.IsAuthenticated)
{
return RedirectToAction("Index", "Manage");
}
You can of course redirect to wherever you like.