gpt4 book ai didi

authentication - 在 .net core 中使用身份验证方案时返回 403(forbidden)

转载 作者:行者123 更新时间:2023-12-04 16:29:34 25 4
gpt4 key购买 nike

我正在使用 Jwt 安全 token 和自定义身份验证方案在我的 Web 应用程序中进行身份验证。

1)我在用户登录时生成 token

2)我创建了身份验证处理程序,我在其中验证所有请求的 token

//Authentication Handler

public class CustomAuthenticationHandler : AuthenticationHandler<CustomAuthenticationOptions>
{
public CustomAuthenticationHandler(
IOptionsMonitor<CustomAuthenticationOptions> options,
ILoggerFactory logger,
UrlEncoder encoder,
ISystemClock clock)
: base(options, logger, encoder, clock)
{

}

protected override Task<AuthenticateResult> HandleAuthenticateAsync()
{
try
{
Exception ex;
var key = Request.Headers[Options.HeaderName].First();

if (!IsValid(key, out ex))
{

return Task.FromResult(AuthenticateResult.Fail(ex.Message));
//filterContext.Result = new CustomUnauthorizedResult(ex.Message);
}
else
{

AuthenticationTicket ticket = new AuthenticationTicket(new ClaimsPrincipal(),new AuthenticationProperties(),this.Scheme.Name);
return Task.FromResult(AuthenticateResult.Success(ticket));
}
}
catch (InvalidOperationException)
{
return Task.FromResult(AuthenticateResult.Fail(""));
}
}
}

public static class CustomAuthenticationExtensions
{
public static AuthenticationBuilder AddCustomAuthentication(this AuthenticationBuilder builder, string authenticationScheme, string displayName, Action<CustomAuthenticationOptions> configureOptions)
{
return builder.AddScheme<CustomAuthenticationOptions, CustomAuthenticationHandler>(authenticationScheme, displayName, configureOptions);
}
}

这是我的startup.cs
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}

public IConfiguration Configuration { get; }

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddMvc().AddFluentValidation(fv => fv.RegisterValidatorsFromAssemblyContaining<Person>());
services.AddTransient<IRepositoryWrapper, RepositoryWrapper>();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

services.AddAuthentication(options=> {
options.DefaultScheme = "CustomScheme";
options.DefaultAuthenticateScheme = "CustomScheme";
options.DefaultChallengeScheme = "CustomScheme";
}).AddCustomAuthentication("CustomScheme", "CustomScheme", o => { });

}


public void Configure(IApplicationBuilder app, IHostingEnvironment env,ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole();
loggerFactory.AddDebug(LogLevel.Information);

if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
}

app.UseAuthentication();
app.UseHttpsRedirection();
app.UseMvc();

}
}

在这里我使用了身份验证方案
[Authorize(AuthenticationSchemes ="CustomScheme")]
[ApiController]
[Route("api/controller")]
public class UserController : BaseController
{

public UserController(IRepositoryWrapper repository) : base(repository)
{
}

[HttpGet]
public IEnumerable<Users> Get()
{
return _repository.Users.FindAll();
}
}

当我使用有效 token 从 postman 调用 api 时,它返回 403 错误。

请帮忙解决这个问题...!!

最佳答案

对于遇到此问题的其他人:
最初的问题似乎是在 AuthenticationHandler 中返回 AuthenticationResult 时,没有将 ClaimsIdentity 传递给 ClaimsPrincipal。另请注意,身份验证类型必须传递给 ClaimsIdentity,否则 IsAuthenticated 将为 false。在 AuthenticationHandler 中做这样的事情应该可以解决这个问题:

else
{
var claimsPrincipal = new ClaimsPrincipal();
var claimsIdentity = new ClaimsIdentity("JWT");
claimsPrincipal.AddIdentity(claimsIdentity);

var ticket = new AuthenticationTicket(claimsPrincipal, this.Scheme.Name);

return AuthenticateResult.Success(ticket);
}

关于authentication - 在 .net core 中使用身份验证方案时返回 403(forbidden),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53519802/

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