2013-04-04 41 views
1

我想創建wcf web serviceusernamepasswordasp.net.so通過提供該用戶名和密碼,我們可以使用任何Web方法。我已經創建了wcf Web服務,但我想在Web服務中添加用戶名和密碼。如何在asp.net中創建具有用戶名和密碼的wcf Web服務?

在此先感謝。

+0

所以基本上,你想驗證請求到你的服務。 [看看這個](http://stackoverflow.com/questions/4949792/wcf-service-using-asp-net-forms-authentication)和谷歌更多 – 2013-04-04 06:29:04

+0

但如何設置用戶名和密碼?比如uname =「abc」和password =「123」,以及如何驗證它是對還是錯? – Naresh 2013-04-04 06:37:10

+0

創建一個WCF服務來驗證用戶身份,爲用戶創建一個安全令牌,然後將安全性傳遞給您的方法,然後進行驗證。 – Sajeetharan 2013-04-05 08:39:38

回答

0

下面是必要的步驟,以達到你的要求爲:

1)使用Visual Studio的「新項目」界面中創建一個新的WCF項目:你有兩個主要文件結束:服務1 .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

相關問題