Машина
Машина

Reputation: 143

WebClient FormsAuthentication in WebAPI

Webservice code

[Authorize]
public class RegistrationController : ApiController
{
    [AllowAnonymous]
    [HttpPost]
    public string Get(string user,string pass)
    {
        if (user=="abc"&&pass=="cba")
            FormsAuthentication.SetAuthCookie("HomeUser", false);
        return "Home";
    }
    [HttpGet]
    public string Post()
    {
        return "Post";
    }
}

Forms Authentication from console

class CookieWebClient : WebClient
    {
        public CookieContainer CookieContainer { get; private set; }

        /// <summary>
        /// This will instanciate an internal CookieContainer.
        /// </summary>
        public CookieWebClient()
        {
            this.CookieContainer = new CookieContainer();
        }

        /// <summary>
        /// Use this if you want to control the CookieContainer outside this class.
        /// </summary>
        public CookieWebClient(CookieContainer cookieContainer)
        {
            this.CookieContainer = cookieContainer;
        }

        protected override WebRequest GetWebRequest(Uri address)
        {
            var request = base.GetWebRequest(address) as HttpWebRequest;
            if (request == null) return base.GetWebRequest(address);
            request.CookieContainer = CookieContainer;
            return request;
        }
    }

The program's objective is to log into a Web service, and then query the secure authorization methods and then reset the authorization. How to do it the easiest way?

using (var client = new CookieWebClient())
        {
            var values = new NameValueCollection
{
    { "user", "abc" },
    { "pass", "cba" },
};
            client.UploadValues("http://localhost:1401/Get/","POST", values);

            // If the previous call succeeded we now have a valid authentication cookie
            // so we could download the protected page
            string result = client.DownloadString("http://localhost:1401");
        }

I have an error 405 Unknown method on line UploadValues. Can you help me? I use the authorization by means of forms, as I find this method as simple as possible and at the same time safe.

P.S. WebApiConfig code:

config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "{api}/{id}",
            defaults: new { controller="Registration",
                api=RouteParameter.Optional,
                id = RouteParameter.Optional }
        );
        config.Filters.Add(new AuthorizeAttribute());

Upvotes: 1

Views: 736

Answers (1)

tizzick
tizzick

Reputation: 5532

Check you WebApiConfig class. The default scaffolded path for api is usually something line this.

config.Routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{id}",
    defaults: new { id = RouteParameter.Optional }
);

In you case you url could be something like this. But that will depend on what routeTemplate you have registered.

client.UploadValues("http://localhost:1401/api/Registration/","POST", values);

Also I would recommend not calling your methods or actions Get() or Post(), those names are too easily confused with httpGet and httpPost.

If you think the forms authentication is stopping you from posting to the url, comment out the [Authorize] tags from the Registration controller and try to post again. If it still not working it is probably you url and not the authentication.

Upvotes: 1

Related Questions