How to create New user identity out side from Account controller? - asp.net-mvc

I have merged my database with MVC asp.net Identity database and i want to creat a new user using asp.net identity from other controller ,but i could not successfully add the user even my code work without error this is the code:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Id,Email,EmailConfirmed,Password,SecurityStamp,PhoneNumber,PhoneNumberConfirmed,TwoFactorEnabled,LockoutEndDateUtc,LockoutEnabled,AccessFailedCount,UserName")] AspNetUsers aspNetUsers)
{
if (ModelState.IsValid)
{
// ApplicationUserManager manager = new ApplicationUserManager(new UserStore<ApplicationUser>());
// var manager = HttpContext.Current.GetOwinContext().GetUserManager<UserManager<User>>();
var store = new UserStore<ApplicationUser>();
var manager = new ApplicationUserManager(store);
var user = new ApplicationUser() { Email = aspNetUsers.Email, UserName = aspNetUsers.UserName };
var result= manager.CreateAsync(user, aspNetUsers.PasswordHash);
manager.Create(user, aspNetUsers.Password);
// db.AspNetUsers.Add(aspNetUsers);
// db.SaveChanges();
return RedirectToAction("Index");
}
return View(aspNetUsers);
}

var store = new UserStore<ApplicationUser>(new ApplicationDbContext());
ApplicationUserManager _userManager = new ApplicationUserManager(store);
var manger = _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
var user = new ApplicationUser() { Email = aspNetUsers.Email, UserName = aspNetUsers.UserName };
var usmanger= manger.Create(user, aspNetUsers.PasswordHash);

Related

Create Users and Roles using Asp.net mvc

I used this code to create default Users and Roles in the Startup file.
public void CreateDefaultRolesAndUsers()
{
var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(db));
var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(db));
IdentityRole role = new IdentityRole();
if(!roleManager.RoleExists("Admins"))
{
role.Name = "Admins";
roleManager.Create(role);
ApplicationUser user = new ApplicationUser();
user.UserName = "Ahmed";
user.Email = "ahmed#live.com";
var Check = userManager.Create(user, "Ahmed*90");
if(Check.Succeeded)
{
userManager.AddToRole(user.Id, "Admins");
}
}
}
The Role is created but the User does not ..where is the problem??

mvc 4 project how to have permissions to get facebook user email after log in using facebook sdk

i have mvc4 project with facebook login
i want to add the user email to the user profile table
this is my AuthConfig code
OAuthWebSecurity.RegisterFacebookClient(
appId: "8919945667880789",
appSecret: "ce8e0b218047693308cb71");
and this is my ExternalLoginCallback code
[AllowAnonymous]
public ActionResult ExternalLoginCallback(string returnUrl)
{
AuthenticationResult result = OAuthWebSecurity.VerifyAuthentication(Url.Action("ExternalLoginCallback", new { ReturnUrl = returnUrl }));
if (!result.IsSuccessful)
{
return RedirectToAction("ExternalLoginFailure");
}
if (OAuthWebSecurity.Login(result.Provider, result.ProviderUserId, createPersistentCookie: false))
{
return RedirectToLocal(returnUrl);
}
if (User.Identity.IsAuthenticated)
{
// If the current user is logged in add the new account
OAuthWebSecurity.CreateOrUpdateAccount(result.Provider, result.ProviderUserId, User.Identity.Name);
return RedirectToLocal(returnUrl);
}
else
{
// User is new, ask for their desired membership name
// User is new, ask for their desired membership name
string loginData = OAuthWebSecurity.SerializeProviderUserId(result.Provider, result.ProviderUserId);
ViewBag.ProviderDisplayName = OAuthWebSecurity.GetOAuthClientData(result.Provider).DisplayName;
ViewBag.ReturnUrl = returnUrl;
var client = new **FacebookClient(result.ExtraData["accesstoken"]);
dynamic me = client.Get("me");
string UserEmail = me.email;
var model = new RegisterExternalLoginModel { UserName = result.UserName, Email = UserEmail, ExternalLoginData = loginData };
return View("ExternalLoginConfirmation", model);
}
}
but when i debug I found the UserEmail = me.email = null
what i have to do to get the user email from the facebook ???
thank you so much for your help
all what i did that i edit my ExternalLoginCallback code to be like that
public ActionResult ExternalLoginCallback(string returnUrl)
{
AuthenticationResult result = OAuthWebSecurity.VerifyAuthentication(Url.Action("ExternalLoginCallback", new { ReturnUrl = returnUrl }));
if (!result.IsSuccessful)
{
return RedirectToAction("ExternalLoginFailure");
}
if (OAuthWebSecurity.Login(result.Provider, result.ProviderUserId, createPersistentCookie: false))
{
return RedirectToLocal(returnUrl);
}
if (User.Identity.IsAuthenticated)
{
// If the current user is logged in add the new account
OAuthWebSecurity.CreateOrUpdateAccount(result.Provider, result.ProviderUserId, User.Identity.Name);
return RedirectToLocal(returnUrl);
}
else
{
// User is new, ask for their desired membership name
// User is new, ask for their desired membership name
string loginData = OAuthWebSecurity.SerializeProviderUserId(result.Provider, result.ProviderUserId);
ViewBag.ProviderDisplayName = OAuthWebSecurity.GetOAuthClientData(result.Provider).DisplayName;
ViewBag.ReturnUrl = returnUrl;
var fb = new FacebookClient(result.ExtraData["accesstoken"]);
dynamic myInfo = fb.Get("/me?fields=email"); // specify the email field
var UserEmail = myInfo.email;
//var client = new FacebookClient(result.ExtraData["accesstoken"]);
//dynamic me = client.Get("me");
//string UserEmail = me.email;
var model = new RegisterExternalLoginModel { UserName = result.UserName, Email = UserEmail, ExternalLoginData = loginData };
return View("ExternalLoginConfirmation", model);
}
}
this is the code to get the user email
var fb = new FacebookClient(result.ExtraData["accesstoken"]);
dynamic myInfo = fb.Get("/me?fields=email"); // specify the email field
var UserEmail = myInfo.email;
thank you
var fb = new FacebookClient(result.ExtraData["accesstoken"]);
dynamic myInfo = fb.Get("/me?fields=email"); // specify the email field
var UserEmail = myInfo.email;
that is ok but but your code between if statment
if(OAuthWebSecurity.GetOAuthClientData(result.Provider).DisplayName;== "facebook"){
code
}

MVC 5 seeding users only works for email

I am working on a porject built on MVC5 and EF Code First.
I have multiple contexts, but the one I'm concered about here is the ApplicationDbContext which has the following configuration code:
namespace DX.DAL.Migrations.ApplicationDbMigrations
{
public class Configuration : DbMigrationsConfiguration<ApplicationDbContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = false;
MigrationsDirectory = #"Migrations\ApplicationDbMigrations";
ContextKey = "DX.DAL.Context.ApplicationDbContext";
}
protected override void Seed(ApplicationDbContext context)
{
var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));
var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
if (!roleManager.RoleExists("Admin"))
{
roleManager.Create(new IdentityRole("Admin"));
}
var user = new ApplicationUser { UserName = "John", Email = "j.doe#world.com" };
if (userManager.FindByName("John") != null) return;
var result = userManager.Create(user, "Password123#");
if (result.Succeeded)
{
userManager.AddToRole(user.Id, "Admin");
}
}
}
}
When I try and login with the email and password seeded above, I get the error:
Invalid login attempt
I wrote the following SQL Query:
SELECT * FROM AspNetUsers
And I see the following:
So the seed has been created. But why can't I login?
Also, I know that if I change the Username to be the same as the email, then it works and I can login. Must the username and email be the same for ASP.NET Membership in MVC 5 to work?
After trying so many different things, I went with LukeP's solution here.
I left Identity as it is and just added a new property called DisplayUsername and allowed the user to set that up on registration.

User.Identity.Name in Web Api Controller

I went through the answer to some of the already existing questions and none of the answers are working for me.
In the ProfileController, I invoke the WebApi Controller as follows:
public ViewResult Index()
{
var client = new HttpClient();
var webApiUrl = ConfigurationManager.AppSettings["WebApiURL"];
var response = client.GetAsync(string.Format("{0}{1}", webApiUrl, "//api/ProfileWeb")).Result;
var profile = response.Content.ReadAsAsync<Profile>().Result;
if (profile != null)
{
_profileModel.Id = profile.Id;
_profileModel.FirstName = profile.FirstName;
_profileModel.LastName = profile.LastName;
_profileModel.PhoneNumber = profile.PhoneNumber;
_profileModel.EmailAddress = profile.EmailAddress;
}
return this.View(_profileModel);
}
In the Api Contoller, I get the userName as follows:
public class ProfileWebController : ApiController
{
private IReminderDb _db;
public ProfileWebController(IReminderDb db)
{
_db = db;
}
public object Get()
{
string userName = User.Identity.Name; // <-- Not working..
var profile = _db.GetProfile(userName);
return profile;
}
}
Inside the web api controller, I am not able to get the User.Identity.Name that is in the ProfileContoller. According to some other answers where I have tried Thread.CurrentPrincipal but still the User.Identity.Name is coming out as null in web api controller.
What am I missing?

Moq a fake cookie in Asp.Net MVC Controller

This is my Action for my Login Controller. I am able to mock the action using Moq.
But i get an error when it hits this.HttpContext.Response.Cookies.Set(new HttpCookie("AcceptedDoDNotice") { Expires = DateTime.Now.AddDays(-1) });
Error:Additional information: Object reference not set to an instance of an object.
How do i Mock the cookie so i wont get the error above?
public ActionResult Login(LoginViewModel model)
{
if (ModelState.IsValid)
{
var user = _uow.UserRepository.FindLogin(model.Email, model.Password);
if (user != null)
{
_uow.UserRepository.UpdateLastLoginDate(user);
_uow.SaveChanges();
this.HttpContext.Response.Cookies.Set(new HttpCookie("MyCookie") { Expires = DateTime.Now.AddDays(-1) });
if (user.UserLevel.IsAdmin)
return RedirectToAction("Index", "Administrator");
}
else
{
ModelState.AddModelError("", "Invalid username or password.");
}
}
return View(model);
}
The Moq test is below:
//Arrange
var model = new LoginViewModel();
model.Email = realEmail;
model.Password = realPassword;
//Act
var loginController = new LoginController();
var result = loginController.Login(model) as RedirectToRouteResult;
var actual = result.RouteValues["controller"].ToString();
//Assert
actual.Should().Be("Administrator");
You need to mock the controller context. This will allow you to provide a mocked response which in turn provides a cookie collection that you control. You can then see exactly which cookies were set on the response.
var cookieCollection = new HttpCookieCollection { };
var response = new Mock<HttpResponseBase>();
response.SetupGet(r => r.Cookies).Returns(cookieCollection);
var context = new Mock<HttpContextBase>();
context.SetupGet(x => x.Response).Returns(response.Object);
var loginController = new LoginController();
loginController.ControllerContext = new ControllerContext(context.Object, new RouteData(), loginController);
var model = new LoginModel { };
var result = loginController.Login(model) as RedirectToRouteResult;
var actual = result.RouteValues["controller"].ToString();
//Assert
actual.Should().Be("Administrator");
cookieCollection.Should().HaveCount(1);
// other assertions about your cookie

Resources