Combine ASP.NET Identity Web API and MVC Best in a Single Web App Jeshal kalena December 6, 2014 4 min read 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 application is no longer valid.The web has become more social. Users interact 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.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 IntegrationClick here for more information about ASP.NET IdentityNow I will show you how to combine Asp.net “Identity” with Web API and ASP Net MVC web application.You need to follow simple steps for how to use “Identity“. Create a new Project and select the Asp.net web application. Select Web API and change Authentication with (select Individual User Accounts). 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. Now in my case I want a login and register with an MVC web form. I just add new empty Controller with name “UserManageController”. Now add the namespace in “UserManageController”. using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.EntityFramework; using Microsoft.Owin.Security; Add two token property like. public UserManager UserManager { get; private set; } public ISecureDataFormat AccessTokenFormat { get; private set; } private IAuthenticationManager AuthenticationManager { get { return HttpContext.GetOwinContext().Authentication; } } Create a constructor for User Mange Controller like. public UserManageController() : this(Startup.UserManagerFactory(), Startup.OAuthOptions.AccessTokenFormat) { } public UserManageController(UserManager userManager, ISecureDataFormat accessTokenFormat) { UserManager = userManager; AccessTokenFormat = accessTokenFormat; } Then add new Method “Register” on “UserManageController” public ActionResult Register() { return View() } Right-click on the “Register” method and add a new view with “RegisterBindingModel” Modal. Create a post method for registering on UserManageController. 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); } } Goto ~/View/Shared/_Layout.cshtml and two links for login and Register. Run your asp.net web application and click on the register link. Create Login Method on “UserManageController”. public ActionResult Login(string returnUrl) { ViewBag.ReturnUrl = returnUrl; return View(); } 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; } } Add Login View and select is modal “LoginViewModel”. Than add a post method for login. [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task 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); } Add redirect method manage method like. private ActionResult RedirectToLocal(string returnUrl) { if (Url.IsLocalUrl(returnUrl)) { return Redirect(returnUrl); } else { return RedirectToAction("Index", "Home"); } } Now add below code to your “Startup.Auth.cs”. After successfully building than run your application and login with the registered user above I registered with a Username:jeshal and Password:123456. Above example, you Understand how asp.net Identity is work now below I will show you how the same thing I will so you using web API it’s already in my project.Following basic step to understand the same thing with API. how to use ASP.NET Identity and [Authorize] Attribute?[Authorize] Attribute: I have already two web API Controller like “ValuesController” another is “AccountController”. Now “Open your Google Chrome and add extension “APIRestClient”. Now I will Use Register method using API Call like this “www.yoururl.com/api/Account/register”. After register, you more Call for Token using “www.yoururl.com/Token” like this. When you click on Send then respond like below format.You will see here your access token. this token is used 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" } Now I will show just when stepping on how to test your access_token and how to get information from your API call. in my case, I just got my registration details using “UserInfo” method from API “www.yoururl.com/UserInfo/api/Account/UserInfo”Now you have shown here the response look like this. { UserName: "satva", HasRegistered: true, LoginProvider: null }I hope that this article for setting up your asp.net identity authentication is helpful. leave replays if you found any difficulty in the authentication. If you want more solutions and tricks related to Asp.Net MVC, nopCommerce Store, Umbraco cms, Orchard, and many more at Here.Thank you…!!