在我的Swagger API中,即使它拿起标题中指定的Api-Key,我也会不断收到此消息,为什么会出现这种情况?任何帮助都会很棒
请求网址
回应机构
{ " 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 "";
}
邮递员回应工作
答案 0 :(得分:0)
在花了好几个小时试图弄清楚它为什么不起作用之后,我发现拼写错误,同时注入了将“bearer”附加到令牌的javascript文件,因此它从未被注入。
我还必须在SwaggerConfig.EnableSwaggerUI中添加ApiKeySupport
.EnableSwaggerUi(c =>
{
c.InjectJavaScript(thisAssembly, "ProjectScavengerAPI.Web.Scripts.Swagger.jwt-auth.js");
c.EnableApiKeySupport("Authorization", "header");
});