Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
660 views
in Technique[技术] by (71.8m points)

asp.net mvc - Use web api cookie for mvc cookie

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

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

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...