Не удается получить доступ к ресурсу сервера, отправлен заголовок авторизации?

#asp.net #.net #asp.net-web-api2 #axios

#asp.net #.net #asp.net-web-api2 #axios

Вопрос:

Я не могу получить доступ к защищенным ресурсам через web api, например [Авторизовать]

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

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

имеется в виду обновленный web.config, запуск, WebApiConfig,

Я занимаюсь этим уже некоторое время. Я делаю вызов и запускаю сетевой отладчик Chrome

{«сообщение»: «Авторизация была отклонена для этого запроса».}

 [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 }
            );
        }
    }
}

  

это запуск startAuth

 
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);


  

это вызов axios

 
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:

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

 заголовки: {
 "Content-Type": "application / json", 
 "Авторизация": "Предъявитель"   bearer_token 
 }

Комментарии:

1. Но как бы я передал токен в заголовок, нужно ли мне перехватывать его в реквизитах и отправлять?