简体   繁体   English

与Web API共享的MVC身份验证

[英]MVC authentication shared with Web API

I currently have an MVC application using the default "Individual User Accounts" option for authentication. 我目前有一个MVC应用程序使用默认的“个人用户帐户”选项进行身份验证。 This works great, I'm able to create users, log in and restrict access to controllers based on user roles. 这很好用,我能够根据用户角色创建用户,登录并限制对控制器的访问。

I have a separate Web API application that currently doesn't use any authentication. 我有一个单独的Web API应用程序,目前不使用任何身份验证。

Both applications are hosted on the same IIS server as separate sites. 两个应用程序都作为单独的站点托管在同一IIS服务器上。 I want to combine the authentication from the MVC application into the Web API application, so after the user has logged into the MVC application, they are also given access to the appropriate controllers in the Web API application, based on user role. 我想将MVC应用程序的身份验证组合到Web API应用程序中,因此在用户登录MVC应用程序后,他们还可以根据用户角色访问Web API应用程序中的相应控制器。

From what I have been reading, I need to set <authentication mode='Forms'> in web.config in both applications, and because they are on the same server, the authentication is automatically shared between the two. 根据我一直在阅读的内容,我需要在两个应用程序中的web.config中设置<authentication mode='Forms'> ,并且由于它们位于同一服务器上,因此两者之间会自动共享身份验证。 I've tried adding [Authorize] to a method in a controller in the Web API application, logged in through the MVC application and tried to access that method, but the method is never entered. 我已经尝试将[Authorize]添加到Web API应用程序中的控制器中的方法,通过MVC应用程序登录并尝试访问该方法,但从未输入该方法。

This is what I have been looking at: http://www.bipinjoshi.net/articles/436bc727-6de2-4d11-9762-9ee1a1e3cbea.aspx 这就是我一直在看的: http//www.bipinjoshi.net/articles/436bc727-6de2-4d11-9762-9ee1a1e3cbea.aspx

What am I missing here? 我在这里错过了什么? I'm hoping there is someone out there who can point me in the right direction. 我希望有人可以指出我正确的方向。

You need to be impersonated from your MVC application to the Web Api application with user that has access to the Web api controllers on your Web Api application, for instance with the user that is defined as an identity on the Web Api Application Pool. 您需要从您的MVC应用程序模拟到Web Api应用程序,用户可以访问Web Api应用程序上的Web api控制器,例如,在Web Api应用程序池中定义为标识的用户。

Then you can authenticate to the Web Api with Network Credential like the code bellow: 然后,您可以使用Network Credential对Web Api进行身份验证,如下面的代码所示:

WebApiProjectSoapClient client= new WebApiProjectSoapClient ();
            client.ClientCredentials.Windows.ClientCredential = new NetworkCredential("username", "password");
            client.ClientCredentials.Windows.AllowedImpersonationLevel = TokenImpersonationLevel.Identification;

            client.callSomeMethod();

This is example with Windows impersonation. 这是Windows模拟的示例。 If you want strictly Forms impersonation you can reffer to this link: 如果您需要严格的表单模拟,您可以访问此链接:

Impersonate using Forms Authentication 使用表单身份验证进行模拟

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM