user1349354
user1349354

Reputation:

Remote authentication and local authorization in MVC5

My web site authentication is centralized and I authenticate my users with a web service and I don't store usernames and passwords. Web service returns details of valid user that I insert in my local db once user logins. I need authorize valid users in my web site and want to use ASP.NET Identity. I was confused how to use this method for authorization users. Can I use Identity without any code first authentication?

Upvotes: 2

Views: 708

Answers (1)

Sam FarajpourGhamari
Sam FarajpourGhamari

Reputation: 14741

As far as I understand you want send user credential to remote server and if remote server accept it authorize the user in your MVC application. It this kind of scenario you don't need user manager or user store. You could simply generate an Identity object with proper claims and sign in the user with the generated Identity object. Consider this simply example as clue:

[HttpPost]
public ActionResult Login(string username, string password)
{
    if (_remoteServer.IsValid(username, password))
    {
        var ident = new ClaimsIdentity(
          new[] 
          {
              // adding following 2 claim just for supporting default antiforgery provider
              new Claim(ClaimTypes.NameIdentifier, username),
              new Claim("http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider", "ASP.NET Identity", "http://www.w3.org/2001/XMLSchema#string"),

              new Claim(ClaimTypes.Name, username),
              // you could add extra claims like role or even custom one
              new Claim(ClaimTypes.Role, "UserRoleName"),
              new Claim("MyCustomClaim", "MyValue"),
          },
          DefaultAuthenticationTypes.ApplicationCookie);

        HttpContext.GetOwinContext().Authentication.SignIn(
           new AuthenticationProperties { IsPersistent = false }, ident);
        return RedirectToAction("MyAction"); // auth succeed 
    }
    // invalid username or password
    ModelState.AddModelError("", "invalid username or password");
    return View();
}

Now user is authenticated and injected in Identity's pipeline.

[Authorize]
public ActionResult Foo()
{
}

// since we injected user roles to Identity we could do this as well
[Authorize(Roles="UserRoleName")]
public ActionResult Foo()
{
    // since we injected our authentication mechanism to Identity pipeline 
    // we have access current user principal by calling also
    // HttpContext.User
} 

Upvotes: 3

Related Questions