.NET WebApi Authentication

前端 未结 1 2018
名媛妹妹
名媛妹妹 2020-12-30 14:24

Currently, I have an MVC web application that sells widgets. A user logs into our system using forms authentication, and can then do various functions based on the group th

相关标签:
1条回答
  • 2020-12-30 15:04

    Is there a way to pass the Forms Auth credentials from our MVC app to our Web api app?

    Sure, let's take for example the following MVC controller action calling the Web API:

    [Authorize]
    public ActionResult CallWebApi()
    {
        var baseAddress = new Uri("https://example.com");
        var cookieContainer = new CookieContainer();
        using (var handler = new HttpClientHandler() { CookieContainer = cookieContainer })
        using (var client = new HttpClient(handler) { BaseAddress = baseAddress })
        {
            var authCookie = Request.Cookies[FormsAuthentication.FormsCookieName].Value;
            cookieContainer.Add(baseAddress, new Cookie(FormsAuthentication.FormsCookieName, authCookie));
            var result = client.GetAsync("/api/values").Result;
            result.EnsureSuccessStatusCode();
    
            // now you can read the result.Content ...
        }
    }
    

    This assumes that you have also enabled forms authentication in the web.config of your Web API project and that the cookie name is the same as the one used in your MVC project.

    0 讨论(0)
提交回复
热议问题