How to authenticate username password in Jquery with asp.net?

后端 未结 2 889
伪装坚强ぢ
伪装坚强ぢ 2021-01-17 07:01

I have code of Jquery login control loke following using this into asp.net but but confused where and how I can simply authenticate username and password.

Logi

相关标签:
2条回答
  • 2021-01-17 07:45

    Here's how you can write an ajax call to start with

    var usernameText = $("#usernameTextbox");
    var passwordText = $("#passwordTextbox");
    
    $.ajax({
        type: 'GET',
        url: '/Account/ValidateUser',
        async: true,
        dataType: 'json',
        data:
        {
            userName: usernameText,
            password: passwordText
        },
        success: function(result) {
            if(result){
                // redirect user to required page
            }
            else{
                // show error on some div that usrname and password do not match
            }
        }
    });
    

    Related Question on SO

    MVC 4 Jquery Ajax call returns login page html

    How to use Basic Auth with jQuery and AJAX?

    0 讨论(0)
  • 2021-01-17 07:54

    I'm not sure what are you trying exactly to do, but in order to perform log on with asp.net you should send your data somehow to the server. You can do it in two ways: send it with form or by AJAX request. If you want to send it within the form, you should specify action in your tag form, e.g.

    <form id="loginForm" action="MySite/Logon">
        <!-- fields, labels, etc. -->
    </form>
    

    If you want to send it via jQuery AJAX request, you can use jQuery.ajax method, which is clearly explained here, with corresponding url in url parameter.
    On the server side, your authentication may look like this:

    FormsAuthenticationTicket ticket = new FormsAuthenticationTicket( // create authentication ticket
        1, // id
        email, // user name
        DateTime.Now, // date of issue
        DateTime.Now.AddMinutes(15), // expiration date
        true, // true if your ticket will be stored in a cookie, that will be kept by browser across the sessions
        userdata, // any text data, that you want to add to ticket (e.g. user roles)
        FormsAuthentication.FormsCookiePath // path associated with your ticket
    );
    string hashedTicket = FormsAuthentication.Encrypt(ticket);
    HttpCookie cookie = new HttpCookie(
        FormsAuthentication.FormsCookieName, hashedTicket); // adding your ticket to cookie
    cookie.Expires = ticket.Expiration;
    Response.Cookies.Add(cookie); // sending cookie to client with current response
    

    After these actions, your client will be recognized as authenticated until he logs off or expiration time of cookie/ticket expires.
    Hope this info will help you.

    0 讨论(0)
提交回复
热议问题