如何在WebService中实现身份验证

本文关键字:实现 身份验证 WebService | 更新日期: 2023-09-27 18:28:47

我将在c#中创建一个web服务。客户端将发送用户名和密码。我想在访问web方法(IIS级别)之前对用户进行身份验证。有可能在c#中创建一个过滤器吗?任何人都可以分享代码或链接吗。用户详细信息存储在MSSQL数据库中[我想验证这样的用户是否存在于数据库中。如果用户不存在,那么我想阻止请求本身。目的是避免在每个web方法中验证用户]。

如何在WebService中实现身份验证

我建议构建一个基于REST的Web服务,并通过API密钥而不是用户名和密码进行发送。

看看:REST GET请求、动词和apikey

然后,只需谷歌基于REST的ASP.NET Web服务,就可以获得大量关于如何实现它的教程

更新以显示实施

注意:我找不到原始页面,但这段代码是基于某个地方的示例。

步骤1-编辑web.config

将其插入system.serviceModel部分。

<behaviors>
  <serviceBehaviors>
    <clear />
    <behavior>
      <!-- This behavior enables API Key Verification -->
      <serviceAuthorization serviceAuthorizationManagerType="API.APIKeyAuthorization, API" />
      <serviceMetadata httpGetEnabled="true" />
    </behavior>
  </serviceBehaviors>
</behaviors>

步骤2-创建API授权类

根据您的实际情况更改IsValidAPI密钥中的代码。您可以看到我的去一个函数测试API密钥是否有效。

namespace API
{
public class APIKeyAuthorization : ServiceAuthorizationManager
{
    public const string APIKEY = "APIKey";
    public const string APIKEYLIST = "APIKeyList";
    protected override bool CheckAccessCore(OperationContext operationContext)
    {
        return IsValidAPIKey(operationContext);
    }
    public bool IsValidAPIKey(OperationContext operationContext)
    {
        // if verification is disabled, return true
        if (Global.APIKeyVerification == false)
            return true;
        string key = GetAPIKey(operationContext);
        // Convert the string into a Guid and validate it
        if (BusinessLogic.User.ApiKey.Exists(key))
        {
            return true;
        }
        else
        {
            // Send back an HTML reply
            CreateErrorReply(operationContext, key);
            return false;
        }
    }
    public string GetAPIKey(OperationContext operationContext)
    {
        // Get the request message
        var request = operationContext.RequestContext.RequestMessage;
        // Get the HTTP Request
        var requestProp = (HttpRequestMessageProperty)request.Properties[HttpRequestMessageProperty.Name];
        // Get the query string
        NameValueCollection queryParams = HttpUtility.ParseQueryString(requestProp.QueryString);
        // Return the API key (if present, null if not)
        return queryParams[APIKEY];
    }
    private static void CreateErrorReply(OperationContext operationContext, string key)
    {
        // The error message is padded so that IE shows the response by default
        using (var sr = new StringReader("<?xml version='"1.0'" encoding='"utf-8'"?>" + APIErrorHTML))
        {
            XElement response = XElement.Load(sr);
            using (Message reply = Message.CreateMessage(MessageVersion.None, null, response))
            {
                HttpResponseMessageProperty responseProp = new HttpResponseMessageProperty() { StatusCode = HttpStatusCode.Unauthorized, StatusDescription = String.Format("'{0}' is an invalid API key", key) };
                responseProp.Headers[HttpResponseHeader.ContentType] = "text/html";
                reply.Properties[HttpResponseMessageProperty.Name] = responseProp;
                operationContext.RequestContext.Reply(reply);
                // set the request context to null to terminate processing of this request
                operationContext.RequestContext = null;
            }
        }
    }
    public const string APIErrorHTML = @"
<html>
<head>
    <title>Request Error - No API Key</title>
    <style type=""text/css"">
        body
        {
            font-family: Verdana;
            font-size: x-large;
        }
    </style>
</head>
<body>
    <h1>
        Request Error
    </h1>
    <p>
        A valid API key needs to be included using the apikey query string parameter
    </p>
</body>
</html>
";
    }
}

API授权是在您访问web方法之前完成的。然而,此示例显示了作为查询字符串传递的API键。按照上面链接中的更多示例将其更改为通过HTTP标头发送。一个更干净的方法,它不会弄乱你的URL。但这完全取决于您的要求。

更新事实上,我刚刚遇到了以下内容:Microsoft ASP.NET Web API-http://www.asp.net/web-api

试试看:)