更新时间:2022-05-19 07:57:09
我最近一直在努力执行你所描述的相同的功能。我设法得到它具有以下code工作:
I have recently been trying to implement the same functionality you have described. I have managed to get it working with the following code:
private readonly AuthenticationServiceClient service = new AuthenticationServiceClient();
public void SignIn(string userName, string password, bool createPersistentCookie)
{
using (new OperationContextScope(service.InnerChannel))
{
// login
service.Login(userName, password, String.Empty, createPersistentCookie);
// Get the response header
var responseMessageProperty = (HttpResponseMessageProperty)
OperationContext.Current.IncomingMessageProperties[HttpResponseMessageProperty.Name];
string encryptedCookie = responseMessageProperty.Headers.Get("Set-Cookie");
// parse header to cookie object
var cookieJar = new CookieContainer();
cookieJar.SetCookies(new Uri("http://localhost:1062/"), encryptedCookie);
Cookie cookie = cookieJar.GetCookies(new Uri("http://localhost:1062/"))[0];
FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookie.Value);
if (null != ticket)
{
//string[] roles = RoleManager.GetRolesFromString(ticket.UserData);
HttpContext.Current.User = new GenericPrincipal(new FormsIdentity(ticket), null);
FormsAuthentication.SetAuthCookie(HttpContext.Current.User.Identity.Name, createPersistentCookie);
}
}
}
这不正是你所描述的评论你的问题。
It does exactly what you have described the comment to your question.
修改
我在这里张贴这code的服务器端部分,以供参考。
I am posting here the Server-Side portion of this code for reference.
public class HttpResponseMessageInspector : BehaviorExtensionElement, IDispatchMessageInspector, IServiceBehavior
{
public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
{
HttpRequestMessageProperty httpRequest = request.Properties[HttpRequestMessageProperty.Name]
as HttpRequestMessageProperty;
if (httpRequest != null)
{
string cookie = httpRequest.Headers[HttpRequestHeader.Cookie];
if (!string.IsNullOrEmpty(cookie))
{
FormsAuthentication.Decrypt(cookie);
FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(cookie);
string[] roles = PrincipalHelper.GetUserRoles(authTicket);
var principal = new BreakpointPrincipal(new BreakpointIdentity(authTicket), roles);
HttpContext.Current.User = principal;
}
// can deny request here
}
return null;
}
}