ASP.NET JSON Web令牌“401 Unauthorized”

前端之家收集整理的这篇文章主要介绍了ASP.NET JSON Web令牌“401 Unauthorized”前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在使用分离的资源和身份验证服务器.
当我成功获得 JSON Web Token时,我使用jwt.io进行检查,所有内容都可以使用令牌格式,这是秘密.

请求具有授权标头:

  1. Authorization: Bearer TOKEN_HERE

响应总是“401 Unauthorized”:

  1. {
  2. "message": "Authorization has been denied for this request."
  3. }

这是我的资源服务器的Startup.cs

  1. using Microsoft.Owin;
  2. using Microsoft.Owin.Cors;
  3. using Microsoft.Owin.Security;
  4. using Microsoft.Owin.Security.Jwt;
  5. using Newtonsoft.Json.Serialization;
  6. using Owin;
  7. using System.Web.Http;
  8. using Test.Database;
  9. using Test.Infrastructure;
  10. using Microsoft.WindowsAzure.ServiceRuntime;
  11.  
  12. [assembly: OwinStartup(typeof(Test.API.Startup))]
  13. namespace Custodesk.API
  14. {
  15. public class Startup
  16. {
  17. public void Configuration(IAppBuilder app)
  18. {
  19. app.CreatePerOwinContext(() =>
  20. ApplicationDbContext.Create(RoleEnvironment.GetConfigurationSettingValue("sqlConnectionString")));
  21. app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
  22.  
  23. GlobalConfiguration.Configuration.SuppressDefaultHostAuthentication();
  24.  
  25. ConfigureOAuthTokenConsumption(app);
  26.  
  27. GlobalConfiguration.Configure(config =>
  28. {
  29. //global filters
  30. config.Filters.Add(new AuthorizeAttribute());
  31.  
  32. // Web API routes
  33. config.MapHttpAttributeRoutes();
  34. config.Routes.MapHttpRoute(
  35. name: "DefaultApi",routeTemplate: "{controller}/{action}/{id}",defaults: new { id = RouteParameter.Optional }
  36. );
  37.  
  38. config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
  39. });
  40.  
  41. app.UseCors(CorsOptions.AllowAll);
  42.  
  43. app.UseWebApi(GlobalConfiguration.Configuration);
  44. }
  45.  
  46. private void ConfigureOAuthTokenConsumption(IAppBuilder app)
  47. {
  48. var issuer = "http://localhost";
  49. var audience = "Universal_application";
  50. var secret = Helper.GetHash("helper_class_to_get_the_same_hash_as_authentication_server");
  51.  
  52. // Api controllers with an [Authorize] attribute will be validated with JWT
  53. app.UseJwtBearerAuthentication(
  54. new JwtBearerAuthenticationOptions
  55. {
  56. AuthenticationMode = AuthenticationMode.Active,AllowedAudiences = new[] { audience },IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[]
  57. {
  58. new SymmetricKeyIssuerSecurityTokenProvider(issuer,secret)
  59. }
  60. });
  61.  
  62. }
  63. }
  64. }

以下是令牌解密的示例:

  1. {
  2. "typ": "JWT","alg": "HS256"
  3. }
  4. {
  5. "nameid": "b22a825e-60ce-45ed-b2cb-b2ee46a47936","unique_name": "begunini","role": [
  6. "Owner","Admin","ManagerViewer"
  7. ],"iss": "http://localhost","aud": "Universal_application","exp": 1454876502,"nbf": 1454876202
  8. }

我已经检查了秘密,双方都是相同的(身份验证和资源服务器).
观众比赛,发行人也.
已经尝试将System.IdentityModel.Tokens.Jwt降级到版本3.0.2但没有运气

我猜配置顺序有一些问题,但没有任何帮助.

有任何想法吗 ?

解决方法

TL; DR:您是否尝试删除GlobalConfiguration.Configuration.SuppressDefaultHostAuthentication()?

使用此方法时,Web API将删除由Web主机(在您的情况下由JWT承载中间件)注册的主机或中间件创建并添加到OWIN上下文的用户主体.

方法旨在与HostAuthenticationFilter或HostAuthenticationAttribute一起使用,该方法直接调用与指定的身份验证类型对应的身份验证中间件,并在OWIN上下文中保留生成用户主体.

由于您在没有HostAuthenticationAttribute的情况下使用SuppressDefaultHostAuthentication,因此Web API始终会看到未经身份验证的请求,这就是AuthorizeAttribute拒绝它们的原因.

猜你在找的asp.Net相关文章