使用JWT实现的最小WebAPI2 + OAuth:总是返回401

我正在尝试实现一个简单的WebAPI2项目,以确保我的API函数具有JWT令牌。 由于我对此很新,我主要关注这些教程作为指导:http://bitoftech.net/2015/01/21/asp-net-identity-2-with-asp-net-web-api- 2-accounts-management /在https://github.com/tjoudeh/AspNetIdentity.WebApi上的代码,以及http://odetocode.com/blogs/scott/archive/2015/01/15/using-json-web -tokens与 - 武士刀和-webapi.aspx。

编辑#1:查看底部 :已解决的问题client_id = null。

当然,在我的实现中,有些细节会有所改变,这些细节应该尽可能少,因为我目前的要求并不复杂:我不使用第三方JWT或安全库(如Thinktecture或Jamie Kurtz JwtAuthForWebAPI),但仅仅坚持MS JWT组件,也不需要2FA或外部登录,因为这将是由管理员注册用户的客户端应用程序使用的公司API。

我设法实现了一个返回JWT令牌的API,但是当我向任何受保护的API发出请求(当然,未受保护的API可以工作)时,请求会不断被401-Unauthorized错误拒绝。 api/token端点上的示例请求/响应如下所示:

要求

POST http://localhost:50505/token HTTP/1.1
Host: localhost:50505
Connection: keep-alive
Content-Length: 56
Accept: application/json, text/plain, */*
Origin: http://localhost:50088
User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36
Content-Type: application/x-www-form-urlencoded;charset=UTF-8
Referer: http://localhost:50088/dist/
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.8,it;q=0.6

grant_type=password&username=Zeus&password=ThePasswordHere

回应

HTTP/1.1 200 OK
Cache-Control: no-cache
Pragma: no-cache
Content-Length: 343
Content-Type: application/json;charset=UTF-8
Expires: -1
Server: Microsoft-IIS/8.0
Access-Control-Allow-Origin: http://localhost:50088
Access-Control-Allow-Credentials: true
X-SourceFiles: =?UTF-8?B?QzpcUHJvamVjdHNcNDViXEV4b1xJYW5pdG9yXElhbml0b3IuV2ViQXBpXHRva2Vu?=
X-Powered-By: ASP.NET
Date: Mon, 13 Apr 2015 22:16:50 GMT

{"access_token":"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1bmlxdWVfbmFtZSI6IlpldXMiLCJyb2xlIjoiYWRtaW5pc3RyYXRvciIsImlzcyI6Imh0dHA6Ly9sb2NhbGhvc3Q6NTA1MDUiLCJhdWQiOiIwZDQ1ZTljZWM4MzY0NmI2YTE3Mzg0N2VjOWM5NmY3ZiIsImV4cCI6MTQyOTA0OTgwOSwibmJmIjoxNDI4OTYzNDA5fQ.-GFvtEfNI7Y8tf6Ln1MpxJc4yORuf2gzksGjRbSMEnU","token_type":"bearer","expires_in":86399}

如果我检查令牌(在http://jwt.io/),我得到JWT有效载荷的JSON:

{
  "unique_name": "Zeus",
  "role": "administrator",
  "iss": "http://localhost:50505",
  "aud": "0d45e9cec83646b6a173847ec9c96f7f",
  "exp": 1429049809,
  "nbf": 1428963409
}

然而,任何具有类似标记的请求(这里是示例模板中使用的'规范'API ValuesController ),像这样(我省略了预检OPTIONS CORS请求,它被正确地发布):

GET http://localhost:50505/api/values HTTP/1.1
Host: localhost:50505
Connection: keep-alive
Accept: application/json, text/plain, */*
Origin: http://localhost:50088
User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36
Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1bmlxdWVfbmFtZSI6IlpldXMiLCJyb2xlIjoiYWRtaW5pc3RyYXRvciIsImlzcyI6Imh0dHA6Ly9sb2NhbGhvc3Q6NTA1MDUiLCJhdWQiOiIwZDQ1ZTljZWM4MzY0NmI2YTE3Mzg0N2VjOWM5NmY3ZiIsImV4cCI6MTQyOTA4MzAzOCwibmJmIjoxNDI4OTk2NjM4fQ.i5ik6ggSzoV2Nz-1_Od5fZVKxBpgOmEJcQN00YsG_DU
Referer: http://localhost:50088/dist/
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en-US,en;q=0.8,it;q=0.6

