Combine Asp.net Identity Web Api and MVC Best in a Single Web App

ASP.NET Identity
As the membership story in ASP.NET has evolved over the years, the ASP.NET team has learned a lot from feedback from customers.
The assumption that users will log in by entering a username and password that they have registered in your own application is no longer valid. The web has become more social. Users are interacting with each other in real time through social channels such as Facebook, Twitter, and other social websites. ASP.NET MVC developers want users to be able to log in with their social identities so that they can have a rich experience on their websites. A modern membership system must enable redirection-based log-ins to authentication providers such as Facebook, Twitter, and others.

As ASP NET web development evolved, so did the patterns of web development. Unit testing of application code became a core concern for application developers. In 2008 ASP.NET added a new framework based on the Model-View-Controller (MVC) pattern, in part to help .net developers build unit testable ASP.NET applications. ASP.Net Developers who wanted to unit test their application logic also wanted to be able to do that with the membership system.

Hire Now!

Do You Need Help From Our Dedicated ASP Net MVC Developer?

Hire our best ASP Net MVC developer on hourly, Full-time, Part-time bases. We are ready to help you resolve the problems for ASP MVC web app development.
Hire Now!

Considering these changes in ASP NET web application development, ASP.NET Identity was developed with the following goals:

  • One ASP.NET Identity system
  • Ease of plugging in profile data about the user
  • Persistence control
  • Unit test-ability
  • Role provider
  • Claims Based
  • Social Login Providers
  • Windows Azure Active Directory
  • OWIN Integration

Click here for more information about ASP.NET Identity

now the i will show you how to combine Asp.net “Identity” with Web API and ASP Net MVC web application.
you need following simple step for how to use Identity.

Step 1) Create new Project select Asp.net web application.

Step 2) Select Web API and change Authentication with (select Individual User Accounts)

Step 3) Now, your web API project is ready.
Let’s run your web API project and click on web API menu you will see how web API access.
Step 4) Now in my case I want login and register with a MVC web form.
I just add new empty Controller with name “UserManageController”
Step 5) Now add namespace in “UserManageController”.

using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.Owin.Security;

Step 6) Add two token property like.

 public UserManager<IdentityUser> UserManager { get; private set; }
 public ISecureDataFormat<AuthenticationTicket> AccessTokenFormat { get; private set; }
private IAuthenticationManager AuthenticationManager
        {  get {  return HttpContext.GetOwinContext().Authentication; }
        }

Step 7) Create a constructor for User Mange Controller like.

 public UserManageController()
            : this(Startup.UserManagerFactory(), Startup.OAuthOptions.AccessTokenFormat){}
public UserManageController(UserManager<IdentityUser> userManager,           ISecureDataFormat<AuthenticationTicket> accessTokenFormat)
        {
            UserManager = userManager;
            AccessTokenFormat = accessTokenFormat;
        }

Step 8) Than add new Method “Register” on “UserManageController”

[AllowAnonymous]
        public ActionResult Register()
        {
            return View();
        }

Step 9) Right click on “Register” method and add a new view with “RegisterBindingModel” Modal.
Step 10) Create post method for register on UserManageController.

  [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Register(RegisterBindingModel model)
        {   if (ModelState.IsValid)
            {   IdentityUser user = new IdentityUser
                {   UserName = model.UserName
                };
                var result = await UserManager.CreateAsync(user, model.Password);
                if (result.Succeeded)
                {
                    await SignInAsync(user, isPersistent: false);
                    return RedirectToAction("Index", "Home");
                }
                else
                {
                    AddErrors(result);
                }
            }
/ If we got this far, something failed, redisplay form
            return View(model);
        }
 private void AddErrors(IdentityResult result)
        {
            foreach (var error in result.Errors)
            {
                ModelState.AddModelError("", error);
            }
        }

Step 11) Goto ~/View/Shared/_Layout.CsHtml and two link for login and Register.

