ASP.NET Core Authentication Id? - authentication

The tutorials on enabling authentication work all right, but what identifier should be used to store data for a user in the database? The only thing easily available is User.Name, which seems to be my email address.
I see in the database there is an AspNetUsers table with that as the UserName column, and a varchar Id column that appears to be a GUID and is the primary key. It seems like the 'Id' field is the logical value to use, but it's not readily available in my app. I found I can get to it like this:
string ID_TYPE = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier";
var id = User.Claims.Where(x => x.Type == ID_TYPE).Select(x => x.Value).FirstOrDefault();
But that seems like a weird way to go about it. Is that the proper value to use say if I want to create a 'Posts' table that has a user associated with a post?
I've looked at these pages and it seems that a lot of this might be due to Microsoft integrating the same login process with ActiveDirectory.
Is there a reason to make the id so hard to get to and the name so easy? Should I be using the name instead? Should I be careful not to let the user change their user name then?

The shortest path to UserId is:
User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
Or create extension like so if you need to access UserId a lot:
public static class ClaimsPrincipalExtensions
{
public static string GetUserId(this ClaimsPrincipal principal)
{
if (principal == null)
return null; //throw new ArgumentNullException(nameof(principal));
string ret = "";
try
{
ret = principal.FindFirst(ClaimTypes.NameIdentifier)?.Value;
}
catch (System.Exception)
{
}
return ret;
}
}
Usage:
User.GetUserId()

In your controller use dependency injection to get the user manager:
Create a class MyUser that has your extended properties
public class MyUser : IdentityUser
{
public string MyExendedInfo { get; set; }
public int MyOtherInfo {get;set;}
}
add this property to the database using migration, or manually add it.
In Startup.cs in Configure Services add:
services.AddIdentity<MyUser, IdentityRole>()
Now inject this in your controller class:
private readonly UserManager<MyUser> _userManager;
public HomeController(
UserManager<MyUser> userManager)
{
_userManager = userManager;
}
Now you can access your additional proporties and your Id (if you still need this) in your action methods like this:
var user = await _userManager.GetUserAsync(HttpContext.User);
var id = user.Id;
var myExtendedInfo = user.MyExtendedInfo;
var myOtherInfo = user.MyOtherInfo;
etc
You can also update information about your user:
user.myExtendedInfo = "some string";
user.MyOtherInfo = myDatabase.pointer;
var result = await _userManager.UpdateAsync(user);
if (!result.Succeeded)
{
//handle error
}
So as long as you want only limited additional data stored in the database, you can create a custom user class, and use the Identity system to store it for you. I would not store it myself.
If however, you need to store large information in a separate table and/or reference the user from other tables, the Id is the correct field to use and you can access it as shown above.
I don't know what the best practice is for how much information can be stored in AspNetUsers, versus in claims, versus in your own table, but since the provided table already stores things like user name, phonenumber etc, I think it is Ok to extend it like this.

Related

How to add a newly created user to a specific security group in sensenet?

When the user registers an account in my web application I would like for them to be added to the security group identified users so they have the necessary permissions to run my web application. This is what I've tried.
using SenseNet.ContentRepository.Storage;
using SenseNet.ContentRepository.Storage.Security;
namespace DerAssistantService.Actions
{
public static class UserActions
{
[ODataAction]
public static Content RegisterUser(Content content, string email, string password)
{
if (string.IsNullOrEmpty(email))
throw new ArgumentNullException(nameof(email));
if (string.IsNullOrEmpty(password))
throw new ArgumentNullException(nameof(password));
var username = email.Split('#').First();
using (new SystemAccount())
{
var user = Content.CreateNew("User", content.ContentHandler, username);
user["FullName"] = username;
user["Email"] = email;
user["LoginName"] = email;
user["Enabled"] = true;
user["Password"] = password;
user.Save();
var identifiedUsers = Node.Load<Group>("/Root/IMS/BuiltIn/Portal/IdentifiedUsers");
identifiedUsers.AddMember(user); // Error because type Content is not of type IGroup
return user;
}
}
}
}
The AddMember method of the group class expects either an IUser or an IGroup instance. The user you created previously is of the Content type, which is a wrapper type sensenet uses for everything. The underlying business object sits inside that content object, you can extract it using the ContentHandler property:
identifiedUsers.AddMember(user.ContentHandler as IUser);
The Content object represents the upper, generic API layer where you find fields for example. The lower layer, accessible by the ContentHandler property represents the business layer with strongly typed classes like User, File or Workspace.

Nhibernate mapping at run time

