Use web api cookie for mvc cookie

后端 未结 2 1326
走了就别回头了
走了就别回头了 2020-12-18 09:06

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 wh

2条回答
  •  悲&欢浪女
    2020-12-18 09:22

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

提交回复
热议问题