powered by simpleCommunicator - 2.0.40     © 2025 Programmizd 02
Форумы / WCF, Web Services, Remoting [игнор отключен] [закрыт для гостей] / Как аутентифицировать внешние запросы к WCF Web- сервису?
2 сообщений из 2, страница 1 из 1
Как аутентифицировать внешние запросы к WCF Web- сервису?
    #39218734
Коллеги, приветствую.

Есть некоторый простой WCF Web- сервис ("SayHello") и консольный клиент, полученный из WSDL Web- сервиса.

Контракт Web- сервиса:

Код: c#
1.
2.
3.
4.
5.
6.
7.
8.
9.
namespace SimpleCustomService
{
    [ServiceContract]
    public interface UsrIService
    {
        [OperationContract]
        string SayHello();
    }
}



Реализация Web- сервиса:

Код: c#
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
namespace SimpleCustomService
{
    public class UsrService : UsrIService
    {
        public string SayHello()
        {
            return "Hello";
        }
    }
}



Используя утилиту wsdl.exe я сгенерировал прокси- классы, скомпилировал их в сборку и добавил сборку в проект консольного клиента.

И Web- сервис, и его клиент работаю на платформе .NET Framework 4.5

Сгенерированный прокси- класс выглядит так:

Код: c#
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.
62.
63.
64.
65.
66.
67.
68.
69.
70.
71.
72.
73.
74.
75.
76.
77.
78.
79.
80.
81.
82.
83.
84.
85.
86.
87.
88.
89.
90.
91.
92.
93.
94.
95.
96.
97.
98.
99.
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Serialization;

// 
// This source code was auto-generated by wsdl, Version=4.6.1055.0.
// 


/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.6.1055.0")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Web.Services.WebServiceBindingAttribute(Name="BasicHttpBinding_UsrIService", Namespace="http://tempuri.org/")]
public partial class UsrService : System.Web.Services.Protocols.SoapHttpClientProtocol {

    private System.Threading.SendOrPostCallback SayHelloOperationCompleted;

    /// <remarks/>
    public UsrService() {
        this.Url = "http://localhost:8080/0/ServiceModel/SimpleCustomService.svc/soap";
    }

    /// <remarks/>
    public event SayHelloCompletedEventHandler SayHelloCompleted;

    /// <remarks/>
    [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://tempuri.org/UsrIService/SayHello", RequestNamespace="http://tempuri.org/", ResponseNamespace="http://tempuri.org/", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
    [return: System.Xml.Serialization.XmlElementAttribute(IsNullable=true)]
    public string SayHello() {
        object[] results = this.Invoke("SayHello", new object[0]);
        return ((string)(results[0]));
    }

    /// <remarks/>
    public System.IAsyncResult BeginSayHello(System.AsyncCallback callback, object asyncState) {
        return this.BeginInvoke("SayHello", new object[0], callback, asyncState);
    }

    /// <remarks/>
    public string EndSayHello(System.IAsyncResult asyncResult) {
        object[] results = this.EndInvoke(asyncResult);
        return ((string)(results[0]));
    }

    /// <remarks/>
    public void SayHelloAsync() {
        this.SayHelloAsync(null);
    }

    /// <remarks/>
    public void SayHelloAsync(object userState) {
        if ((this.SayHelloOperationCompleted == null)) {
            this.SayHelloOperationCompleted = new System.Threading.SendOrPostCallback(this.OnSayHelloOperationCompleted);
        }
        this.InvokeAsync("SayHello", new object[0], this.SayHelloOperationCompleted, userState);
    }

    private void OnSayHelloOperationCompleted(object arg) {
        if ((this.SayHelloCompleted != null)) {
            System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg));
            this.SayHelloCompleted(this, new SayHelloCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState));
        }
    }

    /// <remarks/>
    public new void CancelAsync(object userState) {
        base.CancelAsync(userState);
    }
}

/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.6.1055.0")]
public delegate void SayHelloCompletedEventHandler(object sender, SayHelloCompletedEventArgs e);

/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.6.1055.0")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
public partial class SayHelloCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs {

    private object[] results;

    internal SayHelloCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : 
            base(exception, cancelled, userState) {
        this.results = results;
    }

    /// <remarks/>
    public string Result {
        get {
            this.RaiseExceptionIfNecessary();
            return ((string)(this.results[0]));
        }
    }
}



Все внешние запросы к Web- сервису должны быть аутентифицированы. Для этого я передаю учетные данные пользователя в заголовке SOAP:

Код: c#
1.
2.
3.
4.
5.
using (UsrService client = new UsrService())
{
    client.Credentials = new System.Net.NetworkCredential("Пользователь 1", "Пользователь 1");
    client.SayHello();
}



Однако таким образом запрос аутентифицировать не удается и, насколько я понимаю, происходит редирект на форму авторизации:

Код: html
1.
http://localhost:8080/NuiLogin.aspx?ReturnUrl=%2f0%2fServiceModel%2fSimpleCustomService.svc



В консоли я вижу такое исключение:

Код: html
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
Необработанное исключение: System.Net.WebException: Сбой запроса с сообщением об
 ошибке:
--
<html><head><title>Object moved</title></head><body>
<h2>Object moved to <a href="/NuiLogin.aspx?ReturnUrl=%2f0%2fServiceModel%2fSimp
leCustomService.svc%2fsoap">here</a>.</h2>
</body></html>

--.
   в System.Web.Services.Protocols.SoapHttpClientProtocol.ReadResponse(SoapClien
tMessage message, WebResponse response, Stream responseStream, Boolean asyncCall
)
   в System.Web.Services.Protocols.SoapHttpClientProtocol.Invoke(String methodNa
me, Object[] parameters)
   в UsrService.SayHello() в c:\VS2015\Projects\WCFSharedDLL\WCFSharedDLL\TestPr
oxyClass.cs:строка 44
   в ConsoleApplicationForTesting.Program.Main(String[] args) в c:\VS2015\Projec
ts\ConsoleApplicationForTesting\ConsoleApplicationForTesting\Program.cs:строка 1
6
Для продолжения нажмите любую клавишу . . .



Если в код клиента добавить:

Код: c#
1.
client.AllowAutoRedirect = true;



В консоли появляется следующее (исходный код страницы авторизации):

Код: html
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.
62.
63.
64.
65.
66.
67.
68.
69.
70.
71.
72.
73.
74.
75.
76.
77.
78.
79.
80.
81.
82.
83.
84.
85.
86.
87.
88.
89.
90.
91.
92.
93.
94.
95.
96.
97.
98.
99.
100.
101.
102.
103.
104.
105.
106.
107.
108.
109.
110.
111.
112.
113.
114.
115.
116.
117.
118.
119.
120.
121.
122.
123.
124.
125.
126.
127.
128.
129.
130.
131.
132.
133.
134.
135.
136.
137.
138.
139.
140.
141.
142.
143.
144.
145.
146.
147.
148.
149.
150.
151.
152.
Unhandled exception: System.InvalidOperationException: The client found response content type "text/html; charset=utf-8", but expected type is "text/xml". The request failed with the error message:
--


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.or
g/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head><meta http-equiv="X-UA-Compatible" content="IE=Edge" /><meta http-equiv="C
ontent-Type" content="text/html; charset=utf-8" /><link href="favicon.ico" rel="
shortcut icon" type="image/vnd.microsoft.icon" /><title>
        bpm'online bank customer journey
