Monday, 30 November 2015

ASP.Net Identity 2 Authentication Local Users - Step 15

> C#/.Net Samples
> .Net Authentication
> Setting up ASP.NET Identity 2 with External Logins Facebok Google Microsoft and Twitter

Step # 15

 

For other steps follow:

Setting up ASP.NET Identity 2 with External Logins Facebook Google Microsoft and Twitter

Login Redirection



At this time, we are going to make a small change so that we stay close to the sample application.

When the [Authorize] attribute will get applied to the controllers/actions, the user will get redirected to /Account/Login. Now this is not defined in the web.config file. This is defined in Statup.Auth.cs, as detailed above.



app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath = new PathString("/Account/Login"),
            });


Login Functionality

 

View model used by the login



using System.ComponentModel.DataAnnotations;
 
namespace Identity.WebSite.IdentityModels
{
    public class LoginViewModel
    {
        [Required]
        [Display(Name = "User Name")]
        public string UserName { get; set; }
 
        [Required]
        [DataType(DataType.Password)]
        [Display(Name = "Password")]
        public string Password { get; set; }
 
        public string ReturnUrl { get; set; }
 
        public bool RememberMe { get; set; }
    }
}

Action



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 Identity.WebSite.IdentityHelper;
using Identity.WebSite.IdentityModels;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin.Security;
 
namespace Identity.WebSite.Controllers
{
    [Authorize]
    public class AccountController : Controller
    {
        public AccountController()
        {
        }
 
        public AccountController(ApplicationUserManager applicationUserManager)
        {
            UserManager = applicationUserManager;
        }
 
        private ApplicationUserManager _applicationUserManager;
        public ApplicationUserManager UserManager
        {
            get
            {
                return _applicationUserManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
            }
            private set
            {
                _applicationUserManager = value;
            }
        }
 
        private IAuthenticationManager AuthenticationManager
        {
            get
            {
                return HttpContext.GetOwinContext().Authentication;
            }
        }
 
 
        #region Login
 
        [AllowAnonymous]
        public ActionResult Login(string returnUrl)
        {
            var model = new LoginViewModel{ReturnUrl = returnUrl };
            return View(model);
        }
 
        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Login(LoginViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = await UserManager.FindAsync(model.UserName, model.Password);
                if (user == null)
                {
                    ModelState.AddModelError("", "Invalid user name or password.");
                }
                else
                {
                    var identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
                    AuthenticationManager.SignOut();
                    AuthenticationManager.SignIn(new AuthenticationProperties
                    {
                        IsPersistent = model.RememberMe
                    }, identity);
                    if (!String.IsNullOrEmpty(model.ReturnUrl))
                    {
                        return Redirect(model.ReturnUrl);
                    }
                    return RedirectToAction("Index", "Home");
                }
            }
            return View(model);
        }
 
 
        #endregion
 
    }
}


Apply [Authorize] attribute to the UsersAdmin controller and run the application again. You’ll get redirected to the login view. Login with the user that you created during UsersAdmin Create/Register testing.

 

Log Off

 

Next implement Log Off action inside AccountCntroller



public ActionResult LogOff()
        {
            AuthenticationManager.SignOut();
            return RedirectToAction("Index", "Home");
        }