Я выполняю аутентификацию в своем веб-приложении с токенами безопасности Jwt и пользовательской схемой аутентификации.
1) Я генерирую токены, когда логин пользователя
2) Я создал обработчик аутентификации, где я проверяютокен для всех запросов
//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();
}
}
Когда я вызываю API изпочтальон с действительным токеном возвращает ошибку 403.
Пожалуйста, помогите решить эту проблему ... !!