如何在Web API中使用Google样式令牌身份验证

时间:2013-12-11 00:18:35

标签: asp.net asp.net-mvc authentication asp.net-web-api identity

我有一个内部使用的网站,将通过互联网公开,以便在移动设备上使用。该网站是MVC 5,将与不同服务器上的Web API进行通信。用户将在登录页面上输入其Windows帐户信息,该信息将根据我们的Active Directory服务进行身份验证。经过身份验证后,我想创建一个身份验证令牌,用于后续调用MVC站点以及调用各种其他Web API。

起初我们只是使用基本身份验证,因为所有通信渠道都通过SSL,但我们有一个Web API无法访问我们的AD,但可以访问可能包含令牌信息的中央数据库。 / p>

有关如何保护企业Web API的任何示例或文档都非常棒。我找不到有关此主题的更多信息。

2 个答案:

答案 0 :(得分:0)

执行此操作的方法是创建自定义ActionFilterAttribute并覆盖OnActionExecuting方法。

public class AuthenticateAttribute : ActionFilterAttribute
{
     public override void OnActionExecuting(HttpActionContext actionContext)
     {
          //grab token from httprequest in the actionContext
          //and authenticate it against the token in the database

         if(/*token is NOT authenticated*/)
         {
              //set unauthorised response
              var response = actionContext.ControllerContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
             //and set the httpresponse in the actionContext to the unauthorised response
             actionContext.Response = response;
             //then return
             return;
         }
     }
}

然后,您可以将此属性应用于您要进行身份验证的API中的任何操作或方法。

答案 1 :(得分:0)

我们最终使用了thinktecture的IdentityServer。 https://github.com/thinktecture/Thinktecture.IdentityServer.v3

v3 Beta 1刚刚发布。看起来很有希 支持OpenID Connect和OAuth2.0。

他们有几个客户端示例,您可以从其他存储库下载。 https://github.com/thinktecture/Thinktecture.IdentityServer.v3.Samples/tree/master/source/Clients