0

We are thinking about revising our existing membership provider into web service to allow remote authentication. Say, a windows 8 application will be able to accept login credentials and check it in our database on the server.

---update---

We have checked the video on asp.net website (Authorization, but only to find it is still using a traditional controller to do the authentication/authorization task. The video only shows we can use [Authorize] attribute. Is there a way to use an ApiController so that the authentication can be exposed as a webservice to be consumed by another application?

---end of my update---

I have been trying to find some example codes/project but found none so far. Can anyone suggestion a solution?

Thanks.

Blaise
  • 21,314
  • 28
  • 108
  • 169
  • 1
    You've really been drinking the Microsoft Kool-Aid, haven't you ;)? Yes, Windows 8 is cool. I've been playing with it myself. I absolutely encourage you to play with it, and play with the Metro UI. But as far as server-side: K.I.S.S.!!!!! *Forget* the framework-du-jour, and build on what you know and you're working with today. And even as far as client-side: please consider alternate frameworks, like PhoneGap. IMHO... – paulsm4 May 09 '12 at 20:19
  • Well, not necessarily for Windows 8. I have been working with MVC4 WebApi these days. But there is no existing example showing me how to authenticate using an ApiController. I will update my question. – Blaise May 10 '12 at 01:06
  • Hi - fair enough. These links might help: http://stackoverflow.com/questions/9482982/custom-mvc-authorizeattribute-for-asp-net-web-api/9484119 http://netmvc.blogspot.com/2012/03/aspnet-mvc-4-webapi-authorization.html – paulsm4 May 10 '12 at 01:19
  • One other link with some interesting content: http://weblogs.asp.net/scottgu/archive/2012/02/23/asp-net-web-api-part-1.aspx – paulsm4 May 10 '12 at 01:25

1 Answers1

-1

Here's how I'm authenticating via WebAPI - it's with Forms Auth and SimpleMembershipProvider. I'm not a seasoned coder so this could be far from quality but it should get you started. Note that this just authenticates the user, not the client (api key implementation is a TODO for me). Feedback welcome.

Checking to see if the current client/user is authenticated:

public class AccountController : ApiController
{
    public static DtoService _service = new DtoService();

    // GET/api/isAuthenticated
    [System.Web.Http.HttpGet]
    public HttpResponseMessage IsAuthenticated()
    {
        try
        {
            if (User.Identity.IsAuthenticated)
                return Request.CreateResponse(HttpStatusCode.OK, WebSecurity.GetUserId(User.Identity.Name));
            else
                return Request.CreateResponse(HttpStatusCode.OK, false);
        }
        catch (Exception e)
        {
            return Request.CreateResponse(HttpStatusCode.InternalServerError, e);
        }

    }

Log in:

    // POST /api/login
    // [System.Web.Http.AllowAnonymous]
    [System.Web.Http.HttpPost]
    public HttpResponseMessage LogIn(LoginModel model)
    {
        if (!ModelState.IsValid)
            return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
        try
        {
            if (User.Identity.IsAuthenticated)
                return Request.CreateResponse(HttpStatusCode.Conflict, "already logged in.");
            if (!WebSecurity.UserExists(model.UserName))
                return Request.CreateResponse(HttpStatusCode.BadRequest, "User does not exist.");
            if (WebSecurity.Login(model.UserName, model.Password, persistCookie: model.RememberMe))
            {
                FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
                return Request.CreateResponse(HttpStatusCode.OK, "logged in successfully");
            }
            return Request.CreateResponse(HttpStatusCode.BadRequest, "Login Failed.");
        }
        catch (Exception e)
        {
            return Request.CreateResponse(HttpStatusCode.InternalServerError, e);
        }
    }

Log out:

    // POST /api/logout
    [System.Web.Http.HttpPost]
    ////[ValidateAntiForgeryToken]
    [Authorize]
    public HttpResponseMessage LogOut()
    {
        try
        {
            if (User.Identity.IsAuthenticated)
            {
                WebSecurity.Logout();
                return Request.CreateResponse(HttpStatusCode.OK, "logged out successfully.");
            }
            return Request.CreateResponse(HttpStatusCode.Conflict, "already done.");
        }
        catch (Exception e)
        {
            return Request.CreateResponse(HttpStatusCode.InternalServerError, e);
        }
    }

Register:

    // POST: /api/register
    [System.Web.Http.HttpPost]
    //[ValidateAntiForgeryToken]
    public HttpResponseMessage Register(RegisterModel model)
    {
        if (!ModelState.IsValid)
        {
            return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
        }
        try
        {
            if (User.Identity.IsAuthenticated)
                return Request.CreateResponse(HttpStatusCode.Conflict, "User Already Registered and Logged In");
            if (WebSecurity.UserExists(model.UserName))
                return Request.CreateResponse(HttpStatusCode.Conflict, "User Already Registered");
            else
            {
                // Attempt to register the user
                WebSecurity.CreateUserAndAccount(model.UserName, model.Password);
                WebSecurity.Login(model.UserName, model.Password);
                InitiateDatabaseForNewUser(WebSecurity.GetUserId(model.UserName));

                FormsAuthentication.SetAuthCookie(model.UserName, createPersistentCookie: false);
                return Request.CreateResponse(HttpStatusCode.Created, WebSecurity.GetUserId(model.UserName));
            }

        }
        catch (Exception e)
        {
            return Request.CreateResponse(HttpStatusCode.InternalServerError, e);
        }

    }
}
SB2055
  • 12,272
  • 32
  • 97
  • 202