Bonjour,

j'ai un soucis entre mon WEBDATESERVICE et mon client. J'ai beau voir le forum de la Msdn mais rien ne fonctionne.
Je veux simplement sécurisé mon service et ajouter un system d'identification.

Cote WCFWebService => 2 projets. (l'un est mon projet WCF et l'autre mon entityFramework)
J'aimerai faire une identification "Custom"
1er class
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
public class CustomAuthenticationProvider
    {
        public static bool Authenticate(HttpContext context)
        {
            //if (!HttpContext.Current.Request.IsSecureConnection)
            //    return false;
            //if (!HttpContext.Current.Request.Headers.AllKeys.Contains("Authorization"))
            //    return false;
            string authHeader = HttpContext.Current.Request.Headers["Authorization"];
            IPrincipal principal;
            if (TryGetPrincipal(authHeader, out principal))
            {
                HttpContext.Current.User = principal;
                return true;
            }
            return false;
        }
 
        private static bool TryGetPrincipal(string authHeader, out IPrincipal principal)
        {
            var creds = ParseAuthHeader(authHeader);
            if (creds != null && TryGetPrincipal(creds, out principal))
                return true;
            principal = null;
            return false;
        }
 
        private static string[] ParseAuthHeader(string authHeader)
        {
            // Check this is a Basic Auth header 
            if (authHeader == null || authHeader.Length == 0 ||  !authHeader.StartsWith("Basic"))
                return null;
            // Pull out the Credentials with are seperated by ‘:’ and Base64 encoded 
            string base64Credentials = authHeader.Substring(6);
            string[] credentials = Encoding.ASCII.GetString(Convert.FromBase64String(base64Credentials)).Split(new char[] { ':' }); 
 
***         if (credentials.Length != 2 || string.IsNullOrEmpty(credentials[0]) ||  string.IsNullOrEmpty(credentials[0]))
                return null; 
***          // Okay this is the credentials 
***         return credentials; 
        }
 
        private static bool TryGetPrincipal(string[] creds, out IPrincipal principal)
        {
            if (creds[0] == "Administrator" && creds[1] == "SecurePassword") 
***         {
                principal = new GenericPrincipal(new GenericIdentity("Administrator"), new string[] {"Administrator", "User"});
                return true;
            } 
***         else if (creds[0] == "JoeBlogs" && creds[1] == "Password") 
***         {
                principal = new GenericPrincipal( new GenericIdentity("JoeBlogs"), new string[] {"User"});
                return true;
            } 
***         else 
***         {
                principal = null;
                return false;
            }
        }
    }
et la deuxième
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class CustomAuthentificationModule : IHttpModule
    {
        public void Init(HttpApplication context)
        {
            context.AuthenticateRequest +=
            new EventHandler(context_AuthenticateRequest);
        }
 
        void context_AuthenticateRequest(object sender, EventArgs e)
        {
            HttpApplication app = (HttpApplication)sender;
            if (!CustomAuthenticationProvider.Authenticate(app.Context))
            {
                app.Context.Response.Status = "401 Unauthorized";
                app.Context.Response.StatusCode = 401;
                app.Context.Response.End();
            }
        }
 
 
 
        public void Dispose() { }
    }
Dans le web.config
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <connectionStrings>
    <add name="KALENDO_DEVEntities" connectionString="metadata=res://*/Model_KALENDO.csdl|res://*/Model_KALENDO.ssdl|res://*/Model_KALENDO.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=.\SQLEXPRESS;initial catalog=KALENDO_DEV;persist security info=True;user id=***;*******=Kaspersky2013;multipleactiveresultsets=True;application name=EntityFramework&quot;" providerName="System.Data.EntityClient" />
  </connectionStrings>
  <appSettings>
    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
  </appSettings>
  <system.web>
    <compilation debug="true" targetFramework="4.5" />
    <httpRuntime targetFramework="4.5"/>
  </system.web>
  <system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <!-- Pour éviter la divulgation d'informations de métadonnées, définissez les valeurs ci-dessous sur false avant le déploiement -->
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
          <!-- Pour recevoir les détails de l'exception dans les erreurs à des fins de débogage, définissez la valeur ci-dessous sur true. Pour éviter la divulgation d'informations d'exception, définissez-la sur false avant le déploiement -->
          <serviceDebug includeExceptionDetailInFaults="false"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <protocolMapping>
        <add binding="basicHttpsBinding" scheme="https" />
    </protocolMapping>    
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
  </system.serviceModel>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true">
      <remove name="CustomAuthenticationModule" />
      <add name="CustomAuthenticationModule" type="SERVICES_WCF.CustomAuthentificationModule"/>
 
      <!--  -->
    </modules>  
 
    <!--
        Pour parcourir le répertoire racine de l'application Web lors du débogage, définissez la valeur ci-dessous sur true.
        Définissez-la sur false avant le déploiement pour ne pas divulguer d'informations du dossier de l'application Web.
      -->
    <directoryBrowse enabled="true"/>
  </system.webServer>
 
</configuration>

COTE CLIENT EN WPF


Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
  Context = new KALENDO_DEVEntities(new Uri("http://localhost:57500/WcfDataEntity.svc/"));
            Context.Credentials = new NetworkCredential("USER", "PASSWORD", "DOMAINE"); ;
 
            f = new WDATASERVICE.FORME_JURIDIQUE();
            f.FJUR_LIBELLE = "libelle";
            f.FJUR_ACTIF = true;
            f.FJUR_CODE = "CDFORM";
            f.FJUR_CREATION = DateTime.Now;
 
            Context.AddToFORME_JURIDIQUE(f);
            Context.SaveChanges();
PS => si je n'est pas de sécurité en place, je n'ai aucun problème, le CRUD ok!
Merci.
Cordialement