I am developing a site in which nhibernate is using. that is working fine for static mapping. but problem that i apply this application on existing database. so is there any way that mapping of classes took place at run time. i mean user provide tables and column names for mapping. Thanks
From your question I interpret you saying that the POCO classes exists, but you don't know the table or column names at build time.
So, if you already had this class:
public class MyGenericClass
{
public virtual long Id { get; set; }
public virtual string Title { get; set; }
}
You could bind it to a table and columns at runtime:
string tableName; // Set somewhere else by user input
string idColumnName; // Set somewhere else by user input
string titleColumnName; // Set somewhere else by user input
var configuration = new NHibernate.Cfg.Configuration();
configuration.Configure();
var mapper = new NHibernate.Mapping.ByCode.ModelMapper();
mapper.Class<MyGenericClass>(
classMapper =>
{
classMapper.Table(tableName);
classMapper.Id(
myGenericClass => myGenericClass.Id,
idMapper =>
{
idMapper.Column(idColumnName);
idMapper.Generator(Generators.Identity);
}
);
classMapper.Property(c => c.Title,
propertyMapper =>
{
propertyMapper.Column(titleColumnName);
}
);
}
);
ISessionFactory sessionFactory = configuration.BuildSessionFactory();
ISession session = sessionFactory.OpenSession();
////////////////////////////////////////////////////////////////////
// Now we can run an SQL query over this newly specified table
//
List<MyGenericClass> items = session.QueryOver<MyGenericClass>().List();
I don't think that could be possibly with NHibernate, but you could use a workaround.
You could use a view instead a table for the NHibernate mapping.
And in runtime, you could create that View or update it with the especified user mapping you need.
For example, you define a mapping in NHibernate to a view named ViewMapped with two columns Name and Mail.
And in the other hand, the user has a table with three columns Name, SecondName, EMail.
you can create a view on runtime with the following select:
(SELECT Name + ' ' + SecondName as Name, EMail as Mail FROM tableName) AS ViewMapped
I hope that helps you, or at least leads you to a solution.

MVC DBContext, how to connect to a table?

im just creating my first MVC applicaiton and am having trouble connecting to my database located on my sql server.
i have added the connection string to the web config as normal, created a model with all the fields in.
i created a model and created a new DBContext as there wasnt one listed. this created the below file
im not sure how it connects to the right table in my SQLDB, how do i do this?
also how do i make it run stored procedures?
Thanks
public EquipmentDBContext()
: base("name=ITAPPConnectionString")
{
}
public DbSet<Equipment> Equipments { get; set; }
public EquipmentDBContext()
: base("name=ITAPPConnectionString")//this name should be the name of database
{
}
public DbSet<Equipment> Equipments { get; set; }
here you say you have a
Datamodoel called Equipment. Your context also defines a single property, Equipments, which is of type DbSet. This property acts as a collection that allows you to query the data in you table in database as though it were an in-memory collection of objects.
So, if you create an object of class EquipmentDbContext in controller named lets say db, then you can access the data in table with something like
db.Equipments
To expand further on Cybercop's answer you would do something like this
using (var context = new EquipmentDBContext())
{
var equipments = context.Equipments.ToList();
var equipment = context.Equipments.FirstOrDefault(c=>c.Id == 1);
var blueThings= context.Equipments.Where(c=>c.Color == "blue").ToList();
}

How do I manage profiles using SimpleMembership?

