How to Authenticate using MVC5RC/RTW with existing database - visual-studio

I originally asked this question when Identity was in beta. The classes and interfaces have changed considerably since then and it appears the RTW version has some modifications again over the RC version. In principle I need to achieve the following.
authenticate the local login against my usertable tblMembers which contains the userid field and password which are the two items I need to authenticate.
have access to my tblMember record/class via the Controller.User property (Prior to MVC5 identity I had achieved this using the membership provider methods.) regardless of if the user logged in via the localuser method or via one of the other OAuth providers (Twitter, Google etc).
Ability to display my own custom username despite the login method. Local users login with a userid 1234567 and a password, ideally I would like to display "John Smith (1234567)" regardless of the authentication method (local/Twitter etc)
Initially I'm unsure as to what my memberclass should be inheriting from It appears from the
aspIdentitySample project that I should be using IdentityUser?
public partial class tblMember
{
public int id { get; set; }
public string membership_id { get; set; }
public string password { get; set; }
....other fields
}
Are there any new or updated examples of integrating your existing database/user tables with the ASP.NET Identity system?

I am also adding the identity tables to my database. If you create a new web project in visual studio 2013 you will see that now in RTM everything works better than RC plus you will see the
following table
public class ApplicationUser : IdentityUser
{
}
So Instead of ApplicationUser you can call your table tblMembers
public class tblMembers : IdentityUser
{
}
your table tblMembers will inherit Id Username Password security stamp and a discriminator column saying this is a tblMemeber
without making custom classes for authentication the easiest thing to do would be just to make the username the combination of your old usernames and userids. Then store the users real name or old username without the user id in a separate column.
have the users register with the built in user login and they can go to manage account and click use another service to log in. This will link the Google account to their regular account, so no matter which one they use it will log them in to the same account. If you have users with connected table information, I suggest you seed your table with all the users with something similar to the register method found in the template.Then just match the new combined username and Id to the old ones and populate data where needed in sql management studio.
Again a lot of issues in RC with extending IdentityUsers have been fixed. Microsoft is already adding more features to the identity user store and this tutorial http://www.windowsazure.com/en-us/develop/net/tutorials/web-site-with-sql-database/ is supposed to be updated soon. I plan on making my own walk through when i'm done changing my database but for now I hope my suggestions even though they are a simpler solution than you might want to implement.

You can do this easily by modifying the IdentityModel.cs as per the below:
Override OnModelCreating in your DbContext then add the following, this will change AspNetUser table to "Users" you can also change the field names the default Id column will become User_Id.
modelBuilder.Entity<IdentityUser>()
.ToTable("Users", "dbo").Property(p => p.Id).HasColumnName("User_Id");
or simply the below if you want to keep all the standard column names:
modelBuilder.Entity<IdentityUser>()
.ToTable("Users", "dbo")
Full example below (this should be in your IdentityModel.cs file) i changed my ApplicationUser class to be called User.
public class User : IdentityUser
{
public string PasswordOld { get; set; }
public DateTime DateCreated { get; set; }
public bool Activated { get; set; }
public bool UserRole { get; set; }
}
public class ApplicationDbContext : IdentityDbContext<User>
{
public ApplicationDbContext()
: base("DefaultConnection")
{
}
protected override void OnModelCreating(System.Data.Entity.DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<IdentityUser>()
.ToTable("Users", "dbo").Property(p => p.Id).HasColumnName("User_Id");
modelBuilder.Entity<User>()
.ToTable("Users", "dbo").Property(p => p.Id).HasColumnName("User_Id");
}
}
Please note i have not managed to get this working if the current table exists.
Also note whatever columns you do not map the default ones will be created.
Hope that helps.

I'm starting to think (partially due to the lack of information in this area), that it may be easier to user the default identity classes, but to provide referential integrity to my own user table from the AspNetUsers table.
If i add a custom linking field into the AspNetUsers table is it possible to access my tables from the Controllers.User property? i.e. Controller.User.tblMember.Orders?

Related

How to Auto Generate of Guid ID in .NET CORE 6?

