Невозможно получить идентификацию пользователя, установленную в Web Core API v1 - PullRequest
0 голосов
/ 28 ноября 2018

У меня есть проект Web Core API версии 1, где, когда я вызываю метод через Postman, я обнаруживаю, что тег [Authorize] не работает.В моем веб-API мой запуск выглядит следующим образом (отредактировано для удобства чтения)

    public void ConfigureServices(IServiceCollection services)
    {
        var manager = new ApplicationPartManager();
        manager.ApplicationParts.Add(new AssemblyPart(typeof(Startup).Assembly));
        services.AddSingleton(manager);
        services.AddCors();
        services.AddMvcCore().AddJsonFormatters();

        services.Configure<IISOptions>(options => new IISOptions
        {
            AutomaticAuthentication = true,
            ForwardClientCertificate = false,
            ForwardWindowsAuthentication = false
        });

    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler();
        }

        app.UseIdentityServerAuthentication(new IdentityServerAuthenticationOptions
        {
            RequireHttpsMetadata = false,
            Authority = Settings.AuthorityUrl,
            ApiName = Settings.ApiName
        });

        app.UseStaticFiles();
        var url = Configuration["originUrl"];
        app.UseCors(
            options => options.WithOrigins(url).AllowAnyHeader().AllowAnyMethod().AllowCredentials()
        );

        app.UseMiddleware<StackifyMiddleware.RequestTracerMiddleware>();
        app.UseMvc();
    }

На моем сервере OAuth я использую Quickstart для IdentityServer4

  public class Startup
    {
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddIdentityServer()
                .AddSigningCredential(new X509Certificate2(Settings.CertPath, Settings.Password))
                .AddTestUsers(InMemoryConfiguration.Users().ToList())
                .AddInMemoryClients(InMemoryConfiguration.Clients())
                .AddInMemoryApiResources(InMemoryConfiguration.ApiResources());

            services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
                .AddIdentityServerAuthentication(options =>
                {
                    options.RequireHttpsMetadata = false;
                    options.Authority = Settings.AuthorityUrl;
                    options.ApiName = Settings.ApiName;
                });
            services.AddMvc();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole();
            loggerFactory.AddDebug();
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseMiddleware<StackifyMiddleware.RequestTracerMiddleware>();
            app.UseIdentityServer();
            app.UseStaticFiles();
            app.UseMvcWithDefaultRoute();
        }
    }

И это метод, которым я являюсьзвоню в Почтальон;

[HttpGet("get")]
public async Task<IActionResult> Get()
{
    var claims = User.Claims;
    var username = User.Identity.Name;
    this.NLogger.Info("api/comboboxdata/get".ToPrefix());
    try
    {
        var container = new ComboBoxData(this.SirUoW);
        return Ok(container);
    }
    catch (Exception e)
    {
        var message = "Error getting combo box data";
        await ReportException(e, message);
        var status = OperationStatus.CreateFromException(message, e);
        return BadRequest(status);
    }
}

В Почтальоне я получаю токен на предъявителя и помещаю его в заголовок.Метод успешно вызывается и возвращает данные.Претензии также устанавливаются в соответствии с ожиданиями, и по истечении срока действия токена они становятся пустыми.Однако [Авторизация] не блокирует запрос, если токен недействителен или не отправлен.Атрибут Authorize находится в начале контроллера;

 [Authorize]
    [Route("api/comboboxdata")]
    public class ComboBoxDataController : BaseSirController
    {

Как это исправить?

1 Ответ

0 голосов
/ 03 декабря 2018

Вы должны добавить AddAuthorization метод, чтобы включить сервисы авторизации в вашем веб-интерфейсе:

services.AddMvcCore()
                .AddAuthorization()
                .AddJsonFormatters();
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...