gpt4 book ai didi

c# - .NetCore 和 SoapCore 如何进行身份验证

转载 作者:行者123 更新时间:2023-12-02 03:43:44 25 4
gpt4 key购买 nike

我想添加身份验证作为 NetworkCredential 但我不知道如何设置身份验证

var binding = new BasicHttpBinding();
var endpoint = new EndpointAddress(new Uri(string.Format("http://{0}:5050/Service.svc", Environment.MachineName)));
var channelFactory = new ChannelFactory<ISampleService>(binding, endpoint);
var serviceClient = channelFactory.CreateChannel();

最佳答案

您可以在我的代码中激发灵感。我花了一些时间和一些调查。请记住,服务契约(Contract)接口(interface)是由 Controller 实现的,我没有找到任何其他方法将服务请求放入 http 管道。由于这种配置,我可以在一个代码上运行 REST 和 SOAP 分支。

在 Startup.cs 中:

using SoapCore;
using ZNetCS.AspNetCore.Authentication.Basic;
using ZNetCS.AspNetCore.Authentication.Basic.Events;

public void ConfigureServices (IServiceCollection services)
{
services.AddScoped<YourNamespace.BasicAuthValidator>();
services.AddSingleton<YourNamespace.Contracts.IEnityService, YourNamespace.Controllers.ApiController>();
services.AddAuthentication(BasicAuthenticationDefaults.AuthenticationScheme)
.AddBasicAuthentication(op => {
op.Realm = "YourRealm";
op.EventsType = typeof(YourNamespace.BasicAuthValidator);
});
services.AddControllers();
}

public void Configure (IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints => {
endpoints.MapControllers().RequireAuthorization(); //Use DefaultAuthorizationPolicy, ie. require authenticated users on REST interface
endpoints.UseSoapEndpoint<YourNamespace.Contracts.IEnityService>("/SOAP/YourService.svc", this.CreateBindingForSOAP(), SoapSerializer.DataContractSerializer).RequireAuthorization();
}

BasicHttpBinding CreateBindingForSOAP ()
{
var binding = new BasicHttpBinding(BasicHttpSecurityMode.Transport); //security is on HTTP level
binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Basic; //http challenges filling Authorization header
return binding;
}

然后创建用于处理基本身份验证的类:

public class BasicAuthValidator:BasicAuthenticationEvents
{
public override Task ValidatePrincipalAsync (ValidatePrincipalContext context)
{
if ((context.UserName == "userName") && (context.Password == "password")) {
var claims = new List<Claim>{new Claim(ClaimTypes.Name, context.UserName, context.Options.ClaimsIssuer)};

var principal = new ClaimsPrincipal(new ClaimsIdentity(claims, context.Scheme.Name));
context.Principal = principal;
}

return Task.CompletedTask;
}
}

关于c# - .NetCore 和 SoapCore 如何进行身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47535296/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com