401失败:

HTTP/1.1 401 Unauthorized
Cache-Control: no-cache
Pragma: no-cache
Content-Type: application/json; charset=utf-8
Expires: -1
Server: Microsoft-IIS/8.0
Access-Control-Allow-Origin: http://localhost:50088
Access-Control-Allow-Credentials: true
X-AspNet-Version: 4.0.30319
X-SourceFiles: =?UTF-8?B?QzpcUHJvamVjdHNcNDViXEV4b1xJYW5pdG9yXElhbml0b3IuV2ViQXBpXGFwaVx2YWx1ZXM=?=
X-Powered-By: ASP.NET
Date: Tue, 14 Apr 2015 07:30:53 GMT
Content-Length: 61

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

鉴于这对于像我这样的安全新手来说是一个相当复杂的话题,下面我将描述我的解决方案的基本方面,以便专家可以指望我找到解决方案,并且新手可以找到一些最新的指导。

数据层

我使用EntityFramework在一个单独的DLL项目中创建了我的数据层,并包含了我的IdentityDbContext派生的数据上下文及其实体( UserAudience )。 User实体只是为名字和姓氏添加一些字符串属性。 Audience实体用于为多个受众提供基础设施; 它有一个ID(一个由字符串属性表示的GUID),一个名称(仅用于提供人性化的标签)和一个base-64编码的共享密钥。

通过使用迁移,我创建了数据库并将其与管理员用户和测试受众一起植入。

Web API

1.启动模板

我创建了一个空的WebApp项目,包括WebAPI库,并且没有用户身份验证,因为缺省的身份验证模板太臃肿,因为我的用途有限,而且学习者的移动部件太多。 我手动添加了所需的NuGet软件包,最终是:

EntityFramework
Microsoft.AspNet.Identity.EntityFramework
Microsoft.AspNet.Cors
Microsoft.AspNet.Identity.Owin
Microsoft.AspNet.WebApi
Microsoft.AspNet.WebApi.Client
Microsoft.AspNet.WebApi.Core
Microsoft.AspNet.WebApi.Owin
Microsoft.AspNet.WebApi.WebHost
Microsoft.Owin
Microsoft.Owin.Cors
Microsoft.Owin.Host.SystemWeb
Microsoft.Owin.Security
Microsoft.Owin.Security.Cookies
Microsoft.Owin.Security.Jwt
Microsoft.Owin.Security.OAuth
Newtonsoft.Json
Owin
System.IdentityModel.Tokens.Jwt

2.基础设施

至于基础设施,我创建了一个相当标准的ApplicationUserManager (在我的情况下底层的提供者不是必需的,但是我添加了这个来提醒其他项目):

public class ApplicationUserManager : UserManager<User>
{
    public ApplicationUserManager(IUserStore<User> store)
        : base(store)
    {
    }

    public static ApplicationUserManager Create(
        IdentityFactoryOptions<ApplicationUserManager> options,
        IOwinContext context)
    {
        var manager = new ApplicationUserManager
            (new UserStore<User>(context.Get<IanitorContext>()));

        manager.UserValidator = new UserValidator<User>(manager)
        {
            AllowOnlyAlphanumericUserNames = false,
            RequireUniqueEmail = true
        };

        manager.PasswordValidator = new PasswordValidator
        {
            RequiredLength = 6,
            RequireNonLetterOrDigit = true,
            RequireDigit = true,
            RequireLowercase = true,
            RequireUppercase = true,
        };

        manager.UserLockoutEnabledByDefault = true;
        manager.DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(5);
        manager.MaxFailedAccessAttemptsBeforeLockout = 5;

        var dataProtectionProvider = options.DataProtectionProvider;
        if (dataProtectionProvider != null)
        {
            // for email confirmation and reset password life time
            manager.UserTokenProvider =
                new DataProtectorTokenProvider<User>(dataProtectionProvider.Create("ASP.NET Identity"))
                {
                    TokenLifespan = TimeSpan.FromHours(6)
                };
        }
        return manager;
    }

3.提供商

此外,我需要一个OAuth令牌提供程序:AFAIK,这里的核心方法是GrantResourceOwnerCredentials ,它会针对我的商店验证接收到的用户名和密码; 当成功时,我创建一个新的ClaimsIdentity ,并使用我想要在我的令牌中发布的经过验证的用户的声明填充它; 然后,我使用这个加上一些元数据属性(这里是受众ID)来创建一个AuthenticationTicket ,并将其传递给context.Validated方法:

public class ApplicationOAuthProvider : OAuthAuthorizationServerProvider
{
    public override Task ValidateClientAuthentication
        (OAuthValidateClientAuthenticationContext context)
    {
        context.Validated();
        return Task.FromResult<object>(null);
    }

