人们如何处理Web服务的用户身份验证?

Mar*_*rcE 8 c# security authentication web-services

我正在创建一个Web服务,通​​过可公开访问的API公开一些数据.在较高的层面上,人们使用什么机制来保护他们的API以确保有效的,经过身份验证的用户正在进行呼叫?

该服务将是C#,消费者可以是任何东西(Facebook或iPhone应用程序以及网站),因此微软的解决方案已经淘汰.

这不是一个新问题,所以我假设有一些标准的做法来处理它,但我的google-fu让我失败了.集体能指出我的资源吗?谢谢.

And*_*rey 5

您仍然可以使用成员身份验证:拥有一个Web服务方法Login(username, password),在该方法中验证用户:

[WebMethod]
public bool Login( string username, string password)
{
    bool isValid = Membership.ValidateUser(username, password);
    if (isValid)
    {
        FormsAuthentication.SetAuthCookie(username, true);
        return true;
    }
    return false;
}
Run Code Online (Sandbox Code Playgroud)

而且应该这样做 - 它会创建一个随请求传播的cookie,并且可以在每种方法中检查HttpContext.Current.User.IsAuthenticated.

void SomeWebMethodThatRequiresAuthentication(someparameter)
{
    if (HttpContect.Current.User.IsAuthenticated)
    {
        ... do whatever you need - user is logged in ...
    }
    else
    {
        .... optionally let user know he is not logged in ...
    }
}
Run Code Online (Sandbox Code Playgroud)

我相信它可以与支持cookie的不同消费者合作,因为它需要工作的是消费者将auth cookie与请求一起发送到您的Web服务器.


小智 3

我发现 SaaS Web 服务中经常使用基于 SSL 的令牌密钥进行身份验证 - 我们在上一个项目中通过 OAuth 和 SAML 协议选择这种简单的方法。也许这很有用——有时简单的解决方案使事情更具可扩展性和过度控制。