Аутентификация в CoreWCF-ServerC#

Место общения программистов C#
Ответить
Anonymous
 Аутентификация в CoreWCF-Server

Сообщение Anonymous »

В настоящее время я мигрирую приложение .NET 4.8, которое размещает несколько API REST и интерфейсы WCF в Core ASP.NET (.NET 8). Чтобы перенести интерфейсы WCF, я использую CoreWCF.

Код: Выделить всё

 using (HttpClientHandler handler = new HttpClientHandler())
{
handler.UseDefaultCredentials = true;

using (HttpClient client = new HttpClient(handler))
{
var response = client.GetAsync($"https://localhost:44375/api/interfaces").Result;
}
}
< /code>
Сервер размещен в IIS Express для разработки и должен работать на сервере IIS при развертывании. Но сейчас это не проблема.  < /P>
Клиентский код для инициализации соединения WCF: < /p>
 private static void EnsureWCFServiceBindings()
{
if (transportBinding == null)
{
XmlDictionaryReaderQuotas readerQuotas = new XmlDictionaryReaderQuotas();
readerQuotas.MaxDepth = 2147483647;
readerQuotas.MaxStringContentLength = 2147483647;
readerQuotas.MaxArrayLength = 2147483647;
readerQuotas.MaxBytesPerRead = 2147483647;
readerQuotas.MaxNameTableCharCount = 2147483647;

HttpTransportSecurity httpTransportSecurity = new HttpTransportSecurity();
httpTransportSecurity.ClientCredentialType = HttpClientCredentialType.Ntlm;
httpTransportSecurity.ProxyCredentialType = HttpProxyCredentialType.Ntlm;
httpTransportSecurity.Realm = "mydomain.com";

BasicHttpMessageSecurity basicHttpMessageSecurity = new BasicHttpMessageSecurity();
basicHttpMessageSecurity.ClientCredentialType = BasicHttpMessageCredentialType.UserName;
basicHttpMessageSecurity.AlgorithmSuite = SecurityAlgorithmSuite.Default;

BasicHttpsSecurity basicHttpsSecurity = new BasicHttpsSecurity
{
Mode = BasicHttpsSecurityMode.Transport,
Transport = httpTransportSecurity,
Message = basicHttpMessageSecurity
};

BasicHttpsBinding basicHttpsBinding = new BasicHttpsBinding
{
CloseTimeout = TimeSpan.FromMinutes(5),
OpenTimeout = TimeSpan.FromMinutes(5),
ReceiveTimeout = TimeSpan.FromMinutes(10),
SendTimeout = TimeSpan.FromMinutes(5),
AllowCookies = false,
BypassProxyOnLocal = false,
HostNameComparisonMode = HostNameComparisonMode.StrongWildcard,
MaxBufferSize = 2147483647,
MaxBufferPoolSize = 0,
MaxReceivedMessageSize = 2147483647,
MessageEncoding = WSMessageEncoding.Text,
TextEncoding = Encoding.UTF8,
TransferMode = TransferMode.Buffered,
ReaderQuotas = readerQuotas,
Security = basicHttpsSecurity
};
transportBinding = basicHttpsBinding;
}

if (clientBuildClient == null)
{
clientBuildClient = new EndpointAddress(string.Format("{0}{1}", "https://localhost:44375/", "BuildClient.svc"));
}
}
< /code>
и вызов на сервер выполняется со следующим кодом: < /p>
MyCommunicationClient myClient = new MyCommunicationClient (WCFBindings.TransportBinding, WCFBindings.EndPointBuildClient));
ResultObject response = myClient.CallService(serviceRequestParameter);
Когда я пробую этот вызов WCF в Migrated Service, я получаю httpstatuscode 401.

Код: Выделить всё

builder.Services.AddHttpContextAccessor();
builder.Services.AddAuthentication(NegotiateDefaults.AuthenticationScheme)
.AddNegotiate();

builder.Services.AddAuthorization(options =>
{
options.FallbackPolicy = options.DefaultPolicy;
options.AddPolicy("RequireWindowsAuth", policy =>
{
policy.RequireAuthenticatedUser();
policy.AddAuthenticationSchemes(NegotiateDefaults.AuthenticationScheme);
});
});

builder.WebHost.UseIISIntegration();
// some more code here
app.UseServiceModel(serviceBuilder =>
{
serviceBuilder.AddService((serviceOptions) =>  { })
.AddServiceEndpoint(new BasicHttpBinding
{
Security = new BasicHttpSecurity
{
Mode = BasicHttpSecurityMode.Transport,
Transport = new HttpTransportSecurity
{
ClientCredentialType = HttpClientCredentialType.Windows,
AlwaysUseAuthorizationPolicySupport = true,
Realm = "mydomain.com"
}
}
}, "/BuildClient.svc");
});

var serviceMetadataBehavior = app.Services.GetRequiredService();
serviceMetadataBehavior.HttpGetEnabled = true;
serviceMetadataBehavior.HttpsGetEnabled = true;

IHttpContextAccessor httpContextAccessor = app.Services.GetRequiredService();
IdentityProvider.Configure(httpContextAccessor);

app.UseAuthentication();
app.UseAuthorization();
< /code>
Конфигурация для IIS Express: < /p>
{
"iisSettings": {
"windowsAuthentication": true,
"anonymousAuthentication": false,
"iisExpress": {
"applicationUrl": "http://localhost:50228",
"sslPort": 44375
}
},
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchUrl": "swagger",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
},
"BuildService": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"applicationUrl": "http://localhost:50228;https://localhost:44375",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
< /code>
С помощью этой настройки я получаю уже упомянутый 401 код состояния HTTP. Когда я изменяю addauthentication 
, чтобы выглядеть так:

Код: Выделить всё

builder.Services.AddAuthentication("Ntlm")
.AddScheme("Ntlm", options =>
{
options.Domain = "mydomain.com";
}).AddNegotiate();
где ntlmauthenticationhandler содержит следующее:
protected override async Task HandleAuthenticateAsync()
{
var user = Context.User;
var user2 = IdentityProvider.Current;
}
< /code>
Когда я смотрю на пользователя или пользователь2-viable, в то время как аутентификация я вижу в запросе отдыха, который я аутентифицирован, и мой идентификатор пользователя предоставляется. В запросе WCF не предоставляется идентификатор пользователя, и запрос не является аутентифицированным. Вам нужна дополнительная информация о сервере или клиенте, я могу его предоставить.

Подробнее здесь: https://stackoverflow.com/questions/794 ... wcf-server
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «C#»