How to authenticate in an ASP.NET MVC application from a console application

不打扰是莪最后的温柔 提交于 2019-12-03 16:22:53

You're mixing credential types;

wc.Credentials = new NetworkCredential("user", "password");

is for HTTP authentication.

<authentication mode="Forms">
  <forms loginUrl="~/Account/LogOn" timeout="2880" />
</authentication> 

is forms authentication.

These are entirely different, and not compatible. Using forms authentication from a command line app is challenging, you'd need to go to the login page with a request, POST the username and password, then take the authentication cookie that is return and attach it to subsequent requests.

You need to Authenticate first of all as you are using Forms Authentication.

  1. Invoke the Logon Web Method and capture the Auth Cookie from the Http Response
  2. Set the Auth Cookie on the second Http Request to the DoSomething Method

Or Set the Auhentication Mode="Windows" if you are on a local intranet!

Create an AuthenticationService which can be used to do forms authentication. With the ClientBaseExtensions class you can get the cookie out of your WCF service client. Inject this cookie into the other call...

String cookies = null;
var auth = new AuthenticationServiceClient();
using (new OperationContextScope(auth.InnerChannel))
{
    auth.Login("user", "password", null, true);
    cookies = auth.GetIncomingCookies();
}

Now inject the cookie data into your data service or your HTTP call.

See http://mytoolkit.codeplex.com/wikipage?title=ClientBaseExtensions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!