</title>
        <style>
                .login-label-logo
                {
                        background: url("terrasoft.axd?s=nui-binary-syssetting&r
=Logoimage");
                        background-repeat: no-repeat;
                        width: 223px;
                        height: 100px;
                        margin-bottom: 28px;
                        background- bottom;
                }
        </style>
<script type="text/javascript">
window.workspaceList = {'1': { value: 'Default', displayValue: 'Default' }};
window.supportInfo = [];
window.supportInfoCaption = '';
window.importantLinks = [];
window.importantLinksCaption = '';
window.productVersion = '7.7.0.2872';
window.loginTimeout = '30000';
window.workspaceCount = 1;
var Terrasoft = Terrasoft || {};
window.isNtlmLoginVisible = false;
</script>
<script type="text/javascript" src="http://localhost:8080//core-sl/3218931132877
873a78c92ded6a0b0cf/Terrasoft.Nui"></script>
<script type="text/javascript">
var Terrasoft = Terrasoft || {};
Terrasoft.loaderBaseUrl = 'http://localhost:8080/';
Terrasoft.workspaceBaseUrl = 'http://localhost:8080/';
</script>
<script type="text/javascript">
var FileAPI = {
        staticPath: '../Resources/ui/FileAPI/',
        flashUrl: '../Resources/ui/FileAPI/FileAPI.flash.swf',
        flashImageUrl: '../Resources/ui/FileAPI/FileAPI.flash.image.swf' };
</script>
<script type="text/javascript">
var Terrasoft = Terrasoft || {};Terrasoft.enablePerformanceManager = false;</scr
ipt>
<!--[if IE 8]>
<script type="text/javascript" src="http://localhost:8080//core/b812d8cf89ec068b
5cdda18f2d0de397/normalize/es5shim.js"></script>
<![endif]-->
<script type="text/javascript" src="http://localhost:8080//core/db7fe0930e6258f0
1fb73405039cc9a5/normalize/classList-shim.js"></script>
<script type="text/javascript" src="http://localhost:8080//core/824fc2789913efd8
506c23cfd39496e8/history/history.js"></script>
<script type="text/javascript" src="http://localhost:8080//core/b515858f8b0235cd
de97a34f56882a5b/combined/all-combined.js"></script>
<link rel="stylesheet" type="text/css" href="http://localhost:8080//core/d9868b8
8e2b56f0964c6c0146598e324/combined/all-combined.css" />
<link rel="stylesheet/less" type="text/css" href="http://localhost:8080//core/7e
1adee4ce5c31795a7bb8819c10aeb8/combined/all-combined.less" />
<script type="text/javascript" src="http://localhost:8080//core/48bca5c68f167104
05127cce054f5534/requirejs/require.js"></script>
<script type="text/javascript">
requirejs.config({
paths: {
'core':'http://localhost:8080//core/ef58ab72c648daaa7af074e2526dffc3/Terrasoft/a
md/core',
'bootstrap':'http://localhost:8080//core/022b4acc49ebfbfb33b54d4f95393d2a/Terras
oft/amd/bootstrap',
'performancecountermanager':'http://localhost:8080//core/3bf271e2ad15f056eac25ab
fea30226a/Terrasoft/amd/performancecountermanager',
'loadbootstrap':'http://localhost:8080//core/b0ebbf0e263a02a3db86bf39761aba1c/Te
rrasoft/amd/bootstrap.login',
'jQuery':'http://localhost:8080//core/8d24859b5ac713ab6f05091492b6c631/jQuery/jQ
uery',
'jQuery-easing':'http://localhost:8080//core/a6f75e0c043a2a087837e5c113cc6f7a/jQ
ueryEasing/jQuery-easing',
'jsrender':'http://localhost:8080//core/77f59dfac75bba6c861fe26d75691086/jsrende
r/jsrender',
'ej-common-all':'http://localhost:8080//core/e8b46aebd6473a2f85386c0d072a2b93/Sy
ncfusion/min/ej-common-all',
'ej-diagram':'http://localhost:8080//core/89f5be5f51b070471058224a6550b99a/Syncf
usion/min/ej-diagram',
'process-schema-diagram':'http://localhost:8080//core/650e4ae64a84c1fd11caab7904
39c8ef/Terrasoft/designers/process-schema-designer/process-schema-diagram',
'process-schema-diagram-5x':'http://localhost:8080//core/b0b08b3ec18e7494d488622
07309479f/Terrasoft/designers/process-schema-designer/process-schema-diagram-5x'
,
'ckeditor-base':'http://localhost:8080//core/04628941838af9176121c9cd4332b49d/CK
Editor/ckeditor',
'html2canvas':'http://localhost:8080//core/524ae0cfb507a786266d32d9a16ccc42/html
2canvas/html2canvas'
},
shim: {'jQuery-easing': {'deps': ['jQuery']}, 'ej-common-all': {'deps': ['jQuery
-easing']}, 'ej-diagram': {'deps': ['ej-common-all', 'jsrender']}, 'process-sche
ma-diagram': {'deps': ['ej-diagram']}, 'process-schema-diagram-5x': {'deps': ['p
rocess-schema-diagram']}}});
require(['loadbootstrap'],function() {});
</script>
<script type="text/javascript">
var Terrasoft = Terrasoft || {};
Terrasoft.isDebug = false;
Terrasoft.DataValueTypeRange = {INTEGER: {maxValue:2147483647,minValue:-21474836
48},FLOAT: {maxValue:79228162514264337593543950335,minValue:-7922816251426433759
3543950335},DATE_TIME: {maxValue:"0001-01-01T00:00:00.000",minValue:"0001-01-01T
00:00:00.000"}};
Terrasoft.storesConfig = [];
Terrasoft.storesConfig.push({levelName: 'ClientPageSession', type: 'Terrasoft.Me
moryStore', isCache: true});Terrasoft.storesConfig.push({levelName: 'Domain', ty
pe: 'Terrasoft.LocalStore', isCache: true});
if(Terrasoft.StoreManager){
        Terrasoft.StoreManager.registerStores(Terrasoft.storesConfig);
}

</script>
</head>
<body>
        <form name="IndexForm" method="post" action="./NuiLogin.aspx?ReturnUrl=%
2f0%2fServiceModel%2fSimpleCustomService.svc%2fsoap" id="IndexForm">
<div>
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="Ael0TejuuQ2cn+6a
KrS5wJo2ATMwUDq1DBRh5WGdOqpW+NOyOwBLY85L9xsvJnX+0sZlKI3bZN5Qk7o0okrcDBSteeTArKGx
leRg/1ydqd/XMABb" />
</div>

<div>

        <input type="hidden" name="__VIEWSTATEGENERATOR" id="__VIEWSTATEGENERATO
R" value="F2DA7F48" />
</div>
        </form>
</body>
</html>

--.
   in System.Web.Services.Protocols.SoapHttpClientProtocol.ReadResponse(SoapClien
tMessage message, WebResponse response, Stream responseStream, Boolean asyncCall
)
   in System.Web.Services.Protocols.SoapHttpClientProtocol.Invoke(String methodNa
me, Object[] parameters)
   in UsrService.SayHello() in c:\VS2015\Projects\WCFSharedDLL\WCFSharedDLL\TestPr
oxyClass.cs:line 44
   in ConsoleApplicationForTesting.Program.Main(String[] args) in c:\VS2015\Projec
ts\ConsoleApplicationForTesting\ConsoleApplicationForTesting\Program.cs:line 1
6



Как аутентифицировать внешние запросы к WCF Web- сервису?

Был бы весьма признателен за информацию.

Спасибо.

--
С уважением, Алексей Быков.
...
Рейтинг: 0 / 0
Как аутентифицировать внешние запросы к WCF Web- сервису?
    #39218913
Решил таким образом. На уровне транспортного протокола передал учетные данные:

Код: c#
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.
public const string authServiceUri = 
	"http://localhost:8080/ServiceModel/AuthService.svc/Login";
public static CookieContainer AuthCookie = 
	new CookieContainer();

public static bool TryLogin(string userName, string userPassword)
{
    var authRequest = HttpWebRequest.Create(authServiceUri) 
		as HttpWebRequest;
		
    authRequest.Method = "POST";
    authRequest.ContentType = "application/json";
    authRequest.CookieContainer = AuthCookie;

    using (var requesrStream = authRequest.GetRequestStream())
    {
        using(var writer = new StreamWriter(requesrStream))
        {
            writer.Write(@"{
                ""UserName"":""" + userName + @""",
                ""UserPassword"":""" + userPassword + @"""
            }");
        }
    }

    using(var response = (HttpWebResponse)authRequest.GetResponse())
    {
        if (AuthCookie.Count > 0)
        {
            return true;
        }
    }
    return false;
}



Установил CookieContainer:

Код: c#
1.
client.CookieContainer = AuthCookie;



Стало возможным выполнять запросы к Web- сервису:

Код: c#
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
static void Main(string[] args)
{
        using (UsrService client = new UsrService())
        {
                if(TryLogin("Пользователь 1", "Пользователь 1"))
                {
                        client.CookieContainer = AuthCookie;
                        Console.WriteLine(client.SayHello());
                }
        }
}



Хотя и осталось непонятным, почему не удалось аутентифицировать внешние запросы через передачу учетных данных в SOAP заголовке...
...
Рейтинг: 0 / 0
2 сообщений из 2, страница 1 из 1
Форумы / WCF, Web Services, Remoting [игнор отключен] [закрыт для гостей] / Как аутентифицировать внешние запросы к WCF Web- сервису?
Целевая тема:
Создать новую тему:
Автор:
Закрыть
Цитировать
Найденые пользователи ...
Разблокировать пользователей ...
Читали форум (0):
Пользователи онлайн (0):
x
x
Закрыть


Просмотр
0 / 0
Close
Debug Console [Select Text]