[英]Read username in WCF service after authenticate
我有一個自定義驗證器,用於驗證 Web 服務中傳入的用戶名和密碼。 驗證完成后,我需要在 web 服務中使用該用戶名和密碼。 這是我的 CustomValidator
public class ServiceAuthenticator : UserNamePasswordValidator
{
private static readonly ILog _log = LogManager.GetLogger("ServiceAuthenticator");
public override void Validate(String userName, string password)
{
_log.InfoFormat("-------------{0}/{1}------------------------------", userName, password);
if (userName == null || password == null)
{
_log.WarnFormat(" Missing User-name / Password {0}/{1}", userName, password);
throw new FaultException("Incorrect User name or Password");
}
}
}
現在我有一個網絡服務,我試圖在其中獲取上述用戶名和密碼
[WebInvoke(Method = "POST", UriTemplate = "Uplooc")]
[WebMethod(Description = "Save documents ")]
public void UploadDocGen(RemoteFileInfo remoteFileInfo)
{
// string UserName = ""; --- How i get the username
// sting Password = ""; -- How to get the password into this
}
我們可以使用ServiceSecurityContext
來獲取用戶名值,而在憑證通過認證后我們無法獲取密碼。
public string SayHello()
{
OperationContext oc = OperationContext.Current;
var username1=oc.ServiceSecurityContext.PrimaryIdentity.Name;
Console.WriteLine(username1);
var username2 = ServiceSecurityContext.Current.PrimaryIdentity.Name;
Console.WriteLine(username2);
return $"Hello Buddy,{DateTime.Now.ToLongTimeString()}";
}
結果。
基於 SAML 的安全令牌,我們只能獲取聲明集。 這是一個復雜的話題,我不太了解。 這里有一些相關的文檔,希望對你有用。
https://docs.microsoft.com/en-us/dotnet/framework/wcf/how-to-examine-the-security-context
https://docs.microsoft.com/en-us/dotnet/api/system.servicemodel.servicesecuritycontext?view=netframework-4.8
如果有什么我可以幫忙的,請隨時告訴我。
想出了一個不同的方法。
創建一個 static class 可以保存來自驗證器的用戶名和密碼並在 web 服務中使用
public class ServiceAuthenticator : UserNamePasswordValidator
{
private static readonly ILog _log = LogManager.GetLogger("ServiceAuthenticator");
public override void Validate(String userName, string password)
{
_log.InfoFormat("--------Validate -{0}/{1}------------------------------", userName, password);
if ((userName == null || userName.Trim().Length == 0) || (password == null || password.Trim().Length == 0))
{
_log.WarnFormat(" Missing User-name / Password {0}/{1}", userName, password);
throw new FaultException("Missing User-name / Password", new FaultCode("MISSINGUSERDETAILS"));
}
AuthUser.Username = userName;
AuthUser.Password = password;
}
}
public static class AuthUser
{
private static string name = "";
public static string Username
{
get { return name; }
set { name = value; }
}
private static string pswrd = "";
public static string Password
{
get { return pswrd; }
set { pswrd = value; }
}
}
在 web 服務中
string username = AuthUser.Username;
string passwod = AuthUser.Password;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.