locked
How exactly should I check if the user is authenticated or not when user call any wcf function RRS feed

  • Question

  • User88744855 posted

    i have one question in my mind that how should I check if the user is authenticated or not in wcf. so i search goole and found one url from where i got some write up & code which is not clear to me. here is the url http://stackoverflow.com/questions/20853513/forms-authentication-in-wcf-after-setauthcookie?rq=1

    Using Forms Authentication to secure my WCF service.

    After validating the user, I try to set Forms Authentication Cookie using the code below:

    public bool Login(string username, string password)
            {
                if (Membership.ValidateUser(username, password))
                {
                    FormsAuthentication.SetAuthCookie(username, true);
                    // what should I do here?
                    return true;
                }
    
                return false;
            }

    After the SetAuthCookie how exactly should I check if the user is authenticated? (Whenever I try to access HttpContext.Current.User.Identity.IsAuthenticated, it gives me the value false.)

    a guy answer this quetion like this way but that was not clear to me

    Have you returned the cookie in the response in the login WCF service. In your case you can use this code
    
    public bool Login(string username, string password)
    {
       if (Membership.ValidateUser(username, password))
       {
           //FormsAuthentication.SetAuthCookie(username, true);
           // what should I do here?
           HttpCookie v_Cookie = FormsAuthentication.GetAuthCookie (username,true)
           HttpContext.Current.Response.Cookies.Add(v_Cookie);
           return true;
       }
    
       return false;
    }
    
    

    please help me to understand why the person who has given the idea & code just comment the SetAuthCookie line rather they read cookie. people read cookie after creating cookie. not very clear please guide me.

    Thursday, May 8, 2014 10:24 AM

Answers

  • User-417640953 posted

    Hi,

    Based on your description and code provided, I see you want to use the Asp.net MemberShip for the wcf authencation.

    For how to set a Ticket cookie to client side, you can try to use the CookieContainer like below 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);
                }
            }
        }

    Code comes this thread.

    http://stackoverflow.com/questions/2587645/how-to-use-authentication-cookie-from-wcf-authentication-service-in-an-asp-net-m

    WCF service is protected by a "Forms Authentication" mechanism, you will need to send the authentication cookie when making the WCF

    call to gain the required access to the service. Please note below points.

    # If you are calling a "REST" service using the "WebClient" class, this should not be a difficult task. You can simply work on the "CookieContainer"

      property of the "HttpWebRequest" class.

    # If you are calling a regular WCF service, and your client proxies are generated by the "Adding service reference" tool in the Visual Studio,

       the method to send cookies is not so obvious.

    For how to do that, please refer to below example.

    http://www.codeproject.com/Articles/190806/Send-Cookies-When-Making-WCF-Service-Calls

    Hope that helps, thanks.

    Best Regards!

     

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Sunday, May 11, 2014 10:43 AM

All replies

  • User-417640953 posted

    Hi,

    Based on your description and code provided, I see you want to use the Asp.net MemberShip for the wcf authencation.

    For how to set a Ticket cookie to client side, you can try to use the CookieContainer like below 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);
                }
            }
        }

    Code comes this thread.

    http://stackoverflow.com/questions/2587645/how-to-use-authentication-cookie-from-wcf-authentication-service-in-an-asp-net-m

    WCF service is protected by a "Forms Authentication" mechanism, you will need to send the authentication cookie when making the WCF

    call to gain the required access to the service. Please note below points.

    # If you are calling a "REST" service using the "WebClient" class, this should not be a difficult task. You can simply work on the "CookieContainer"

      property of the "HttpWebRequest" class.

    # If you are calling a regular WCF service, and your client proxies are generated by the "Adding service reference" tool in the Visual Studio,

       the method to send cookies is not so obvious.

    For how to do that, please refer to below example.

    http://www.codeproject.com/Articles/190806/Send-Cookies-When-Making-WCF-Service-Calls

    Hope that helps, thanks.

    Best Regards!

     

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Sunday, May 11, 2014 10:43 AM
  • User88744855 posted

    thanks for your reply. the code u gave me here is it service side code or client side code? i mean the code SignIn() will be writtent at client side?

    please explain me in detail about the code for SignIn() function.......what it does?

    tell me the meaning of each line of SignIn() function that what it is doing?

    what SignIn() func is working with response object? if client will invoke SignIn() then request should goes to server then SignIn() function should parse request object....but it is parsing or working with response....why?

    please looking for explanation in detail about the function SignIn(). thnx

    Sunday, May 11, 2014 4:17 PM
  • User-417640953 posted

    Hi mou_inn,

    The SignIn() method just a custom method for validate the username and password from client side.

    And this method surely on the asp.net application server side. In my mind the method must used in the event handler for the Authenticating event.

    In other word, the SignIn() method just a custom method which will called in below register event.

    void Application_Start(object sender, EventArgs e) 
    {
        System.Web.ApplicationServices.AuthenticationService.Authenticating += 
            new EventHandler<System.Web.ApplicationServices.AuthenticatingEventArgs>(AuthenticationService_Authenticating);
    
    }
    

    That issue more about the WCF authenticating with a Custom Membership Provider, I suggest you read below article carefully and through its' examples.

    http://msdn.microsoft.com/en-us/library/vstudio/bb386582(v=vs.100).aspx

    Thanks.

    Regards!

    Monday, May 12, 2014 7:23 AM
  • User88744855 posted

    if possible tell me the meaning of each line of SignIn() function that what it is doing? thnx

    Monday, May 12, 2014 2:00 PM