This Page isn't working Localhost redirected too many times MVC - asp.net-mvc

Program.cs File with Cookie authentication:
builder.Services.AddAuthentication("CookieAuthentication").AddCookie("CookieAuthentication", options =>
{
options.LoginPath = "/<Login/LoginView";
options.AccessDeniedPath = "/Login/AccessDenied";
});
// Configure the HTTP request pipeline.
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Login}/{action=Signup}/{id?}");
app.Run();
Login Controller:
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult LoginView(string username, string password)
{
if (!ModelState.IsValid)
{
//Error code here
}
if (!UserExists(username, password))//Check if user exists in Database
{
//Error code here
}
TempData["Username"] = username;
return RedirectToAction("Index", "Home");
//I used breakpoint here and this code runs but doesn't work properly.
}
I have also used the [Authorize] attribute on Home Controller to prevent users from accessing it without login.Login/LoginView is the Login rage Path.

This Page isn't working Localhost redirected too many times MVC
For your current scenario,be sure add the [AllowAnonymous] on your Index action in the HomeController. And your LoginPath is /Home/Index, it is no need to be authorized.
[Authorize]
public class HomeController : Controller
{
[AllowAnonymous]
public async Task<IActionResult> Index()
{
//do your stuff...
return View();
}
//....
}
Update:
Cookie authentication to login
Program.cs:
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(options =>
{
options.LoginPath = "/Login/LoginView";
options.AccessDeniedPath = "/Login/AccessDenied";
});
var app = builder. Build();
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseAuthentication(); //be sure add authentication and authorization middleware.....
app.UseAuthorization();
//...
How to sigh in the user:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> LoginView(string username, string password)
{
if (!ModelState.IsValid)
{
//Error code here
}
if (!UserExists(username, password))//Check if user exists in Database
{
//Error code here
}
var claims = new List<Claim>
{
new Claim(ClaimTypes.NameIdentifier,username) //add the claims you want...
};
//authProperties you can choose any option you want, below is a sample...
var authProperties = new AuthenticationProperties
{
//IssuedUtc = DateTimeOffset.UtcNow,
//ExpiresUtc = DateTimeOffset.UtcNow.AddHours(1),
//IsPersistent = false
};
var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity), authProperties);
TempData["Username"] = username;
return RedirectToAction("Index", "Home");
}

Related

Cannot signin using HttpContext.SignInAsync

I'm developing an application using ASP.Net Core MVC 3.1 and i am facing a problem where it fails to sign-in. localhost response 401 unauthorized
AccountController
[HttpPost]
public async Task<IActionResult> Login(PixClient client)
{
var claims = new List<Claim>();
claims.Add(new Claim(ClaimTypes.Email, client.Email));
var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
var principal = new ClaimsPrincipal(identity);
await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(principal));
return RedirectToAction("Index", "Home");
}
Startup.cs
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(options =>
{
options.LoginPath = "/account/login";
options.Cookie.Name = "sessionid";
});
Index.cs
[Authorize]
public IActionResult Index()
{ ...
I checked the codes you've shown,there's no mistake in it.
Make sure you've added the Authentication middleware and it was in correct order:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
.......
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
......
}
And you could create a middleware to check if the ticked is generated and added to cookie successfully:
app.Use(async (context, next) =>
{
var cookies = context.Request.Cookies;
await next.Invoke();
});
I tried as below:
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie( m =>
{
m.LoginPath = new Microsoft.AspNetCore.Http.PathString("/Home/Login");
m.Cookie.Name = "CookieAuth";
});
When redirect to /Home/Login,you could see the cookie namedCookieAuth:

Why Authorize Identity not work correctly?

