Search code examples
asp.netasp.net-mvcauthenticationasp.net-identity

Implement ASP.NET MVC login that authenticates user using api/web request


Background

I've been tasked with building a portal for my clients customers that provides them access to information regarding their accounts, fees/balances, messages etc. Customers information is managed through my clients finance software and is exposed through an API. All CRUD operations are performed via this API. I've implemented a class that builds and executes each web request, deserializes and handles the request response and returns the result to the MVC Controller which then updates the UI accordingly.

Problem

The problem i'm currently facing is implementing a secure login. I plan to use identity to authenticate customers that have accounts within my clients finance software. The issue is authentication has to happen via the API as opposed to a database. The API will return a token that is attached to each subsequent request. All examples i've looked at to date authenticate users using a database. How can I setup identity and configure it to use an API as opposed to a database as a data datasource.


Solution

  • Going down ASP.NET Identity/Identity Server route is the best option, but if you want to... here is an other option

    You could get the token and store in Form Cookie and validate/pull user information on every request.

    //add the token to response cookie

    public ActionResult Login(string username, string password)
    {
        var token = _api.Authenticate(username, password);
        //not only token you could store any user information (Name), you have to serialize it 
    
        var ticket = new FormsAuthenticationTicket(1, email, DateTime.UtcNow, DateTime.UtcNow.AddHours(1), false, token, _formsAuthentication.FormsCookiePath);
    
        var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(ticket))
                {
                    Path = FormsAuthentication.FormsCookiePath,
                    Secure = false,
                    HttpOnly = false,
                    Domain = null,
                    Expires = DateTime.UtcNow.AddHours(1)
                };
    
        Response.Cookies.Add(cookie);
    }
    

    //get token information from HttpContext

    var authCookie = HttpContext.Current.User.Identity as FormsIdentity;
    
    var token = authCookie.Ticket.UserData
    
    if(authCookie.IsAuthenticated)
    {
        // do something....
    }
    

    add this to web.config

    <system.web>
        <authentication mode="Forms"/>
    </system.web>