-1

I'm trying to implement a very simple login system for a webapi backend. The site will only have one login, which is an admin, which will allow create/update/delete actions.

For this reason, I'm trying to implement a simple login with usernames and passwords coded directly into the pages in C#.

Here's how I want it to work:

On the Login.aspx page, the user enters the username and password to a form, which gets sent to the server via a webmethod:

[WebMethod]
public static something Login(string username, string password)
{
    if (username == "bob" && password == "password")
    {
        *Send some response indicating authentication success*
    }
}

This response needs to be something I can obtain from the client-side. Ideally, I'd like to be able to grab it using javascript. Is this possible using WebMethod? And I'm not sure what the method signature should be like.. I assume it would be "public static something methodName" but I'm not sure what that something would be.

Basically, If the user login is a success, I'll pass back a string such as "A(@I#ASGJAWIAW", the client will cache it in the browser, and from there, when they need to make any CREATE, UPDATE, or DELETE requests, they will also send in that value to the webapi methods. The webapi methods will determine whether the have the correct value before running the action.

Does anyone have any experience doing something like this?

carlosfigueira
  • 85,035
  • 14
  • 131
  • 171
Isaiah Lee
  • 647
  • 3
  • 9
  • 18
  • Very easy, you google `call asp.net webmethod from javascript`. – Rick S Aug 20 '14 at 17:47
  • This is 2 questions-- how to do authentication. This example you are showing is the wrong way to do it-- if security doesn't matter, than don't bother. If security does matter, use forms authentication not an adhoc system. The other question is how to return JSON. Return a string and then JSON.parse() the result. – MatthewMartin Aug 20 '14 at 17:53
  • I think security is not a matter to him as he mentioned "very simple login system". The question of the OP should be "how to call webmethod from javascript" and "how to write webmethod to return data for javascript" – kevin Aug 20 '14 at 18:14

1 Answers1

0

If you can use jQuery, you can make a simple call to the WebMethod. Make sure your webmethod returns a String.

ajaxreq = $.ajax({
        type: "POST",
        url: "LoginService.asmx/Login",
        data: "{'username':'" + $('#txtUser').val().trim() + "','password':'" + $('#txtPwd').val()+"'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: OnSuccess
    });
    function OnSuccess(data, status) {
        // Check response from server here and do your stuff here...
    }

In the above code, txtUser and txtPwd are the textboxes where it picks up the up the User Name and Password supplied by the user.

navigator
  • 1,678
  • 16
  • 29