Hi I try Create project with asp.net core mvc. I Create some Controller and also user Identity 3.1 for add manage users and add role to them. I Create 2 role (Normal, Admin) and for example I want only normal user access to the My AccountController. also the users default role is Normal after Registered. But when this type of user login and try open the account they redirect to the signin page. How can I fix this ?
i change all of the password option false temporary to create user test faster.
the below code is all of my configure from startup.
[Authorize(Roles = "Normal")]
public class AccountController : Controller
{
public IActionResult Index()
{
return View("Account");
}
}
enter code| services.AddDbContext<DataAcessLayer.DB>(s => s.UseSqlServer(Configuration.GetConnectionString("CON1")) );
services.AddIdentity<User, IdentityRole>(option =>
{
option.Password.RequireDigit = false;
option.Password.RequireLowercase = false;
option.Password.RequireUppercase = false;
option.Password.RequireNonAlphanumeric = false;
option.Password.RequiredLength = 5;
option.SignIn.RequireConfirmedPhoneNumber = false;
option.SignIn.RequireConfirmedAccount = false;
option.SignIn.RequireConfirmedEmail = false;
})
.AddUserManager<UserManager<User>>()
.AddRoles<IdentityRole>()
.AddRoleManager<RoleManager<IdentityRole>>()
.AddEntityFrameworkStores<DataAcessLayer.DB>();
services.ConfigureApplicationCookie(options =>
{
options.AccessDeniedPath = "/Sign/404";
options.Cookie.Name = "WebAppIdentityCookie";
options.Cookie.HttpOnly = true;
options.ExpireTimeSpan = TimeSpan.FromMinutes(20);
options.LoginPath = "/Sign/SignIn";
options.SlidingExpiration = true;
});
and this is my login code:
[HttpPost]
public async Task<IActionResult> login(Models.UserModel usermodel)
{
var user = await userManager.FindByNameAsync(usermodel.UserName);
if (user == null)
{
ModelState.AddModelError("", "نام کاربری یا رمز عبور اشتباه است.");
return View("SignIn", usermodel);
}
var SignInResult = await signInManager.PasswordSignInAsync(user, usermodel.Password, true, true);
if (SignInResult.Succeeded)
{
return RedirectToAction("Index", "Account");
}
else
{
ModelState.AddModelError("", "نام کاربری یا رمز عبور اشتباه است.");
return View("SignIn", usermodel);
}
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.UseAuthentication();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
try changing
app.UseAuthorization();
app.UseAuthentication();
to
app.UseAuthentication();
app.UseAuthorization()
read this article:
Asp.net Core Middlewares

How to properly use RedirectToAction()

namespace AspWebAppTest.Controllers
{
public class AccountController : Controller
{
public IActionResult Login()
{
return View();
}
[HttpGet]
public IActionResult Login(string userName, string password)
{
if (!string.IsNullOrEmpty(userName) && string.IsNullOrEmpty(password))
{
return RedirectToAction("Login");
}
ClaimsIdentity identity = null;
bool isAuthenticated = false;
if (userName == "Admin" && password == "pass")
{
identity = new ClaimsIdentity(new[] {
new Claim(ClaimTypes.Name, userName),
new Claim(ClaimTypes.Role, "Admin")
}, CookieAuthenticationDefaults.AuthenticationScheme);
isAuthenticated = true;
}
if (isAuthenticated)
{
var principal = new ClaimsPrincipal(identity);
var login = HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal);
return RedirectToAction("Mapping","Setting", "Home");
}
return View();
}
public IActionResult Logout()
{
var login = HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
return RedirectToAction("Login");
}
}
}
I have this Cookie Authentication Controller for my tabs(Mapping, and Config). I'am using RedirectToAction() method to redirect my return view to access mapping and config tab once the user entered the correct password and username. My problem is, after I put the password and username nothing is happening. Am I using the wrong method?
Here is my startup.cs
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
The SignInAsync method returns a Task which will complete when the sign-in operation has succeeded.
Your code does not await this Task, so you're sending the redirection response before the user has been authenticated.
Make your actions async, and await the results of the Sign[In|Out]Async methods:
[HttpGet]
public async Task<IActionResult> Login(string userName, string password)
{
...
if (isAuthenticated)
{
var principal = new ClaimsPrincipal(identity);
await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal);
return RedirectToAction("Mapping", "Setting", "Home");
}
return View();
}
public async Task<IActionResult) Logout()
{
await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
return RedirectToAction("Login");
}

