【问题标题】:how to create wcf web service that has username and password in asp.net?如何在 asp.net 中创建具有用户名和密码的 wcf Web 服务?
【发布时间】:2013-04-04 06:24:47
【问题描述】:

我想创建在asp.net 中具有usernamepasswordwcf web service。这样通过提供该用户名和密码,我们就可以使用任何Web 方法。我已经创建了wcf Web 服务,但我想要在网络服务中添加用户名和密码。

提前致谢。

【问题讨论】:

  • 所以基本上,您想要验证对您的服务的请求。 look at this 和谷歌更多
  • 但是如何设置用户名和密码呢?比如说 uname="abc" 和 password="123" 以及如何验证它是对还是错?。
  • 创建一个 WCF 服务来验证用户,为用户创建一个安全令牌,然后将该安全令牌传递给您的方法,然后进行验证。

标签: c# asp.net wcf web-services


【解决方案1】:

以下是实现您的要求所需的步骤:

1) 使用 Visual Studio 的“新建项目”界面创建一个新的 WCF 项目:您将得到两个主要文件:Service1.svc(代码文件)和 IService1.cs (接口文件)。

2) 打开 IService1.cs 文件并定义您的方法,如下所示:

[ServiceContract]
public interface IService1
{
    [...]

    // TODO: Add your service operations here

    [OperationContract]
    string GetToken(string userName, string password);
}

3) 打开Service1.cs文件,按如下方式添加方法的实现:

/// <summary>
/// Retrieve a non-permanent token to be used for any subsequent WS call.
/// </summary>
/// <param name="userName">a valid userName</param>
/// <param name="password">the corresponding password</param>
/// <returns>a GUID if authentication succeeds, or string.Empty if something goes wrong</returns>
public string GetToken(string userName, string password)
{
    // TODO: replace the following sample with an actual auth logic
    if (userName == "testUser" && password == "testPassword")
    {
        // Authentication Successful
        return Guid.NewGuid().ToString();
    }
    else
    {
        // Authentication Failed
        return string.Empty;
    }
}

基本上就是这样。您可以使用此技术检索(过期且安全的)令牌以在任何后续调用中使用 - 这是最常见的行为 - 或在所有方法中实施该用户名/密码策略:这完全是您的调用。

要测试您的新服务,您可以在调试模式中启动您的 MVC 项目并使用内置的 WCF 测试工具:您必须输入示例值上面指定的(testUsertestPassword),除非您更改它们。

有关此特定主题的更多信息和其他实施示例,您也可以在我的博客上read this post

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-07-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多