Swagger"此请求的授权被拒绝"信息

时间:2018-06-06 11:32:09

标签: c# asp.net-web-api swagger swashbuckle

在我的Swagger API中,即使它拿起标题中指定的Api-Key,我也会不断收到此消息,为什么会出现这种情况?任何帮助都会很棒

请求网址

  

https://localhost:44338/api/Accounts/CreateRole?api_key=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1bmlxdWVfbmFtZSI6ImRhdGFseXR5eCIsInJvbGUiOiJTeXN0ZW1BZG1pbmlzdHJhdG9yIiwiaXNzIjoiRnJhbmtIaXJ0aCIsImF1ZCI6IkNsaWVudEFjY2VzcyIsImV4cCI6MTUyODMyMDI4NX0.w6eYfa4YSyJEwqVovdBUhQJkuHDf1IvG-YZk1rf6SVU

回应机构

  

{     " 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

        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

    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功能(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 as intended with generated token

1 个答案:

答案 0 :(得分:0)

在花了好几个小时试图弄清楚它为什么不起作用之后,我发现拼写错误,同时注入了将“bearer”附加到令牌的javascript文件,因此它从未被注入。

我还必须在SwaggerConfig.EnableSwaggerUI中添加ApiKeySupport

 .EnableSwaggerUi(c =>
                {

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