How do i get this Basic Authentication working in .NET Core

I am using Basic Authentication and I have created a Middleware for this. When I use the Authorize attribute and try to make an API call through Postman, i get 401 Unauthorize even as I am added the authorization details in Postman.
I am not sure if it is the way i am calling the controller action via postman or whether I am missing a header option in postman.
ConfigureServices
services
.AddAuthentication(BasicAuthenticationDefaults.AuthenticationScheme)
.AddBasicAuthentication(GetBasicAuthenticationOptions(users));
Configure
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseMvc();
app.UseCors("SiteCorsPolicy");
app.UseAuthentication();
}
Basic Authentication Implementation
private Action<BasicAuthenticationOptions> GetBasicAuthenticationOptions(IList<UserConfiguration> users)
{
return options =>
{
options.Realm = "Public API";
options.Events = new BasicAuthenticationEvents
{
OnValidatePrincipal = context =>
{
var authenticatedUser = users.FirstOrDefault(u =>
u.Username == context.UserName && u.Password == context.Password);
if (authenticatedUser != null)
{
var claims = new List<Claim>
{
new Claim(ClaimTypes.Name,
context.UserName,
context.Options.ClaimsIssuer)
};
var principal = new ClaimsPrincipal(new ClaimsIdentity(claims,
BasicAuthenticationDefaults.AuthenticationScheme));
context.Principal = principal;
return Task.CompletedTask;
}
return Task.FromResult(AuthenticateResult.Fail("Authentication failed."));
}
};
};
}
Controller Action with Authorize
[Authorize]
[HttpPost]
[Route("test")]
public IActionResult Test()
{
return Json("yes");
}
Postman request
The username and passwords are in the appsettings.json file
The issue was just because app.UseMvc(); was placed before app.UseAuthentication(); . I just had to place app.UseMvc(); after app.UseAuthentication(); and that fixed it.

ASP.NET MVC Database not being created/uploaded System.ComponentModel.Win32Exception: The system cannot find the file specified

