возвращает 403 (запрещено) при использовании схемы аутентификации в ядре .net - PullRequest
0 голосов
/ 28 ноября 2018

Я выполняю аутентификацию в своем веб-приложении с токенами безопасности 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.

Пожалуйста, помогите решить эту проблему ... !!

1 Ответ

0 голосов
/ 29 ноября 2018

Я нашел решение.

Я использовал CustomAuthenticationMiddle вместо AuthenticationHandler

public class CustomAuthenticationMiddleware
{
    private readonly RequestDelegate _next;
    public CustomAuthenticationMiddleware(RequestDelegate next)
    {
        _next = next;
    }
    public async Task Invoke(HttpContext context)
    {
            try
            {
                Exception ex;
                var key = context.Request.Headers["Authorization"].First();

                if (!IsValid(key))
                {
                       //logic for authentication
                }
                else
                {

                    await _next.Invoke(context);
                }
            }
            catch (InvalidOperationException)
            {
                context.Response.StatusCode = 401; //Unauthorized
                return;
            }
        }

    private bool IsValid(string key)
    {
        //Code for checking the key is valid or not
    }
}

, и я добавил следующее в startup.cs

app.UseMiddleware<CustomAuthenticationMiddleware>();
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...