I have an ASP.NET MVC 4 site based off the internet template. I am using the SimpleMembership which i set up with that template.
I can modify the Users table which has been creted for me but I am unsure as to the "correct" way to modify the extra fields I have added. I want Fullname, Email etc and have added them to the user table but there appears no way to update through the SimpleMembership WebSecurity.* static methods.
Are you supposed to just update those properties yourself using EF outside of the SimpleMembership API?
1 - You need to enable migrations, prefereably with EntityFramework 5
2 - Move your
WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId", "EmailAddress", autoCreateTables: true);
to your Seed method in your YourMvcApp/Migrations/Configuration.cs class
protected override void Seed(UsersContext context)
{
WebSecurity.InitializeDatabaseConnection(
"DefaultConnection",
"UserProfile",
"UserId",
"UserName", autoCreateTables: true);
if (!Roles.RoleExists("Administrator"))
Roles.CreateRole("Administrator");
if (!WebSecurity.UserExists("lelong37"))
WebSecurity.CreateUserAndAccount(
"lelong37",
"password",
new {Mobile = "+19725000000", IsSmsVerified = false});
if (!Roles.GetRolesForUser("lelong37").Contains("Administrator"))
Roles.AddUsersToRoles(new[] {"lelong37"}, new[] {"Administrator"});
}
Now EF5 will be in charge of creating your UserProfile table, after doing so you will call the WebSecurity.InitializeDatabaseConnection to only register SimpleMembershipProvider with the already created UserProfile table, also tellling SimpleMembershipProvider which column is the UserId and UserName. I am also showing an example of how you can add Users, Roles and associating the two in your Seed method with custom UserProfile properties/fields e.g. a user's Mobile (number) and IsSmsVerified.
3 - Now when you run update-database from Package Manager Console, EF5 will provision your table with all your custom properties
For additional references please refer to this article with sourcecode:
http://blog.longle.net/2012/09/25/seeding-users-and-roles-with-mvc4-simplemembershipprovider-simpleroleprovider-ef5-codefirst-and-custom-user-properties/
They made it easy to modify the profile with SimpleMembership. SimpleMembership is using the code first EF model and the user profile is defined in the file AccountModels.cs that is generated as part of the Internet template for MVC 4. Just modify the class UserProfile and add the new fields in the class definition. For example, adding a field for email would look something like this:
[Table("UserProfile")]
public class UserProfile
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
public string UserName { get; set; }
public string Email { get; set; }
}
Here is an example on how you would access the email field:
var context = new UsersContext();
var username = User.Identity.Name;
var user = context.UserProfiles.SingleOrDefault(u => u.UserName == username);
var email = user.Email;
Here is what the database looks like after adding the email field.
There is a good blog that describes some of the changes in SimpleMembership here. You can also find more detailed information on customizing and seeding SimpleMembership here.
if you look right around line 273 of the accountcontroller you'll find this line
db.UserProfiles.Add(new UserProfile { UserName = model.UserName });
Looks like even OOTB they (MS) are doing just as you suggested and using EF to update.
I too, am looking for the "correct" way of updating and accessing these properties.
Edit:
Here's my solution (I'm happy if someone says there's an OOTB way to do this).
wrap UserProfile (the .net Entity from SimpleMembership) in a session class.
public static class sessionHelpers {
public static UserProfile userProfile
{
get
{
if (HttpContext.Current.Session["userProfile"] != null)
{
return HttpContext.Current.Session["userProfile"] as UserProfile;
}
else
{
using (UsersContext db = new UsersContext())
{
HttpContext.Current.Session["userInfo"] =
db.UserProfiles.Where(x => x.UserName ==
HttpContext.Current.User.Identity.Name).FirstOrDefault();
return db.UserProfiles.Where(x => x.UserName ==
HttpContext.Current.User.Identity.Name).FirstOrDefault();
}
}
}
set { HttpContext.Current.Session["userProfile"] = value; }
}
}
From this you can access the profile table by doing
string foo = sessionHelpers.userProfile.FIELDNAME;
where sessionHelpers is my wrapper class. The if block just ensures that if it hasn't been set in the current session that accessing it will attempt to get it.
You need to add them to your Database ( done according to description )
add them to the view ( edit , add , delete , and view ) unless modified
add them to your model in UserProfiles
Then it will work.

Handle navigation properties when adding new object to entity model

I have the following data model:
I am writing a WCF service that needs to support adding new Report:
public bool CreateNewReport(Report report)
{
MyEntities context = new MyEntities();
context.AddToReports(Report);
context.SaveChanges();
}
So my method gets a report object that was made on the client and adds it to the database throught the data context. (all of the members are included in the DataContract)
My question is regarding navigation properties.
Do the client also needs to create a user object and put it in the new report object before sending it ?
What is the best way to approach this ? one way i think of is adding a UserId field in the ReportEntity
when a new report is inserted, how do i update the UserEntity Report nav property that with the new Report ?
Thanks.
If you import your database, generate navigation properties (the properties in your picture) AND foreign id properties (then you have for example an User and UserID property in your report class). This way you can set the UserID in your client and send it to the server and add it with AddToReports... If you send the whole user object you have to attach it to the entity context otherwise the user will be created once again...
Attach the referenced user: (but it's better to send the user only by id)
public bool CreateNewReport(Report report)
{
using (MyEntities context = new MyEntities())
{
context.AddToReports(Report);
context.Users.Attach(report.User);
context.SaveChanges();
}
}
To change the report of a user:
public bool ChangeUserToNewReport(int userid, Report newReport)
{
using (MyEntities context = new MyEntities())
{
var user = context.Users.Single(u => u.ID = userid);
user.Report = newReport;
context.SaveChanges();
}
}
For an existing report:
public bool ChangeUserReport(int userid, Report existingReport)
{
using (MyEntities context = new MyEntities())
{
context.Reports.Attach(existingReport);
var user = context.Users.Single(u => u.ID = userid);
user.Report = existingReport;
context.SaveChanges();
}
}
This is a sample how your model should look like. Double click on the association line to open the dialog. You can see that the Person and PersonID properties are the same. If you create your model like this, VS should generate the correct SQL.