    public override async Task GrantResourceOwnerCredentials
        (OAuthGrantResourceOwnerCredentialsContext context)
    {
        // http://www.codeproject.com/Articles/742532/Using-Web-API-Individual-User-Account-plus-CORS-En
        if (!context.OwinContext.Response.Headers.ContainsKey("Access-Control-Allow-Origin"))
            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new []{"*"});

        if ((String.IsNullOrWhiteSpace(context.UserName)) || 
            (String.IsNullOrWhiteSpace(context.Password)))
        {
            context.Rejected();
            return;
        }

        ApplicationUserManager manager = 
            context.OwinContext.GetUserManager<ApplicationUserManager>();
        User user = await manager.FindAsync(context.UserName, context.Password);
        if (user == null)
        {
            context.Rejected();
            return;
        }

        // add selected claims for building the token
        ClaimsIdentity identity = new ClaimsIdentity(context.Options.AuthenticationType);
        identity.AddClaim(new Claim(ClaimTypes.Name, user.UserName));
        foreach (var role in manager.GetRoles(user.Id))
            identity.AddClaim(new Claim(ClaimTypes.Role, role));

        // add audience
        // TODO: why context.ClientId is null? I would expect an audience ID
        AuthenticationProperties props =
            new AuthenticationProperties(new Dictionary<string, string>
            {
                {
                    ApplicationJwtFormat.AUDIENCE_PROPKEY,
                    context.ClientId ?? ConfigurationManager.AppSettings["audienceId"]
                }
            });

        DateTime now = DateTime.UtcNow;
        props.IssuedUtc = now;
        props.ExpiresUtc = now.AddMinutes(context.Options.AccessTokenExpireTimeSpan.TotalMinutes);

        AuthenticationTicket ticket = new AuthenticationTicket(identity, props);
        context.Validated(ticket);
    }
}

这里的第一个问题是,在调试时我可以看到接收到的上下文客户端ID为空。 我不知道应该在哪里设置。 这就是为什么我在这里回落到默认的观众ID(足够用于测试目的,每次只吃一口大象)。

此处的另一个关键组件是JWT令牌格式器,它负责从故障单构建JWT令牌。 在我的实现中,我在构造函数中注入一个函数来检索我的EF数据上下文,格式化程序需要它来获取观众的密钥。 所需的受众ID来自上述代码设置的元数据属性,并用于查找Audience实体的商店。 如果没有找到,我回退到我的Web.config定义的默认观众(这是我使用的测试客户端应用程序)。 一旦我拥有了受众密钥,我就可以为该令牌创建签名凭据,并将其与来自上下文的数据一起用于构建我的JWT。

public class ApplicationJwtFormat : ISecureDataFormat<AuthenticationTicket>
{
    private readonly Func<IanitorContext> _contextGetter;
    private string _sIssuer;
    public const string AUDIENCE_PROPKEY = "audience";

    private const string SIGNATURE_ALGORITHM = "http://www.w3.org/2001/04/xmldsig-more#hmac-sha256";
    private const string DIGEST_ALGORITHM = "http://www.w3.org/2001/04/xmlenc#sha256";

    public string Issuer
    {
        get { return _sIssuer; }
        set
        {
            if (value == null) throw new ArgumentNullException("value");
            _sIssuer = value;
        }
    }

