C# – MVC Identity login with WebAPI

Having an existing C# MVC application with Idenity authorization there was a necessity to implement the same Identity authentication with WebAPI within the same web application and allow a desktop app to authenticate via WebAPI.

The way to get this working is to implement the MVC login authentication generated into the WebAPI controller. The last POST method is the one used to authenticate from the desktop app that uses HTTP Post. The way shown here, the username and password are accepted (and therefore have been submitted) in plain text JSON format. You need to implement your encryption method to get this secure.

using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.AspNet.Identity.Owin;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http;

namespace MyAppNameSpace
{
    public class WebApiController : ApiController
    {
        private ApplicationSignInManager _signInManager;
        private ApplicationUserManager _userManager;

        public WebApiController() { }

        public WebApiController(ApplicationUserManager userManager, ApplicationSignInManager signInManager)
        {
            UserManager = userManager;
            SignInManager = signInManager;
        }

        public ApplicationSignInManager SignInManager
        {
            get
            {
                return _signInManager ?? HttpContext.Current.GetOwinContext().Get();
            }
            private set
            {
                _signInManager = value;
            }
        }

        public ApplicationUserManager UserManager
        {
            get
            {
                return _userManager ?? HttpContext.Current.GetOwinContext().GetUserManager();
            }
            private set
            {
                _userManager = value;
            }
        }

        // GET: api/WebApi
        public IEnumerable Get()
        {
            return new string[] { "value1", "value2" };
        }

        public HttpResponseMessage Post([FromBody]JToken jsonbody)
        {
            AccountController accountController = new AccountController();

            dynamic data = JObject.Parse(jsonbody.ToString());

            string userId = data.userid;
            string userPassword = data.password;

            var result = SignInManager.PasswordSignIn(userId, userPassword, false, false);

            if (result.Equals(SignInStatus.Success))
            {
                return new HttpResponseMessage(HttpStatusCode.Accepted);
            }
            else
            {
                return new HttpResponseMessage(HttpStatusCode.Forbidden);
            }
        }
    }
}

Having the controller ready, the next step is to call the method via our desktop app to perform the login:

private void LoginPostRequest(string username, string password)
        {
            try
            {
                var httpWebRequest = (HttpWebRequest)WebRequest.Create("";
                httpWebRequest.Method = "POST";
                httpWebRequest.ContentType = "application/json; charset=utf-8";
                httpWebRequest.Accept = "application/json; charset=utf-8";

                using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
                {
                    string loginjson = new JavaScriptSerializer().Serialize(new
                    {
                        userid = username,
                        password = password
                    });

                    streamWriter.Write(loginjson);
                    streamWriter.Flush();
                    streamWriter.Close();

                    var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
                    using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
                    {
                        var result = streamReader.ReadToEnd();
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }