In an ASP.NET MVC 5 application how would I go about getting a Username from a given UserId and display it in a View?
Note - I do not need the Username of the current User.
Based on your comment, you are using ASP.Net Identity. I assume you already have ApplicationUserManager. For example,
private ApplicationUserManager _userManager;
protected ApplicationUserManager UserManager
{
get { return _userManager ?? (_userManager =
HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>()); }
}
Then you can call FindById method.
var user = UserManager.FindById(id);
string username = user.UserName;
Related
In a Jhipster 4.4.1 application with Mongodb, JWT.
I need the user logged in for a query, and I do not know how I can retrieve it in a java controller (Resource)
In SecurityUtils I do not see how to get the ID
public static String getCurrentUserLogin() {
SecurityContext securityContext = SecurityContextHolder.getContext();
Authentication authentication = securityContext.getAuthentication();
String userName = null;
if (authentication != null) {
if (authentication.getPrincipal() instanceof UserDetails) {
UserDetails springSecurityUser = (UserDetails) authentication.getPrincipal();
userName = springSecurityUser.getUsername();
} else if (authentication.getPrincipal() instanceof String) {
userName = (String) authentication.getPrincipal();
}
}
return userName;
}
I can capture the user ID logged in, without consulting the database.
Thank you
If you need the current user, then you can query against login as given by getCurrentUserLogin() in your question because it's unique anyway.
If you really want the ID, then have a poke around AccountResource and you'll see that UserDTO and User have a .getID() method.
In my MVC 5 web app I have this (in AccountController.cs):
// Used for XSRF protection when adding external sign ins
private const string XsrfKey = "XsrfId";
and
public string SocialAccountProvider { get; set; }
public string RedirectUri { get; set; }
public string UserId { get; set; }
public override void ExecuteResult(ControllerContext context)
{
var properties = new AuthenticationProperties { RedirectUri = RedirectUri };
if (UserId != null)
{
properties.Dictionary[XsrfKey] = UserId;
}
context.HttpContext.GetOwinContext().Authentication.Challenge(properties, SocialAccountProvider);
}
How exactly is it being used for protection?
Should I set the value of XsrfKey to something more random?
Take a look at ManageController methods LinkLogin and LinkLoginCallback:
//
// POST: /Manage/LinkLogin
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult LinkLogin(string provider)
{
// Request a redirect to the external login provider to link a login for the current user
return new AccountController.ChallengeResult(provider, Url.Action("LinkLoginCallback", "Manage"), User.Identity.GetUserId());
}
//
// GET: /Manage/LinkLoginCallback
public async Task<ActionResult> LinkLoginCallback()
{
var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync(XsrfKey, User.Identity.GetUserId());
if (loginInfo == null)
{
return RedirectToAction("ManageLogins", new { Message = ManageMessageId.Error });
}
var result = await UserManager.AddLoginAsync(User.Identity.GetUserId(), loginInfo.Login);
return result.Succeeded ? RedirectToAction("ManageLogins") : RedirectToAction("ManageLogins", new { Message = ManageMessageId.Error });
}
These are the methods that handle linking of external accounts (i.e. Google, Facebook, etc.). The flow goes like this:
User clicks "Link Account" button, which calls a POST to LinkLogin method.
LinkLogin returns ChallengeResult object, with callback url set to LinkLoginCallback method.
ChallengeResult.ExecuteResult is called by MVC framework, calls IAuthenticationManager.Challenge, which causes a redirect to the specific external login provider (let's say: google).
User authenticates with google, then google redirects to callback url.
The callback is handled with LinkLoginCallback. Here, we want to prevent XSRF and verify that the call was initiated by a user, from a page served by our server (and not by some malicious site).
Normally, if it was a simple GET-POST sequence, you would add a hidden <input> field with an anti-forgery token and compare it with a corresponding cookie value (that's how Asp.Net Anti-Forgery Tokens work).
Here, the request comes from external auth provider (google in our example). So we need to give the anti-forgery token to google and google should include it in the callback request. That's exactly what state parameter in OAuth2 was designed for.
Back to our XsrfKey: everything you put in AuthenticationProperties.Dictionary will be serialized and included in the state parameter of OAuth2 request - and consequentially, OAuth2 callback. Now, GetExternalLoginInfoAsync(this IAuthenticationManager manager, string xsrfKey, string expectedValue) will look for the XsrfKey in the received state Dictionary and compare it to the expectedValue. It will return an ExternalLoginInfo only if the values are equal.
So, answering your original question: you can set XsrfKey to anything you want, as long as the same key is used when setting and reading it. It doesn't make much sense to set it to anything random - the state parameter is encrypted, so no one expect you will be able to read it anyway.
Just leave it as is:
As the name of the member states it is a key:
private const string XsrfKey = "XsrfId";
It is defined in this manner to avoid "magic numbers" and then is used a little down in the scaffold code:
public override void ExecuteResult(ControllerContext context)
{
var properties = new AuthenticationProperties { RedirectUri = RedirectUri };
if (UserId != null)
{
properties.Dictionary[XsrfKey] = UserId;
}
context.HttpContext.GetOwinContext().Authentication.Challenge(properties, LoginProvider);
}
The value of the dictionary item is then set to the UserId property in the above code by using the XsrfKey member as the key.
IOW the code is already setting the XSRF dictionary item to the value of the user ID in the snippet. If you change the XsrfKey members value to anything else you will cause problems down the line, since the expected key "XsrfId" will have no value set.
If by changing it to something more random you are implying to change the value and not they key of the dictionary, or in other words, not set it to the user id then please see the following for an explanation of the anti forgery token inner workings.
http://www.asp.net/mvc/overview/security/xsrfcsrf-prevention-in-aspnet-mvc-and-web-pages
What is the correct way to get an Identity User Object (from the identity framework) of the currently logged in user in a controller?
I need to update some properties against the user (table AspNetUsers) and do not know the correct method of getting the user object so that I could do things such as:
var menuItem = context.MenuItems.First(m => m.Description == "New Order");
var user = ??????????
user.MenuItems.Add(menuItem);
context.SaveChanges();
I've slightly modified the original user model by adding a few properties and renaming the class:
public class User : IdentityUser
{
public string FirstName { get; set; }
public string LastName { get; set; }
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<User> manager)
{
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
return userIdentity;
}
public virtual ICollection<MenuItem> MenuItems { get; set; }
}
So how can I retrieve this User object from my controllers?
In the controller class use the namespace Microsoft.AspNet.Identity and the get the current user like this:
var user = User.Identity;
Example:
using Microsoft.AspNet.Identity;
...
public class FooController : Controller
{
[Authorize]
public ActionResult Index()
{
var user = User.Identity;
...
return View();
}
}
Edited
Getting Profile Information:
This link gives the steps to add profile information to your user.
To retrieve your user data you should:
Get the current logged in UserId, so you can look the user up in
ASP.NET Identity system
var currentUserId = User.Identity.GetUserId();
Instantiate the UserManager in ASP.Identity system so you can look
up the user in the system
var manager = new UserManager(new UserStore(new MyDbContext()));
Get the User object
var currentUser = manager.FindById(User.Identity.GetUserId());
Get the profile information about the user
currentUser.MyUserInfo.FirstName
Get username
var userName = User.Identity.Name;
Get the user using static method created below.
var user = GetCurrentUser(userName);
Static method to get user
public static User GetCurrentUser(string userName)
{
var userManager = new UserManager<User>(new UserStore<User>(new YourIdentityDbContext()));
var user = userManager.FindByName(userName);
return user;
}
I'm working on a new ASP.NET MVC project, using individual accounts stored in the database for authentication. Here's my class that will seed the database with sample data every time I test:
public class DevelopmentInitializer : DropCreateDatabaseAlways<ApplicationDbContext>
{
protected override void Seed(ApplicationDbContext context)
{
base.Seed(context);
var applicationUserManager = new ApplicationUserManager(new UserStore<ApplicationUser>(context));
var sampleUserOne = new ApplicationUser { UserName = "SampleUser", Email = "sample#example.com" };
var result = applicationUserManager.Create(sampleUserOne, "aaaaaa");
if (!result.Succeeded)
throw new Exception();
context.SaveChanges();
}
}
The Login action is as it is in the template:
//
// POST: /Account/Login
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
if (ModelState.IsValid)
{
var user = await UserManager.FindAsync(model.Email, model.Password);
if (user != null)
{
await SignInAsync(user, model.RememberMe);
return RedirectToLocal(returnUrl);
}
else
{
ModelState.AddModelError("", "Invalid username or password.");
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
The description of problem is very simple: Trying to log in using the seeded user's credentials fails.
Specifically, the FindAsync method returns null, even though the user is present in the database - FindByEmailAsync does find the seeded user.
However, creating a new account works and allows me to log in.
Why can't I log in as the seeded user, even though I can register a new account and log in using that?
I'm suspecting it has to do with how the passwords are hashed, but I don't know how to confirm this.
Am I seeding the account wrong? Should I not be creating a separate ApplicationUserManager in the Seed method? If not, how should I get one in order to call Create? I'm trying to understand how the new system works, before ending up locked out of my account or the users end up locked out of theirs in a deployed application.
The following code:
var user = await UserManager.FindAsync(model.Email, model.Password);
is expecting the userName to be passed in, not the email address.
This simple change should take care of things:
var user = await UserManager.FindAsync(model.UserName, model.Password);
If you see the definition of PasswordSignInAsync, it requires the username string and not the email. Maybe the reason why the UI for login ask for email is because of the autogenerated code where the email would be equal to username inside the controller.
I am trying to store a whole truckload of information about a user from a webservice. As this is information about the currently authenticated user, I thought it would make sense to store that information in a custom IIdentity implementation.
The custom MagicMembershipProvider.GetUser(string id, bool userIsOnline) calls the webservice and returns a MagicMembershipUser instance with all the fields populated (department, phone number, other employee info).
The custom membership provider and custom membership user both work fine.
What and where is the best way to put the membership user information into the IPrincipal User object that is accessible in every controller?
I have been trying to wrap my brain around the program flow of security with IIdentity, IPrincipal and Role authorization in an MVC2 application -- but I'm really struggling here and could use some mentoring. There a Internet Ton of articles about the parts, but not much about the whole.
Edit
My best guess so far is to assign the HttpContext.Current.User in the FormsAuthenticationService:
public void SignIn(string userName, bool createPersistentCookie)
{
if (String.IsNullOrEmpty(userName))
throw new ArgumentException("Value cannot be null or empty.", "userName");
try
{
FormsAuthentication.SetAuthCookie(userName, createPersistentCookie);
MagicMembershipUser magicUser = _provider.GetUser("", false)
as MagicMembershipUser;
MagicIdentity identity = new MagicIdentity(userName, magicUser);
GenericPrincipal principal = new GenericPrincipal(identity, null);
HttpContext.Current.User = principal;
}
catch (Exception)
{
throw;
}
}
What and where is the best way to put the membership user information into the IPrincipal User object that is accessible in every controller?
In a custom [Authorize] filter implementation. You could override the AuthorizeCore method and call the base method and if it returns true query your membership provider and inject the custom magic identity into the context.
Example:
public class MagicAuthorizeAttribute : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
var isAuthorized = base.AuthorizeCore(httpContext);
if (isAuthorized)
{
var username = httpContext.User.Identity.Name;
var magicUser = _provider.GetUser(username, false) as MagicMembershipUser;
var identity = new MagicIdentity(username, magicUser);
var principal = new GenericPrincipal(identity, null);
httpContext.User = principal;
}
return isAuthorized;
}
}
Now all that's left is decorate your base controller with the [MagicAuthorize] attribute.