.net core get data for a user not the current user -- Identity - asp.net-core

I have the following which gets me my info:
public async Task<IActionResult> OnGetAsync()
{
var user = await _userManager.GetUserAsync(User);
if (user == null)
{
return NotFound($"Unable to load user with ID
'{_userManager.GetUserId(User)}'.");
}
var userName = await _userManager.GetUserNameAsync(user);
var email = await _userManager.GetEmailAsync(user);
var phoneNumber = await _userManager.GetPhoneNumberAsync(user);
Username = userName;
Input = new InputModel
{
Email = email,
PhoneNumber = phoneNumber,
FriendlyName = user.FriendlyName
};
IsEmailConfirmed = await _userManager.IsEmailConfirmedAsync(user);
return Page();
}
How would I get another users info... how to pass user that is not the current user I guess. I have tried several things and I think i'm missing something obvious here.
Thanks!

There are UserManager<TUser>.FindByXXX() methods that return user object:
Task<TUser> FindByEmailAsync(string email);
Task<TUser> FindByIdAsync(string userId);
Task<TUser> FindByLoginAsync(string loginProvider, string providerKey);
Task<TUser> FindByNameAsync(string userName);

Ended up using this:
var user = await _userManager.FindByIdAsync(Userid);
Getting Userid from the route.

Related

Get incremental changes for a group in Microsoft Graph in C#

I have the following code to get users from an AAD group:
public async Task<IGroupTransitiveMembersCollectionWithReferencesPage> GetGroupMembersPageByIdAsync(string groupId)
{
return await graphServiceClient
.Groups[groupId]
.TransitiveMembers
.Request()
.Top(999)
.GetAsync();
}
public async Task<IGroupTransitiveMembersCollectionWithReferencesPage> GetGroupMembersNextPageAsnyc(
IGroupTransitiveMembersCollectionWithReferencesPage groupMembersRef,
string nextPageUrl)
{
groupMembersRef.InitializeNextPageRequest(_graphServiceClient, nextPageUrl);
return await groupMembersRef
.NextPageRequest
.GetAsync();
}
public async Task<(List<AzureADUser> users,
string nextPageUrl,
IGroupTransitiveMembersCollectionWithReferencesPage usersFromGroup)> GetFirstUsersPageAsync(Guid objectId)
{
var users = new List<AzureADUser>();
var usersFromGroup = await GetGroupMembersPageByIdAsync(objectId.ToString());
usersFromGroup.AdditionalData.TryGetValue("#odata.nextLink", out object nextLink1);
var nextPageUrl = (nextLink1 == null) ? string.Empty : nextLink1.ToString();
users.AddRange((IEnumerable<AzureADUser>)(usersFromGroup));
return (users, nextPageUrl, usersFromGroup);
}
public async Task<(List<AzureADUser> users,
string nextPageUrl,
IGroupTransitiveMembersCollectionWithReferencesPage usersFromGroup)> GetNextUsersPageAsync(string nextPageUrl, IGroupTransitiveMembersCollectionWithReferencesPage usersFromGroup)
{
var users = new List<AzureADUser>();
usersFromGroup = await GetGroupMembersNextPageAsnyc(usersFromGroup, nextPageUrl);
usersFromGroup.AdditionalData.TryGetValue("#odata.nextLink", out object nextLink2);
nextPageUrl = (nextLink2 == null) ? string.Empty : nextLink2.ToString();
users.AddRange((IEnumerable<AzureADUser>)(usersFromGroup));
return (users, nextPageUrl, usersFromGroup);
}
I'm trying to learn about how I can use delta query functionality: https://learn.microsoft.com/en-us/graph/delta-query-groups so that next time when I run this, I can get the difference (new users/removed users/updated users) and return that list. Is that possible via delta query functionality?
I had a test in my asp.net core mvc project and you can get delta information by code below.
using Azure.Identity;
using Microsoft.Graph;
public async Task<IActionResult> Index()
{
var scopes = new[] { "https://graph.microsoft.com/.default" };
var tenantId = "your_tenant_name.onmicrosoft.com";
var clientId = "azure_ad_app_id";
var clientSecret = "client_secret";
var clientSecretCredential = new ClientSecretCredential(
tenantId, clientId, clientSecret);
var graphClient = new GraphServiceClient(clientSecretCredential, scopes);
//get group members
var users = await graphClient.Groups["groupId"].TransitiveMembers.Request().Top(999).GetAsync();
//get group member delta info
var delta = await graphClient.Groups.Delta().Request().Filter("id eq 'group_id'").GetAsync();
return View();
}

Problem with Identity UserManager error on password hashing

when I use this code:
var passwordHasher = new PasswordHasher();
string hashedPassword = passwordHasher.HashPassword(pp.Password);
User newUser = new User()
{
UserName = pp.NationalCode,
Pcode = pp.Pcode,
PasswordHash = hashedPassword,
};
var result = _UserManager.CreateAsync(newUser).Result;
the result will be succeeded, but if I use below code
User newUser = new User()
{
UserName = pp.NationalCode,
Pcode = pp.Pcode,
};
var result = _UserManager.CreateAsync(newUser,pp.Pasword).Result;
Result will be false.
On the other hand, because the password that is not systematically generated by Identity Hash, I can not use it in the login of users because (probably and certainly) the algorithms are different.
my codes in Login are :
if (ModelState.IsValid)
{
var user = _UserManager.FindByNameAsync(lc.UserName).Result;
_SignInManager.SignOutAsync();
if (user != null)
{
var result =await _SignInManager.PasswordSignInAsync(user,lc.Password, lc.IsPersistent, false);
if (result.Succeeded)
{
TempData["LoggedUserCode"] = user.Pcode;
return RedirectToAction("Index", "Home");
}
}
ModelState.AddModelError("", "Invalid User or Password");
}
The problem was solved with the help of an expert friend. In customizing the user table, I had mistakenly added a password field, which I removed it and the problem of adding new user solved.
Also, the post action was defined as async, I removed async and the login problem solved.

How to update AppDBContext in ASP.NET Core Web API

I am quite new to ASP.NET and I am bit stuck with this.
I am creating an entry in my DB while registering the user:
private async Task<bool> CreateEntryInUserActions(AppUser user)
{
var entity = new UserActionEntity
{
UserId = user.Id,
};
await _context.tbl_UserActions.AddAsync(entity);
await _context.SaveChangesAsync();
return true;
}
I want to change the IsPasswordChanged field in the UserActions table to true when a user changes his/her password.
I am trying something like:
private async Task<bool> UpdateUserAction()
{
var userId = _httpContextAccessor.HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value; // gives me current user's id
var user = _context.tbl_UserActions
.Where(x => x.UserId.ToString() == userId).Select(x => x.IsPasswordChanged);
}
but I am not sure how to proceed and update this to "true". How do I update this entry?
You need to fetch the useraction entity from the table and then set the IsPasswordChanged property to true.
Try this:
private async Task<bool> UpdateUserAction()
{
var userId = _httpContextAccessor.HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value; // gives me current user's id
var user = _context.tbl_UserActions.FirstOrDefault(x => x.UserId.ToString() == userId);
if(user != null) //check if the record is not null
{
user.IsPasswordChanged = true; // set the column to desired value
_context.tbl_UserActions.Update(user);
await _context.SaveChangesAsync();
}
}

how to include the role to the JWT token returning?

What I have in my mind when navigating through the application, I want to save the token to the localhost along with role name and I will check if the users have access to a certain link. Is that how it works? with Authgard in Angular 8?. Can you give me some insight of navigating an application with the role from Identity(which is built in from ASP.net core 3.1).
login
// POST api/auth/login
[HttpPost("login")]
public async Task<IActionResult> Post([FromBody]CredentialsViewModel credentials)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var identity = await GetClaimsIdentity(credentials.UserName, credentials.Password);
if (identity == null)
{
//return null;
return BadRequest(Error.AddErrorToModelState("login_failure", "Invalid username or password.", ModelState));
}
var jwt = await Tokens.GenerateJwt(identity, _jwtFactory, credentials.UserName, _jwtOptions, new JsonSerializerSettings { Formatting = Formatting.Indented });
return new OkObjectResult(jwt);
}
Generate Token Method
public static async Task<string> GenerateJwt(ClaimsIdentity identity, IJwtFactory jwtFactory, string userName, JwtIssuerOptions jwtOptions, JsonSerializerSettings serializerSettings)
{
var response = new
{
id = identity.Claims.Single(c => c.Type == "id").Value,
//probably here I want to send the role too!!
auth_token = await jwtFactory.GenerateEncodedToken(userName, identity),
expires_in = (int)jwtOptions.ValidFor.TotalSeconds
};
return JsonConvert.SerializeObject(response, serializerSettings);
}
}
You need to add claims information when generating your JWT.
Here`s an example
And another one:
1 part(how to implement JWT), 2 part(about claims here)

identity framekwork: how to get current login

[HttpPost]
public async Task<IActionResult> Upload(IFormFile files)
{
//var info = await _signInManager.GetExternalLoginInfoAsync();
//var user = await _userManager.FindByIdAsync(User.Identity.GetUserId());
//var user = await _userManager.FindByIdAsync(_userManager.GetUserId(Request.HttpContext.User));
//var user = User.Identity.GetUserId(HttpContext.User); _userManager.GetUserId(Request.HttpContext.User);
//var user1 = await GetCurrentUserAsync();
//var userId = user?.Id;
var filePath = Path.GetTempFileName();
var stream = files.OpenReadStream();
var name = files.FileName;
byte[] fileData = ReadFully(stream);
return Content("Error in uploads");
}
I have this action method. I have created login action whose result is success.
I am trying to get the ID of the current login user but im not able to get that. I have tried 50 ways to do that but failing again and again.
help needed
thanks in adv
I think you forgot to add HttpContext.user
var user = await _userManager.GetUserAsync(HttpContext.User);
if (user == null) return View("Error");