Коллеги, приветствую.

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

using (UsrService client = new UsrService())
{
        client.Credentials = new System.Net.NetworkCredential("Пользователь 1", "Пользователь 1");
        client.SayHello();
}

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

Запрос не проходит аутентификацию и, насколько я понимаю, происходит редирект на форму логина.

http://localhost:8080/NuiLogin.aspx?ReturnUrl=%2f0%2fServiceModel%2fSimpleCustomService.svc

Что я вижу в своем консольном клиенте:

С чем это может быть связано?

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

Спасибо.

--
С уважением, Алексей Быков.

Нравится

5 комментариев

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

client.AllowAutoRedirect = true;

То в консоли вижу следующее:

Необработанное исключение: System.InvalidOperationException: Клиент обнаружил ти
п содержимого ответа "text/html; charset=utf-8", но ожидается тип "text/xml".
Сбой запроса с сообщением об ошибке:
--
 
 
<!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-position: left 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>
 
--.
   в 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
Для продолжения нажмите любую клавишу . . 

Т.е. исходный код страницы авторизации.

Решил таким образом. На уровне транспортного протокола передал учетные данные:

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:

client.CookieContainer = AuthCookie;

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

static void Main(string[] args)
{
	using (UsrService client = new UsrService())
	{
		if(TryLogin("Пользователь 1", "Пользователь 1"))
		{
			client.CookieContainer = AuthCookie;
			Console.WriteLine(client.SayHello());
		}
	}
}

Хотя и осталось непонятным, почему не удалось аутентифицировать внешние запросы через передачу учетных данных в SOAP заголовке...

Здравствуйте.
Как вариант, в заголовок запроса можно было попробовать указать content-type "text/xml".

Здравствуйте, Александр. Хорошо, спасибо - попробую и отпишусь, что вышло.

Показать все комментарии