    public ApplicationJwtFormat(Func<IanitorContext> contextGetter)
    {
        if (contextGetter == null) throw new ArgumentNullException("contextGetter");

        _contextGetter = contextGetter;
        Issuer = "http://localhost:50505";
    }

    public string Protect(AuthenticationTicket data)
    {
        if (data == null) throw new ArgumentNullException("data");

        // get the audience ID from the ticket properties (as set by ApplicationOAuthProvider
        // GrantResourceOwnerCredentials from its OAuth client ID)
        string sAudienceId = data.Properties.Dictionary.ContainsKey(AUDIENCE_PROPKEY)
            ? data.Properties.Dictionary[AUDIENCE_PROPKEY]
            : null;

        // get audience data
        Audience audience;
        using (IanitorContext db = _contextGetter())
        {
            audience = db.Audiences.FirstOrDefault(a => a.Id == sAudienceId) ??
                new Audience
                {
                    Id = ConfigurationManager.AppSettings["audienceId"],
                    Name = ConfigurationManager.AppSettings["audienceName"],
                    Base64Secret = ConfigurationManager.AppSettings["audienceSecret"]
                };
        }

        byte[] key = TextEncodings.Base64Url.Decode(audience.Base64Secret);

        DateTimeOffset? issued = data.Properties.IssuedUtc ?? 
            new DateTimeOffset(DateTime.UtcNow);
        DateTimeOffset? expires = data.Properties.ExpiresUtc;

        SigningCredentials credentials = new SigningCredentials(
            new InMemorySymmetricSecurityKey(key),
            SIGNATURE_ALGORITHM,
            DIGEST_ALGORITHM);

        JwtSecurityToken token = new JwtSecurityToken(_sIssuer,
            audience.Id,
            data.Identity.Claims,
            issued.Value.UtcDateTime,
            expires.Value.UtcDateTime,
            credentials);

        return new JwtSecurityTokenHandler().WriteToken(token);
    }

    public AuthenticationTicket Unprotect(string protectedText)
    {
        throw new NotImplementedException();
    }
}

4.启动

最后,将启动代码粘合在一起: Application_StartGlobal.asax代码只是一个方法调用: GlobalConfiguration.Configure(WebApiConfig.Register); ,它调用了典型的WebAPI路由设置代码,并添加了一些仅用于承载认证并返回骆驼式JSON的代码:

    public static void Register(HttpConfiguration config)
    {
        // Configure Web API to use only bearer token authentication.
        config.SuppressDefaultHostAuthentication();

        // Use camel case for JSON data
        config.Formatters.JsonFormatter.SerializerSettings.ContractResolver =
            new CamelCasePropertyNamesContractResolver();

        // Web API routes
        config.MapHttpAttributeRoutes();

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

OWIN启动配置OWIN中间件:

public partial class Startup
{
    public void Configuration(IAppBuilder app)
    {
        HttpConfiguration config = new HttpConfiguration();

        app.UseCors(CorsOptions.AllowAll);
        app.UseWebApi(config);

        ConfigureAuth(app);
    }
}

基本配置在ConfigureAuth方法中,按照模板约定( App_Start/Startup.Auth.cs )以分开的文件形式存在:这有OAuth和JWT的几个选项包装类。 请注意,对于智威汤逊,我通过从商店中获取它们来向配置中添加多个受众群体。 在ConfigureAuth我配置OWIN的依赖关系,以便它可以获取所需对象(EF数据上下文以及用户和角色管理器)的实例,然后使用指定选项设置OAuth和JWT。

public partial class Startup
{
    public static OAuthAuthorizationServerOptions OAuthOptions { get; private set; }
    public static JwtBearerAuthenticationOptions JwtOptions { get; private set; }

    static Startup()
    {
        string sIssuer = ConfigurationManager.AppSettings["issuer"];

        OAuthOptions = new OAuthAuthorizationServerOptions
        {
            TokenEndpointPath = new PathString("/token"),
            AuthorizeEndpointPath = new PathString("/accounts/authorize"),  // not used
            Provider = new ApplicationOAuthProvider(),
            AccessTokenExpireTimeSpan = TimeSpan.FromHours(24),
            AccessTokenFormat = new ApplicationJwtFormat(IanitorContext.Create)
            {
                Issuer = sIssuer
            },
            AllowInsecureHttp = true   // do not allow in production
        };

        List<string> aAudienceIds = new List<string>();
        List<IIssuerSecurityTokenProvider> aProviders = 
            new List<IIssuerSecurityTokenProvider>();

        using (var context = IanitorContext.Create())
        {
            foreach (Audience audience in context.Audiences)
            {
                aAudienceIds.Add(audience.Id);
                aProviders.Add(new SymmetricKeyIssuerSecurityTokenProvider
                    (sIssuer, TextEncodings.Base64Url.Decode(audience.Base64Secret)));
            }
        }

        JwtOptions = new JwtBearerAuthenticationOptions
        {
            AllowedAudiences = aAudienceIds.ToArray(),
            IssuerSecurityTokenProviders = aProviders.ToArray()
        };
    }

    public void ConfigureAuth(IAppBuilder app)
    {
        app.CreatePerOwinContext(IanitorContext.Create);
        app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
        app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create);

        app.UseOAuthAuthorizationServer(OAuthOptions);
        app.UseJwtBearerAuthentication(JwtOptions);
    }
}

