0

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

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Though creating oAuth supported API on PHP side is easier, it is not applicable in the time being,I think that means I can't use ASP.Net identity,right? So that leaves me to option "create my own feature",which I was trying to avoid because it needs a lot of changes/customizations,I thought there is an easier solution
Yes, in this case you can't use Identity and you have to create your own solution. ASP.NET Identity supports only oAuth protocol.
0

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;
            }
        }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.