Background
I have just created an MVC website (as an application) using Visual Studio 2013 Express for Web from the default MVC template using the "Individual user accounts" option. I have created views to fit and added two fields ("Username" and "Birthdate") to the accounts model (using the tutorials by Microsoft). Note: Everything works fine when running on localhost from visual studio.
The Problem
When I upload the site to my server, I get a file not found error (I think it is the accounts database that is not being found). When I upload it (I am doing this via the file system method), there is nothing in the AppData folder but there isn't in VS either, it's in the server explorer. If I try to do anything with the accounts on the live server (eg. register a user), I get the following stack trace.
The Stack Trace
Note: You can see this for yourself at spiderhouse.org if you register a user; I have left the full error details available and in it's current state (at the time of writing) no info will be saved.
The Identity Models
using System;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
namespace Spiderhouse.Models
{
// You can add profile data for the user by adding more properties to your ApplicationUser class, please visit http://go.microsoft.com/fwlink/?LinkID=317594 to learn more.
public class ApplicationUser : IdentityUser
{
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
{
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
// Add custom user claims here
return userIdentity;
}
public override string UserName { get; set; }
public DateTime BirthDate { get; set; }
}
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("DefaultConnection", throwIfV1Schema: false)
{
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
}
}
The Account Controller
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin.Security;
using Owin;
using Spiderhouse.Models;
namespace Spiderhouse.Controllers
{
[Authorize]
public class AccountController : Controller
{
private ApplicationUserManager _userManager;
public AccountController()
{
}
public AccountController(ApplicationUserManager userManager)
{
UserManager = userManager;
}
public ApplicationUserManager UserManager {
get
{
return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
}
private set
{
_userManager = value;
}
}
//
// GET: /Account/Login
[AllowAnonymous]
public ActionResult Login(string returnUrl)
{
ViewBag.ReturnUrl = returnUrl;
return View();
}
//
// POST: /Account/Login
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
if (ModelState.IsValid)
{
var user = await UserManager.FindAsync(model.UserName, 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);
}
//
// GET: /Account/Register
[AllowAnonymous]
public ActionResult Register()
{
return View();
}
//
// POST: /Account/Register
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Register(RegisterViewModel model)
{
if (ModelState.IsValid)
{
var user = new ApplicationUser() { UserName = model.UserName, Email = model.Email, BirthDate = model.BirthDate };
IdentityResult result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
await SignInAsync(user, isPersistent: false);
// For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
// Send an email with this link
// string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
// var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
// await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking here");
return RedirectToAction("Index", "Home");
}
else
{
AddErrors(result);
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
//
// GET: /Account/ConfirmEmail
[AllowAnonymous]
public async Task<ActionResult> ConfirmEmail(string userId, string code)
{
if (userId == null || code == null)
{
return View("Error");
}
IdentityResult result = await UserManager.ConfirmEmailAsync(userId, code);
if (result.Succeeded)
{
return View("ConfirmEmail");
}
else
{
AddErrors(result);
return View();
}
}
//
// GET: /Account/ForgotPassword
[AllowAnonymous]
public ActionResult ForgotPassword()
{
return View();
}
//
// POST: /Account/ForgotPassword
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> ForgotPassword(ForgotPasswordViewModel model)
{
if (ModelState.IsValid)
{
var user = await UserManager.FindByNameAsync(model.Email);
if (user == null || !(await UserManager.IsEmailConfirmedAsync(user.Id)))
{
ModelState.AddModelError("", "The user either does not exist or is not confirmed.");
return View();
}
// For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
// Send an email with this link
// string code = await UserManager.GeneratePasswordResetTokenAsync(user.Id);
// var callbackUrl = Url.Action("ResetPassword", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
// await UserManager.SendEmailAsync(user.Id, "Reset Password", "Please reset your password by clicking here");
// return RedirectToAction("ForgotPasswordConfirmation", "Account");
}
// If we got this far, something failed, redisplay form
return View(model);
}
//
// GET: /Account/ForgotPasswordConfirmation
[AllowAnonymous]
public ActionResult ForgotPasswordConfirmation()
{
return View();
}
//
// GET: /Account/ResetPassword
[AllowAnonymous]
public ActionResult ResetPassword(string code)
{
if (code == null)
{
return View("Error");
}
return View();
}
//
// POST: /Account/ResetPassword
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> ResetPassword(ResetPasswordViewModel model)
{
if (ModelState.IsValid)
{
var user = await UserManager.FindByNameAsync(model.Email);
if (user == null)
{
ModelState.AddModelError("", "No user found.");
return View();
}
IdentityResult result = await UserManager.ResetPasswordAsync(user.Id, model.Code, model.Password);
if (result.Succeeded)
{
return RedirectToAction("ResetPasswordConfirmation", "Account");
}
else
{
AddErrors(result);
return View();
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
//
// GET: /Account/ResetPasswordConfirmation
[AllowAnonymous]
public ActionResult ResetPasswordConfirmation()
{
return View();
}
//
// POST: /Account/Disassociate
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Disassociate(string loginProvider, string providerKey)
{
ManageMessageId? message = null;
IdentityResult result = await UserManager.RemoveLoginAsync(User.Identity.GetUserId(), new UserLoginInfo(loginProvider, providerKey));
if (result.Succeeded)
{
var user = await UserManager.FindByIdAsync(User.Identity.GetUserId());
await SignInAsync(user, isPersistent: false);
message = ManageMessageId.RemoveLoginSuccess;
}
else
{
message = ManageMessageId.Error;
}
return RedirectToAction("Manage", new { Message = message });
}
//
// GET: /Account/Manage
public ActionResult Manage(ManageMessageId? message)
{
ViewBag.StatusMessage =
message == ManageMessageId.ChangePasswordSuccess ? "Your password has been changed."
: message == ManageMessageId.SetPasswordSuccess ? "Your password has been set."
: message == ManageMessageId.RemoveLoginSuccess ? "The external login was removed."
: message == ManageMessageId.Error ? "An error has occurred."
: "";
ViewBag.HasLocalPassword = HasPassword();
ViewBag.ReturnUrl = Url.Action("Manage");
return View();
}
//
// POST: /Account/Manage
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Manage(ManageUserViewModel model)
{
bool hasPassword = HasPassword();
ViewBag.HasLocalPassword = hasPassword;
ViewBag.ReturnUrl = Url.Action("Manage");
if (hasPassword)
{
if (ModelState.IsValid)
{
IdentityResult result = await UserManager.ChangePasswordAsync(User.Identity.GetUserId(), model.OldPassword, model.NewPassword);
if (result.Succeeded)
{
var user = await UserManager.FindByIdAsync(User.Identity.GetUserId());
await SignInAsync(user, isPersistent: false);
return RedirectToAction("Manage", new { Message = ManageMessageId.ChangePasswordSuccess });
}
else
{
AddErrors(result);
}
}
}
else
{
// User does not have a password so remove any validation errors caused by a missing OldPassword field
ModelState state = ModelState["OldPassword"];
if (state != null)
{
state.Errors.Clear();
}
if (ModelState.IsValid)
{
IdentityResult result = await UserManager.AddPasswordAsync(User.Identity.GetUserId(), model.NewPassword);
if (result.Succeeded)
{
return RedirectToAction("Manage", new { Message = ManageMessageId.SetPasswordSuccess });
}
else
{
AddErrors(result);
}
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
//
// POST: /Account/ExternalLogin
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult ExternalLogin(string provider, string returnUrl)
{
// Request a redirect to the external login provider
return new ChallengeResult(provider, Url.Action("ExternalLoginCallback", "Account", new { ReturnUrl = returnUrl }));
}
//
// GET: /Account/ExternalLoginCallback
[AllowAnonymous]
public async Task<ActionResult> ExternalLoginCallback(string returnUrl)
{
var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();
if (loginInfo == null)
{
return RedirectToAction("Login");
}
// Sign in the user with this external login provider if the user already has a login
var user = await UserManager.FindAsync(loginInfo.Login);
if (user != null)
{
await SignInAsync(user, isPersistent: false);
return RedirectToLocal(returnUrl);
}
else
{
// If the user does not have an account, then prompt the user to create an account
ViewBag.ReturnUrl = returnUrl;
ViewBag.LoginProvider = loginInfo.Login.LoginProvider;
return View("ExternalLoginConfirmation", new ExternalLoginConfirmationViewModel { Email = loginInfo.Email });
}
}
//
// POST: /Account/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 ChallengeResult(provider, Url.Action("LinkLoginCallback", "Account"), User.Identity.GetUserId());
}
//
// GET: /Account/LinkLoginCallback
public async Task<ActionResult> LinkLoginCallback()
{
var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync(XsrfKey, User.Identity.GetUserId());
if (loginInfo == null)
{
return RedirectToAction("Manage", new { Message = ManageMessageId.Error });
}
IdentityResult result = await UserManager.AddLoginAsync(User.Identity.GetUserId(), loginInfo.Login);
if (result.Succeeded)
{
return RedirectToAction("Manage");
}
return RedirectToAction("Manage", new { Message = ManageMessageId.Error });
}
//
// POST: /Account/ExternalLoginConfirmation
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl)
{
if (User.Identity.IsAuthenticated)
{
return RedirectToAction("Manage");
}
if (ModelState.IsValid)
{
// Get the information about the user from the external login provider
var info = await AuthenticationManager.GetExternalLoginInfoAsync();
if (info == null)
{
return View("ExternalLoginFailure");
}
var user = new ApplicationUser() { UserName = model.Email, Email = model.Email };
IdentityResult result = await UserManager.CreateAsync(user);
if (result.Succeeded)
{
result = await UserManager.AddLoginAsync(user.Id, info.Login);
if (result.Succeeded)
{
await SignInAsync(user, isPersistent: false);
// For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
// Send an email with this link
// string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
// var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
// SendEmail(user.Email, callbackUrl, "Confirm your account", "Please confirm your account by clicking this link");
return RedirectToLocal(returnUrl);
}
}
AddErrors(result);
}
ViewBag.ReturnUrl = returnUrl;
return View(model);
}
//
// POST: /Account/LogOff
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult LogOff()
{
AuthenticationManager.SignOut();
return RedirectToAction("Index", "Home");
}
//
// GET: /Account/ExternalLoginFailure
[AllowAnonymous]
public ActionResult ExternalLoginFailure()
{
return View();
}
[ChildActionOnly]
public ActionResult RemoveAccountList()
{
var linkedAccounts = UserManager.GetLogins(User.Identity.GetUserId());
ViewBag.ShowRemoveButton = HasPassword() || linkedAccounts.Count > 1;
return (ActionResult)PartialView("_RemoveAccountPartial", linkedAccounts);
}
protected override void Dispose(bool disposing)
{
if (disposing && UserManager != null)
{
UserManager.Dispose();
UserManager = null;
}
base.Dispose(disposing);
}
#region Helpers
// Used for XSRF protection when adding external logins
private const string XsrfKey = "XsrfId";
private IAuthenticationManager AuthenticationManager
{
get
{
return HttpContext.GetOwinContext().Authentication;
}
}
private async Task SignInAsync(ApplicationUser user, bool isPersistent)
{
AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, await user.GenerateUserIdentityAsync(UserManager));
}
private void AddErrors(IdentityResult result)
{
foreach (var error in result.Errors)
{
ModelState.AddModelError("", error);
}
}
private bool HasPassword()
{
var user = UserManager.FindById(User.Identity.GetUserId());
if (user != null)
{
return user.PasswordHash != null;
}
return false;
}
private void SendEmail(string email, string callbackUrl, string subject, string message)
{
// For information on sending mail, please visit http://go.microsoft.com/fwlink/?LinkID=320771
}
public enum ManageMessageId
{
ChangePasswordSuccess,
SetPasswordSuccess,
RemoveLoginSuccess,
Error
}
private ActionResult RedirectToLocal(string returnUrl)
{
if (Url.IsLocalUrl(returnUrl))
{
return Redirect(returnUrl);
}
else
{
return RedirectToAction("Index", "Home");
}
}
private class ChallengeResult : HttpUnauthorizedResult
{
public ChallengeResult(string provider, string redirectUri) : this(provider, redirectUri, null)
{
}
public ChallengeResult(string provider, string redirectUri, string userId)
{
LoginProvider = provider;
RedirectUri = redirectUri;
UserId = userId;
}
public string LoginProvider { 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, LoginProvider);
}
}
#endregion
}
}
The Connection Strings
<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\aspnet-Spiderhouse-20141120093225.mdf;Initial Catalog=aspnet-Spiderhouse-20141120093225;Integrated Security=True" providerName="System.Data.SqlClient" />
</connectionStrings>
This first line of the exception you mentioned i would get is saying that you don't have SQL express installed on the prod server.
SqlException (0x80131904): A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 52 - Unable to locate a Local Database Runtime installation. Verify that SQL Server Express is properly installed and that the Local Database Runtime feature is enabled.)
Obviously you will need to have that installed in order for your app to work on the server with the .mdf file that you put out. I'm assuming that when you say you "see nothing in the App_Data folder but you do in the server explorer" you are looking through the Visual Studio Solution Explorer into the App_Data folder, correct? If this is true, I also didn't see anything there, but physically going to the directory in file explorer showed the .mdf and .ldf files that the mvc site created. If you do have SQL Express installed on the server, maybe you forgot to put these files in the correct location on the web server.
In my project I opted to use a remote installation of SQL Server full, in which case I needed to change where the connection string was pointing, but because you included that in the information on your post I think you know that.

Resources