简体   繁体   中英

ASP.net MVC Authentication using external PHP API

I'm developing an asp.net MVC website with the following requirements:

  1. Develop pages for Admin and Users, these pages must be accessed based on logged in user role: Admin or User
  2. The website supports login only, You will call a PHP API which resides on an external website, it returns a JSON as a result that includes id, username, and role (admin, user)
  3. You may save the result of returned json on a session to be used in your pages but this data must disappear after logout or session expiration.

I know how to develop the calling HTTP stuff and processing json, but I'm not familiar with authorization and authentication stuff, nor with using membership providers, I searched a lot and at first I thought of using SimpleMembership but I found that won't work since it depends on SQL queries and in my case I'm not going to use any type of databases.

I heard about asp.net identity but I'm not sure how to use it or if it's for my case or not, I searched again and I couldn't find any resource to help me achieve authentication and authorization for my case

I'm asking for your help to help me out and point me in the right direction

Thank you for your help

There is an example of using OAuth separated http auth API: http://www.asp.net/web-api/overview/security/external-authentication-services

Yes, this example depends on some specified http API.. But in case when you have some another JSON/XML RPC API you can try to create your own feature like a:

public class ExternalAuthAPIClient {
    public User Auth(string username, string password) { .... }
}

And use it in your AuthController in the method Login

BUT! This approach requires a lot of side changes.. where to store your user.. then create custom AuthenticateAttribure ... etc.

The better solution is to create oAuth supported API on your PHP side and use it with ASP.NET Identity.

I finally found a solution,I didn't need to use any membership providers since my website supports only login and via an API,I wrote the following code,this one is in AccountController :

    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public ActionResult Login(LoginViewModel login, string returnUrl)
    {
        if (!ModelState.IsValid)
        {
            ViewBag.Error = "Form is not valid; please review and try again.";
            return View(login);
        }

        //Call external API,check if credentials are valid,set user role into userData
        string userData="Admin";

        var ticket = new FormsAuthenticationTicket(
        version: 1,
        name: login.Username,
        issueDate: DateTime.Now,
        expiration: DateTime.Now.AddSeconds(HttpContext.Session.Timeout),
        isPersistent: false,
        userData: userData);

        var encryptedTicket = FormsAuthentication.Encrypt(ticket);
        var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);

        HttpContext.Response.Cookies.Add(cookie);

        if (Url.IsLocalUrl(returnUrl))
        {
            return Redirect(returnUrl);
        }
        return RedirectToAction("Index", userData);

    }

Then decorate admin/user controller with Authorize attribute like this:

[Authorize(Roles = "admin")]
public class AdminController : Controller

Then add the following code in Global.asax :

        public override void Init()
        {
            base.PostAuthenticateRequest += Application_PostAuthenticateRequest;
        }
        protected void Application_PostAuthenticateRequest(Object sender, EventArgs e)
        {
            if (HttpContext.Current.User.Identity.IsAuthenticated)
            {
                var cookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
                var decodedTicket = FormsAuthentication.Decrypt(cookie.Value);
                var roles = decodedTicket.UserData;

                var principal = new GenericPrincipal(HttpContext.Current.User.Identity, roles);
                HttpContext.Current.User = principal;
            }
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM