Forms Authentication for WCF

2019-08-14 17:28发布

问题:

How to secure my simple WCF service using FormsAuthentication concept ?

The ServiceContract looks similar to this:

    [ServiceContract]
    public interface MovieDb
    {
        [OperationContract]
        string GetData(int value);

        [OperationContract]
        string Login(int value);

        [OperationContract]
        string Logout(int value);

    }

I have used FormsAuthentication in my MVC 4 Application for authentication and authorization.

All I could think of is like adding Authorize Filter attribute at the top of the ServiceContract class.

Any pointers in Simple terms in much appreciated. Thanks.

回答1:

You can secure your WCF using username/password(Forms Authentication):

Message Security with a User Name Client

If you decide to use membership for Authentication in WFC configuration on server side you add a behavior configuring the Membership:

<behavior name="myBehavior"> 
    <serviceAuthorization principalPermissionMode="UseAspNetRoles" roleProviderName="myRoleProvider"/>
    <serviceCredentials>
        <serviceCertificate findValue="*.mycert.net" storeLocation="LocalMachine" x509FindType="FindBySubjectName"/>
        <userNameAuthentication userNamePasswordValidationMode="MembershipProvider" membershipProviderName="myMembershipProvidewr"/>
    </serviceCredentials>
</behavior>

Your WCF can be validate as simple as

  [PrincipalPermission(SecurityAction.Demand, Role = "My Role")]
        public bool GetSomething(string param1)
        {
...

You can find additional information here: http://msdn.microsoft.com/en-us/library/ff650067.aspx



回答2:

I know the very useful Authorize keyword in MVC but sofar I didn't find something like that in WCF.

If you are using the WCF service in (and for) the very same IIS application, you might want to write an own implementation of the Authorize keyword, but then for WCF. You can refer to the HttpContext to look whether the request is autorized or not.

Some extra information can be found here:

Does WCF have an equivalent of MVC's [Authorize] attribute?