编辑#1 - client_id

在看几个例子的时候,我在ApplicationOAuthProvider结束了这段代码:

public override Task ValidateClientAuthentication
    (OAuthValidateClientAuthenticationContext context)
{
    // http://bitoftech.net/2014/10/27/json-web-token-asp-net-web-api-2-jwt-owin-authorization-server/

    string sClientId;
    string sClientSecret;

    if (!context.TryGetBasicCredentials(out sClientId, out sClientSecret))
        context.TryGetFormCredentials(out sClientId, out sClientSecret);

    if (context.ClientId == null)
    {
        context.SetError("invalid_clientId", "client_Id is not set");
        return Task.FromResult<object>(null);
    }

    IanitorContext db = context.OwinContext.Get<IanitorContext>();
    Audience audience = db.Audiences.FirstOrDefault(a => a.Id == context.ClientId);

    if (audience == null)
    {
        context.SetError("invalid_clientId", 
            String.Format(CultureInfo.InvariantCulture, "Invalid client_id '{0}'", context.ClientId));
        return Task.FromResult<object>(null);
    }

    context.Validated();
    return Task.FromResult<object>(null);
}

在进行验证时,我进行实际检查,以便从请求的正文中检索client_id ,在我的受众群体商店中查找,并在发现后进行验证。 这似乎解决了上面提到的问题,所以现在我在GrantResourceOwnerCredentials获得非空的客户端ID; 我还可以检查智威汤逊的内容并查找所需的aud ID。 然而,我在收到令牌的同时通过任何请求的时候总是收到401,例如:

HTTP/1.1 401 Unauthorized
Cache-Control: no-cache
Pragma: no-cache
Content-Type: application/json; charset=utf-8
Expires: -1
Server: Microsoft-IIS/8.0
Access-Control-Allow-Origin: http://localhost:50088
Access-Control-Allow-Credentials: true
X-AspNet-Version: 4.0.30319
X-SourceFiles: =?UTF-8?B?RDpcUHJvamVjdHNcNDViXEV4b1xJYW5pdG9yXElhbml0b3IuV2ViQXBpXGFwaVx2YWx1ZXM=?=
X-Powered-By: ASP.NET
Date: Wed, 22 Apr 2015 18:05:47 GMT
Content-Length: 61

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

我实施了自己的JWT OAuth身份验证(带有无标记令牌)。 我认为你绝对可以让你的代码更轻,就是你现在拥有的。

以下是我发现的关于如何使用OAuth + JWT保护Web API的基础知识的最佳文章。

我现在没有时间进一步解决你的问题。 祝你好运!

http://chimera.labs.oreilly.com/books/1234000001708/ch16.html#_resource_server_and_authorization_server

另外:

http://www.asp.net/web-api/overview/security/authentication-and-authorization-in-aspnet-web-api

链接地址: http://www.djcxy.com/p/84363.html

上一篇: Minimal WebAPI2 + OAuth with JWT implementation: 401 always returned

下一篇: D3 histogram, number of occurrences of date from time stamp