Skip to content

Instantly share code, notes, and snippets.

@gerrymiller
Last active December 16, 2015 12:38
Show Gist options
  • Save gerrymiller/5435672 to your computer and use it in GitHub Desktop.
Save gerrymiller/5435672 to your computer and use it in GitHub Desktop.
Microsoft WebApi including with MVC 4 offers a great way to build RESTful services. However, if you want to take advantage of ASP.NET's build-in Forms Authentication with cookies for secure services with [Authorize], you have to jump through some hoops to allow some browsers (e.g., IE10) to set the auth cookie. Here's some simple server- and cli…
namespace MyNamespace
{
public class AccountController : ApiController
{
private readonly IAccountRepository _repository;
public AccountController()
{
_repository = new AccountRepository();
}
public AccountController(IAccountRepository repository)
{
_repository = repository;
}
// GET api/account
[Authorize]
public HttpResponseMessage Get()
{
try
{
return Request.CreateResponse<Account>(HttpStatusCode.OK, _repository.Get(User.Identity.Name));
}
catch
{
return Request.CreateErrorResponse(HttpStatusCode.Forbidden, "Invalid User");
}
}
// POST api/account/Login
[HttpPost]
public HttpResponseMessage Login(Account account)
{
try
{
var targetAccount = _repository.Get(account.Email);
if (!MD5Utilities.VerifyMD5Hash(account.Password, targetAccount.Password))
{
throw new Exception();
}
// Workaround - have to pass sessionId back to client as some browsers prevent access to cookies on AJAX call,
// so manually setting auth cookie
var cookie = FormsAuthentication.GetAuthCookie(account.Email, false);
var response = Request.CreateResponse(HttpStatusCode.OK, new { account = targetAccount, cookieName = FormsAuthentication.FormsCookieName, sessionId = cookie.Value });
response.Headers.AddCookies(new [] { new CookieHeaderValue(cookie.Name, cookie.Value) { Path="/", HttpOnly = true } });
return response;
}
catch
{
return Request.CreateErrorResponse(HttpStatusCode.Forbidden, "Invalid Email or Password");
}
}
[Authorize]
[HttpPost]
public void Logout()
{
FormsAuthentication.SignOut();
}
}
}
var login = function(email, password) {
$.post('/api/account/Login', { Email: email, Password: password },
function (data, textStatus, jqXHR) {
// Some browsers prevent getting this cookie, so check and set session cookie if necessary
if(!jqXHR.getResponseHeader("Set-Cookie"))
document.cookie = data.cookieName + "=" + data.sessionId + "; Path='/'; HttpOnly";
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment