How to authenticate user while calling WCF service using AJAX?

后端 未结 3 1059
醉梦人生
醉梦人生 2021-02-10 16:10

I have a WCF service which needs to be called from client side(ajax call). I want to use ScriptManager on ASPX page to add a ServiceReference to the WCF service (or) JQuery ajax

3条回答
  •  暗喜
    暗喜 (楼主)
    2021-02-10 16:39

    There are a number of things you can do to secure your WCF services. Probably the easiest way is if your services are already part of the existing overall ASP.NET application is to enable ASP.NET Compatibility Mode for your services. If your ASP.NET app uses authentication to validate users (e.g. forms authentication) and you are enabling that via a session cookie, then ASP.NET Compatibility Mode does most of that work for you.

    By default, this is disabled, but you can enable it with an addition to your web.config:

    
            ...
            
            ...
    
    

    This will enable compatibility mode for all your services in your application. You can also enable this on a service by service basis by setting the web.config value and also using the AspNetCompatibilityRequirements attribute on your service class not the interface):

    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]
    public class FooService: IFooService {
    }
    

    When you enable this setting, you have access to HttpContext.Current (like an ASP.NET page) and it will also enforce that a user must be authenticated before accessing the .svc file (just like you have to be authenticated before accessing any .aspx file). If you try to access a .svc file without being authenticated, and you're using forms authentication, the caller will be redirected to the default login page and, after successful authentication, will be redirected to the .svc file.

    This suggestion makes a few assumptions:

    • your services are in an ASP.NET application;
    • you're using some type of ASP.NET authentication (like forms authentication) to validate users' credentials and persist a validation ticket in a cookie;

    This suggestion, while maybe not the most secure or robust, is probably the simplest to at least get up and running and secure your site to a reasonable degree.

    Here's a good MSDN library intro article on ASP.NET compatibility mode.

    If this works, perhaps the next step is to look into something like HMAC authentication (which involves a bit more work and the coordination of secret keys - but it's definitely more secure IMHO). Here's a nice walk-through of implementing it - http://blogs.microsoft.co.il/blogs/itai/archive/2009/02/22/how-to-implement-hmac-authentication-on-a-restful-wcf-service.aspx

    I hope this helps. Good luck!!

提交回复
热议问题