Не удается получить доступ к ресурсу сервера, отправлен заголовок авторизации? - PullRequest
0 голосов
/ 23 марта 2019

Я не могу получить доступ к защищенным ресурсам через веб-интерфейс, например [Авторизоваться]

с использованием OAuth / OWIN ...

Что я могу сделать: 1. генерировать токен на предъявителя 2. отправить токен на предъявителя (от Axios) 3. Я попробовал это решения по этой ссылке:

означает обновленный web.config, startUp, webApiConfig,

Я был в этом в течение некоторого времени. Я делаю вызов и Chrome сетевой отладчик

{"message": "В этом запросе отказано в авторизации."}

[Authorize]
   [RoutePrefix("api/testV2")]
    public class testController : BaseApiController
    {

        readonly ItestV2Service _service;

        //public testController()
        //{

        //}

        public testController(ItestV2Service service)
        {
            _service = service;
        }




тогда

запуск

using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Owin;
using Owin;
using Microsoft.Owin.Security.OAuth;

[assembly: OwinStartup(typeof(testV2.Startup))]

namespace testV2
{
    public partial class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions { });

            ConfigureAuth(app);          
        }
    }
}



веб-конфигурация

 <appSettings>

    <add key="owin:appStartup" value="testV2.Startup" />

  </appSettings>
  <system.web>
    <authentication mode="None" />
    <compilation debug="true" targetFramework="4.6.1" />
    <httpRuntime targetFramework="4.6.1" />

    <machineKey validationKey="750C536CFAEE1375A4FB62025BB841684D463BDB13D375ECE8853121BD03C596FD042C423F47E88CFD1B81ECDE4812FE43DDEF89C6DB699DD9B65DD26462BE44" 
                decryptionKey="A34768D4D9AA3B309525F0A4AE642B2E8004155FC441827C" 
                validation="SHA1" 
                decryption="AES"/>


  </system.web>

это wedApiconfig

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Web.Http;
using Microsoft.Owin.Security.OAuth;
using Newtonsoft.Json.Serialization;

namespace testV2
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services
            // Configure Web API to use only bearer token authentication.
            config.SuppressDefaultHostAuthentication();
            config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));

            // Web API routes
            config.MapHttpAttributeRoutes();

            var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().First();
            jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }
}

это начало работы вверх


namespace testV2
{
    public partial class Startup
    {
        public static OAuthAuthorizationServerOptions OAuthOptions { get; private set; }

        public static string PublicClientId { get; private set; }

        // For more information on configuring authentication, please visit https://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app)
        {
            // Configure the db context and user manager to use a single instance per request
            app.CreatePerOwinContext(ApplicationDbContext.Create);
            app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);

            // Enable the application to use a cookie to store information for the signed in user
            // and to use a cookie to temporarily store information about a user logging in with a third party login provider
            app.UseCookieAuthentication(new CookieAuthenticationOptions());
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            // Configure the application for OAuth based flow
            PublicClientId = "self";
            OAuthOptions = new OAuthAuthorizationServerOptions
            {
                TokenEndpointPath = new PathString("/Token"),
                Provider = new ApplicationOAuthProvider(PublicClientId),
                AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
                // In production mode set AllowInsecureHttp = false
                AllowInsecureHttp = true
            };

            // Enable the application to use bearer tokens to authenticate users
            app.UseOAuthBearerTokens(OAuthOptions);


это аксиос


const getAllVideo = header => {
  let url = basePath2;

  let config = {
    headers: {
      "Content-Type": "application/json",
      header
    },
    method: "GET",
    withCredentials: true,
    crossdomain: true
  };
  return axios(url, config);
};


1 Ответ

0 голосов
/ 25 марта 2019

Пожалуйста, добавьте следующую строку к вызову axios


    headers: {
          "Content-Type": "application/json",
          "Authorization": "Bearer " + bearer_token
    }

...