Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm making a web application by using Web API 2 and MVC 5.

My app has api : api/account/login, which is used for checking posted information and throw status 200 when an account is granted to access application.

Also, I have one view : /Home/Index which is only available to authenticated client.

Now, my approach is :

  • Call api/account/login, receive the cookie thrown from that api.
  • Attach thrown back cookie to browser.
  • When user access /Home/Index, view is available for him/her.

My questions are :

- Is my approach possible ?

- How can I encrypt my cookie in Web API 2 like MVC 5 does to its cookie ?

Thank you,

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
650 views
Welcome To Ask or Share your Answers For Others

1 Answer

You could set the cookie once the user has authenticated against the Account controller.

public class AccountController 
{
   public HttpResponseMessage Login() 
   {         
      // Your authentication logic

      var responseMessage = new HttpResponseMessage();

      var cookie = new CookieHeaderValue("session-id", "12345");
      cookie.Expires = DateTimeOffset.Now.AddDays(1);
      cookie.Domain = Request.RequestUri.Host;
      cookie.Path = "/";

      responseMessage.Headers.AddCookies(new CookieHeaderValue[] { cookie });
      return responseMessage;
   }
}

To authenticate you can put the [Authenticate] attribute on your Home controller.

public class HomeController
{
    [Authenticate]
    public ActionResult Index() 
    {
       return View();
    }
}

The Authenticate attribute can also be applied at the Controller level if needed.

[Authenticate]
public class HomeController
{
}

You can also make your own authorization attribute if needed by overriding AuthorizeCore and checking for a valid cookie:

public class CustomAuth : AuthenticationAttribute
{
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        HttpCookie authCookie = httpContext.Request.Cookies["CookieName"];

        // Your logic
        return true;
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...