Step 12) Run your asp.net web application and click on register link.

Step 13) Create Login Method on “UserManageController”

[AllowAnonymous]
        public ActionResult Login(string returnUrl)
        {
            ViewBag.ReturnUrl = returnUrl;
            return View();
        }

Step 14) Add New login modal on “LoginViewModel” class on =>AccountViewModels on “Modals/AccountViewModels .cs file

 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; }

        [Display(Name = "Remember me?")]
        public bool RememberMe { get; set; }
    }

Step 15) Add Login View and select is modal “LoginViewModel”
Step 16) Than add post method for login like.

[HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
     public async Task<ActionResult> Login(LoginViewModel model,stringreturnUrl)        {
          if (ModelState.IsValid)
	 {  var user = await UserManager.FindAsyncmodel.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);
        }

Step 17) Add redirect method manage method like

  private ActionResult RedirectToLocal(string returnUrl)
        {
            if (Url.IsLocalUrl(returnUrl))
            {
                return Redirect(returnUrl);
            }
            else
            {
                return RedirectToAction("Index", "Home");
            }
        }

Step 18) Now add below code to your “Startup.Auth.cs”

Step 19) After successfully build than run your application and login with registered user above i registred with username like “jeshal” and pwd:123456

above example you Understand how asp.net Identity is work now below i will show you how same thing i will so you using webapi it’s already in my project.

following basic step to understand same thing with api. how to use asp.net Identity and

[Authorize] Attribute.
step 1 ) i have already two web Api Controller like “ValuesController” another is “AccountController”
step 2) now “Open your google Chrome and add extension “APIRestClient”
step 3) Now i will Use Register method using Api Call like this “www.yoururl.com/api/Account/register”

step 4)After register you more Call for Token using “www.yoururl.com/Token” like this.

when you click on Send then response like below formate
you will see here your access token. this token is use for calling your api method.

{
access_token: "YtX1SYLQutAxsulcmT5s16ErZWgxYi1Rdc-qHqjCF4TdKDXWN6-XjzaiVsWFdX8eAWvzLUP8F1w2apaZIXg4NiMVnk9n-3jgrJrJ1M1yQpYz1OMzDtxet0fUSFmjOapnEwudbUBhtXvmpK9-JBxPS0jUJe3mgC2PaV7-ihCv5BZFL1tD_5QTGY_tnOQAh4jbBXxn0joO_gGfAonoOi6sHqGFeBHxYGzwHgU16xkd4oKpf54cxlbT5YfaE6OVSHLwPz1E7j28DVTfscW0zE1xLXc-YygC0-sgw3biIGfXq8ISWX36dThJh_0siYsAcReNGR1KT_F5Me0i6kYFNqBC4ordWtx6GZImw4DKvfE62ZwVO6G_QcP18syQRA11kCBM7psEVQ_tpwuT2DcIMsqFfRlh_Ic09Mvot0Pqz8cbA8Q"
token_type: "bearer"
expires_in: 1209599
userName: "satva"
.issued: "Wed, 16 Jul 2014 09:41:09 GMT"
.expires: "Wed, 30 Jul 2014 09:41:09 GMT"
}

step 4) now i will show just when step how to test your access_token and how to getting information from your api call.
in my case i just getting my register details using “UserInfo” method form Api
“www.yoururl.com/UserInfo/api/Account/UserInfo”

now you we show here response look like this.

{
UserName: "satva"
HasRegistered: true
LoginProvider: null
}

I hope that this article for setup your asp.net identity authentication is helpful. leave replays if you found any difficulty in authentication. If you want more solutions and tricks related with Asp.Net Mvc, nopCommerce Store, Umbraco cms, Orchard and many more at Here.

Thank you

By | 2017-09-20T11:35:26+00:00 December 6th, 2014|API Integration Services, Asp.Net, Asp.Net MVC, How To, Web Service|