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 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 Integration

Click here for more information about ASP.NET Identity

Now 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“.

  1. Create a new Project and select the Asp.net web application.
    Create a new Project and select the Asp.net web application
  2. Select Web API and change Authentication with (select Individual User Accounts).
    Create a new Project and select the Asp.net web application
  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.
  4. Now in my case I want a login and register with an MVC web form. I just add new empty Controller with name “UserManageController”.
  5. Now add the namespace in “UserManageController”.

using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.Owin.Security;
  1. 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; }
}
  1. 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;
}
  1. Then add new Method “Register” on “UserManageController”

public ActionResult Register()
{
	return View()
}
  1. Right-click on the “Register” method and add a new view with “RegisterBindingModel” Modal.
  2. 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);
}
}

  1. Goto ~/View/Shared/_Layout.cshtml and two links for login and Register.
    two links for login and Register
  2. Run your asp.net web application and click on the register link.
  3. Create Login Method on “UserManageController”.

public ActionResult Login(string returnUrl)
{
ViewBag.ReturnUrl = returnUrl;
return View();
}
  1. 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; }
}
  1. Add Login View and select is modal “LoginViewModel”.
  2. 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);
}
  1. Add redirect method manage method like.

private ActionResult RedirectToLocal(string returnUrl)
{
	if (Url.IsLocalUrl(returnUrl))
	{
		return Redirect(returnUrl);
	}
	else
	{
		return RedirectToAction("Index", "Home");
	}
}
  1. Now add below code to your “Startup.Auth.cs”.
    Now add below code to your
  2. After successfully building than run your application and login with the registered user above I registered with a Username:jeshal and Password:123456.
    After successfully building than run your application

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:

  1. I have already two web API Controller like “ValuesController” another is “AccountController”.
  2. Now “Open your Google Chrome and add extension “APIRestClient”.
  3. Now I will Use Register method using API Call like this “www.yoururl.com/api/Account/register”.
    Now I will Use Register method using API Call
  4. After register, you more Call for Token using “www.yoururl.com/Token” like this.
    When you click on Send then respond like below formatWhen 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"
}
  1. 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”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…!!

Article by

Jeshal kalena

Jeshal Kalena is a passionate Programmer and Tech Lead at Satva Solutions, specializing in RPA, Microsoft.NET Core, ASP.NET, Azure and AWS cloud service integrations. With Master's degree in IT and Computer Applications, Jeshal brings a wealth of knowledge and 12+ years experience to his writing. His blog is a treasure trove of example-driven content, focusing on real-world problems and their solutions in the realm of software programming. Jeshal's philosophy is simple yet powerful: be result-oriented and never give up. Through his insightful posts, he aims to empower fellow programmers with practical tips and techniques to enhance their coding skills and solve complex challenges efficiently.