简体   繁体   English

挥舞着“此请求的授权已被拒绝”消息

[英]Swagger “Authorization has been denied for this request” message

In my Swagger API I am getting this message constantly even when it picks up the Api-Key specified in the header,Why is this occuring? 在我的Swagger API中,即使它选择了标头中指定的Api-Key,我也不断收到此消息,这是为什么呢? any help would be great 任何帮助都会很棒

Request URL 要求网址

https://localhost:44338/api/Accounts/CreateRole?api_key=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1bmlxdWVfbmFtZSI6ImRhdGFseXR5eCIsInJvbGUiOiJTeXN0ZW1BZG1pbmlzdHJhdG9yIiwiaXNzIjoiRnJhbmtIaXJ0aCIsImF1ZCI6IkNsaWVudEFjY2VzcyIsImV4cCI6MTUyODMyMDI4NX0.w6eYfa4YSyJEwqVovdBUhQJkuHDf1IvG-YZk1rf6SVU HTTPS://本地主机:44338 / API /账户/ CREATEROLE API_KEY = eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1bmlxdWVfbmFtZSI6ImRhdGFseXR5eCIsInJvbGUiOiJTeXN0ZW1BZG1pbmlzdHJhdG9yIiwiaXNzIjoiRnJhbmtIaXJ0aCIsImF1ZCI6IkNsaWVudEFjY2VzcyIsImV4cCI6MTUyODMyMDI4NX0.w6eYfa4YSyJEwqVovdBUhQJkuHDf1IvG-YZk1rf6SVU

Response Body 反应体

{ "message": "Authorization has been denied for this request." {“ message”:“此请求已被拒绝授权。” } }

Startup.cs 启动文件

[assembly: OwinStartup(typeof(ProjectScavengerAPI.Web.Startup))]

namespace ProjectScavengerAPI.Web
{
public partial class Startup
{
    public void Configuration(IAppBuilder app)
    {
        app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
        this.ConfigureOAuthTokenConsumption(app);
        HttpConfiguration config = new HttpConfiguration();
        config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
        config.Formatters.JsonFormatter.UseDataContractJsonSerializer = false;
        config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;

        WebApiConfig.Register(config);
        app.UseWebApi(config);
    }
}
}

WebApiConfig WebApiConfig

        public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services
        config.SuppressDefaultHostAuthentication();
        config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
        // Web API routes
        config.MapHttpAttributeRoutes();

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

Startup_Auth Startup_Auth

    public partial class Startup
{
    // For more information on configuring authentication, please visit https://go.microsoft.com/fwlink/?LinkId=301864
    public static OAuthAuthorizationServerOptions OAuthOptions { get; private set; }

    public static string PublicClientId { get; private set; }

    private void ConfigureOAuthTokenConsumption(IAppBuilder app)
    {
        var issuer = ConfigurationManager.AppSettings["Issuer"];
        var audienceId = ConfigurationManager.AppSettings["AudienceId"];
        var clientAudienceId = ConfigurationManager.AppSettings["ClientAudienceId"];
        var audienceSecret = ConfigurationManager.AppSettings["AudienceSecret"];

        // Api controllers with an [Authorize] attribute will be validated with JWT
        app.UseJwtBearerAuthentication(new JwtBearerAuthenticationOptions
        {
            AuthenticationMode = AuthenticationMode.Active,
            AllowedAudiences = new[] { audienceId, clientAudienceId },
            IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[]
            {
                new SymmetricKeyIssuerSecurityTokenProvider(issuer, audienceSecret)
            }
        });
    }
}

CreateRole Function (SystemAdministrator already exists) CreateRole函数(SystemAdministrator已存在)

    [HttpPost]
    [Authorize(Roles = "SystemAdministrator")]
    [Route("CreateRole")]
    public IHttpActionResult CreateRole(string roleName)
    {
        return TryAction(() => _CreateRole(roleName));
    }
    private object _CreateRole(string roleName)
    {
        try
        {
            if (!Roles.RoleExists(roleName))
            {
                Roles.CreateRole(roleName);
            }
            return $"{roleName} created";
        }
        catch
        {
            if (Roles.RoleExists(roleName))
            {
                return $"{roleName} exists";
            }
        }

        return "";
    }

Postman Response working 邮递员响应工作

邮递员响应按预期与生成的令牌一起工作

After spending hours trying to figure out why it wasn't working it turns out I had a spelling error while injecting the javascript file that appends "bearer" to the token so it was never being injected. 花了几个小时试图弄清楚为什么它不起作用后,事实证明我在注入将“ bearer”附加到令牌的javascript文件时遇到了拼写错误,因此从未被注入。

I also had to add ApiKeySupport in the SwaggerConfig.EnableSwaggerUI 我还必须在SwaggerConfig.EnableSwaggerUI中添加ApiKeySupport

 .EnableSwaggerUi(c =>
                {

                    c.InjectJavaScript(thisAssembly, "ProjectScavengerAPI.Web.Scripts.Swagger.jwt-auth.js");
                    c.EnableApiKeySupport("Authorization", "header");
                                        });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM