Figer's Technology Consulting | C# Web API Forms Authentication using JQuery Ajax calls from HTML5 app

C# Web API Forms Authentication using JQuery Ajax calls from HTML5 app

------------------

Enable Forms Authentication

-------------------

add to web.config

<system.web>

<authentication mode="Forms" />


LogonModel.cs

--------------

namespace DeliveryApp.Models

{

using System;

using System.Collections.Generic;


public class LogOnModel

{

public string Username { get; set; }

public string Password { get; set; }

}

}


AccountController.cs

--------------------

using System.Web.Http;

using System.Web.Security;

using DeliveryApp.Models;

using System.Web;

using System.Security.Principal;

using System.Web.Helpers;


namespace DeliveryApp.Controllers

{

public class AccountController : ApiController

{

public bool Post(LogOnModel UserAccount)

{

if (UserAccount != null)

{

//Change this to hit the SQL server to get the accounts and validate

if (UserAccount.Username == "test" && UserAccount.Password == "test12")

{

FormsAuthentication.SetAuthCookie(UserAccount.Username, false);

return true;

}

}


return false;

}

}

}


Javascript ajax function to login - once logged in, it creates cookie that all other ajax calls auto send with the request.

<strong>Must be over SSL to be secure</strong>

---------------------------------


function login() {


var user = $('#user').val();

var pass = $('#pass').val();


$.ajax({

type: 'Post',

url: webapiURL + '/Api/Account',

data: { Username: user, Password: pass },

dataType: 'json',

success: function(data) {


//Login Success

window.location = "index.html";

},

error: function(msg) {

alert("Error Logging in - " + msg.responsetext);

}

});

}


Finally place  [Authorize] directly above every web api controller function except for the Login one. This will restrict access unless the user has authenticated.

Comments are closed