In my request data, if I have a duplication Guid ID, I want to generate a new Guid ID automatically. How to do it?
public class Roster { public Guid Id {get; set;} }
Here Guid Id is the primary key.
When I made an api post request, what would be the value I give for Guid Id?
If you use SQL and EntityFramework Core you could use this inside your model:
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid ActivityId { get; set; }
This will tell EF:
this property is the PRIMARY KEY of the table hence the [KEY]
this property should be automatically generated by the database
FYI you need to set a DEFAULT value for you SQL column like so:
(newsequentiaid()) tells SQL that he's in charge of creating a Globally Unique Id everytime you add a record to that table
Don't know if this is the answer you were looking for (nex time provide more info for us) anyway
hope this helps you Cheers!
UPDATE
I do not know if my solution works with MySQL i use it for SQL. Searching a bit online i found no resources to newsequentialid in MySQL database (but i could be wrong, do your own research if you'd like).
Anyway i just don't set it for example:
var activityDB = await context.Activity.FirstOrDefaultAsync(c => c.ActivityId == activity.ActivityId);
if (activityDB == null)
{
activityDB = new Activity();
context.Activity.Add(activityDB);
}
activityDB.Code = activity.Code;
activityDB.Description = activity.Description;
activityDB.Status = activity.Status;
Here's what the code does
check if my id exists if yes i have to edit if is null i don't
create new activity and edit
automatically EF nows what id to handle therefore no need to se it
If there is it means im editing for that id if not will create it automatically

DbSet declaration does not accept the table name shown in database

I have developed an app for tracking multi-party coordination on proposed change requests.
I only use two table, with a one-to-one relationship. One table correlates to fields on an existing official paper form, while the other table tracks additional information in a one-to-one relationship.
I previously developed this app as a standalone project, using MS Access, but now, I am adding the app to a "one-stop shopping" SQL Server database environment.
My problem comes in my DbSet statements. The table names which the DBA chose result in errors which I never had when the app was stand-alone:
Below is the C# code for the DbContext portion:
namespace FormTracker
{
public class ApplicationDbContext:DbContext
{
public ApplicationDbContext(DbContextOptions options) : base(options)
{
}
public DbSet<T__AODMS_1067_tracking_fields> T__AODMS_1067_tracking_fieldss { get; set; }
public DbSet<T__AODMS_1067_tracking_non_1067_fields> T__AODMS_1067_tracking_non_1067_fields_Recordss { get; set; }
}
}
The portions between the <> are what is being flagged when build is executed.
Any ideas? possibly something totally obvious that I'm not seeing?

How to tell default value from clearing with FromBody in ASP.NET Core Web API

I have coded in C# for years, but I am new to ASP.NET Core. I have created a Web API where I generated my Model classes from an existing database and used the scaffolding to create a Controller for each model that gives me Get, Put, Post, and Delete. My question is how do I know if the caller is clearing a value vs the value is the default for the C# object?
For example, in Vue.js I send
var sendstuff = {userName: "TestUser1", userId: 7, email: null};
In C#, my user object has
public int UserId { get; set; }
public string UserName { get; set; }
public string Email { get; set; }
public string FavoriteColor { get; set; }
In my controller, my put method begins
public async Task<IActionResult> PutUsers([FromRoute] int id, [FromBody] User user)
My User instance in the database is TestUser1, 7, test#test.com, purple. The User that comes into PutUsers is TestUser1, 7, null, null.
At this point, I want to compare the values sent in for user 7 to the values in the database for user 7. However, since both FavoriteColor (that is not sent) and Email (that is sent) look the same as they both appear as null, how do I know whether or not it should be changed? I want test#test.com to be cleared, but I want purple to remain.
It seems my only other option is to have Vue.js send in every single column for every table, with the values either the original value I don't want changed or the new value. This doesn't feel right.
Am I missing something?
Thanks in advance!
The only way I can think of is to accept a Generic Json-Object and checking wether or not the Properties are set.
Most Json Frameworks will be able to cast to a specific Object from the Json Object so you won't even need to change your further code.

Register/Loginwith facebook and google on mobile and web data store

I want users to be able to log in with facebook/google via a mobile app(android and ios) and/or a website(built with asp.net MVC)...
What should my database be storing to make authentication work across mobile app and website? userId , google/facebook token?
Im unsure how to go about saving user information.
Should I combine this with OWIN? I dont know much about asp.net identity but have seen that it fairly straight forward with 3rd party providers....the question is if i login from the mobile app for the first time should i programatically add the new user to the database?
So far I think this seems like the best link: http://bitoftech.net/2014/07/16/enable-oauth-refresh-tokens-angularjs-app-using-asp-net-web-api-2-owin/
but I'm hoping theres a simpler way.
Im getting google/fb tokens and sending them to the server to get the ids of the users...
What do i need to do here, so that if the google/fb user logs in through the web, they will be recognised as the same user.
It seems like MS have made it so easy to use ASP.Net Identity to set up social login for the web, but have ignored how that can be used with mobile to use a sql server db to store user/membership details...
Just trying to work out the best way of managing users for mobile and web as one
This link describes everything you are looking for http://www.asp.net/mvc/overview/security/create-an-aspnet-mvc-5-app-with-facebook-and-google-oauth2-and-openid-sign-on
What you have to store in the database in order to check if user already exist in your database or not can be get from the response you will get from Facebook or Google after a users credential verified, Facebook & Google must be giving the details of the users back in response. like Email Id, Date of birth etc., you can save these details in your database and at every login check it user already exist or not and register accordingly.
Details that comes in response is mentioned in another post WebApi ASP.NET Identity Facebook login
public class FacebookLoginModel
{
public string token { get; set; }
public string username { get; set; }
public string userid { get; set; }
}
public class FacebookUserViewModel
{
public string id { get; set; }
public string first_name { get; set; }
public string last_name { get; set; }
public string username { get; set; }
public string email { get; set; }
}
It's relatively straightforward for Google Sign in.
The easiest way is for you to store the unique ID in your local database that Google returns for each account that you authenticate with it.
You can call the getSignInAccount method after the sign-in intent succeeds.
Auth.GoogleSignInApi.getSignInResultFromIntent(data);
GoogleSignInAccount acct = result.getSignInAccount();
String personName = acct.getDisplayName();
String personEmail = acct.getEmail();
**String personId = acct.getId();**
Uri personPhoto = acct.getPhotoUrl();
And whether the person signs in from the phone or the mobile, you know it is the same person. More details at https://developers.google.com/identity/sign-in/android/people
In any case, you will have to programmatically store the user in your database every time someone new logs in. So you will have to store their personID as an additional field to authenticate them overtime.

Can't Persist Field to Aspnet_Users via NHibernate/ActiveRecord

I'm using ActiveRecord with NHibernate on the backend. I've set up a mapping for Users; I can create/retrieve/register users without any issues.
I now want to add an association called Role to my users (many users per role). I've created the appropriate Role class, tables, data, etc. and everything seems to be working on that end as well.
The problem is that when I save a user and associate a Role, that association does not persist to the database.
I've added a RoleId (int16) column to the aspnet_Users table to match the Role table's Id (int16) column. I've tried using Save and SaveAndFlush without success.
Here's some code:
Role superUser = Role.First(r => r.name == "Super User");
User me = User.First(r => r.UserName == myUserName);
me.Role = superUser;
me.Save(); // Or: SaveAndFlush
When debugging, I can see the association on the objects when they're saved (i.e. me.Role is not null and has the right attributes/properties/etc.) However, when I look at the database, the RoleId value for that user is still NULL. (SaveAndFlush doesn't make a difference.)
What am I missing?
I've read somewhere on SO that extending the users table is usually done by adding another table and linking the two by a foreign key; I assume the classes would then use inheritance by composition for the new ExtendedUser class. Assuming I don't want to go that route, why isn't this working? Is it because of the specific ASP.NET MVC stored procedures et. all?
Some relevant mapping:
[ActiveRecord("aspnet_Users", Mutable = false)]
public class User : ActiveRecordLinqBase<User>
{
[PrimaryKey(PrimaryKeyType.Assigned)]
public Guid UserId { get; set; }
// ...
[BelongsTo("RoleId", Cascade = CascadeEnum.SaveUpdate)]
public Role Role { get; set; }
}
[ActiveRecord]
public class Role : ActiveRecordLinqBase<Role>
{
[PrimaryKey]
public int Id { get; set; }
// ...
[HasMany(Inverse = true)]
public IList<User> Users { get; set; }
[Property]
public string Name { get; set; }
}
Edit: mutable="false" - this clearly stands that entity is read only, which is the source of your problem.
Immutable classes, mutable="false", may not be updated or deleted by the application. This allows NHibernate to make some minor
performance optimizations.
Also:
I believe that you need to have cascading defined. You are not saving just the entity itself but also reference to other entity. Use attributes, fluent config or hbml to define this the way you need. Here are the cascading options:
Here is what each cascade option means:
none - do not do any cascades, let the users handles them by
themselves.
save-update - when the object is saved/updated, check the assoications and save/update any object that require it (including
save/update the assoications in many-to-many scenario).
delete - when the object is deleted, delete all the objects in the assoication.
delete-orphan - when the object is deleted, delete all the objects in the assoication. In addition to that, when an object is
removed from the assoication and not assoicated with another object
(orphaned), also delete it.
all - when an object is save/update/delete, check the assoications and save/update/delete all the objects found.
all-delete-orphan - when an object is save/update/delete, check the assoications and save/update/delete all the objects found. In additional to that, when an object is removed from the assoication and not assoicated with another object (orphaned), also delete it.
You may want to read this article.

Resources