Asp.net mvc 最小WebAPI2+;OAuth和JWT实现:401始终返回

Asp.net mvc 最小WebAPI2+;OAuth和JWT实现:401始终返回,asp.net-mvc,oauth,asp.net-web-api2,jwt,asp.net-identity,Asp.net Mvc,Oauth,Asp.net Web Api2,Jwt,Asp.net Identity,我试图实现一个简单的WebAPI2项目,用JWT令牌保护我的API函数。由于我对这方面还比较陌生,我主要遵循这些教程作为指导:其代码位于,和 编辑#1:请参见底部:已解决客户端的问题_id=null 当然,在我的实现中,有几个细节发生了变化,随着我的学习,这些变化应该是最小的,我目前的需求也没有那么复杂:我不使用第三方JWT或安全库(如Thinktecture或Jamie Kurtz JwtAuthForWebAPI),但只需坚持使用MS JWT组件,也不需要2FA或外部登录,因为这将是由管理员

我试图实现一个简单的WebAPI2项目,用JWT令牌保护我的API函数。由于我对这方面还比较陌生,我主要遵循这些教程作为指导:其代码位于,和

编辑#1:请参见底部:已解决客户端的问题_id=null

当然,在我的实现中,有几个细节发生了变化,随着我的学习,这些变化应该是最小的,我目前的需求也没有那么复杂:我不使用第三方JWT或安全库(如Thinktecture或Jamie Kurtz JwtAuthForWebAPI),但只需坚持使用MS JWT组件,也不需要2FA或外部登录,因为这将是由管理员注册用户的客户端应用程序使用的公司API

我设法实现了一个返回JWT令牌的API,但是当我用它向任何受保护的API发出请求时(当然,未受保护的API不起作用),请求总是被拒绝,并出现一个未经授权的错误。
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}
响应

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}
如果我检查令牌(at),我会得到JWT负载的JSON:

{
  "unique_name": "Zeus",
  "role": "administrator",
  "iss": "http://localhost:50505",
  "aud": "0d45e9cec83646b6a173847ec9c96f7f",
  "exp": 1429049809,
  "nbf": 1428963409
}
但是,任何具有类似令牌的请求(这里是示例模板中使用的“规范”API
ValuesController
)都是这样的(我省略了正确发出的飞行前
OPTIONS
CORS请求):

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
-派生数据上下文及其实体(
User
访问者
)。
User
实体只是为first和last name添加了几个字符串属性。
受众
实体用于为多个受众提供基础设施;它有一个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
(在我的案例中,底部的提供者不是必需的,但我添加了它作为其他项目的提醒):

这里的第一个问题是,在调试时,我可以看到收到的上下文客户机ID为null。我不确定它应该放在哪里。这就是为什么在这里我会回到默认的观众ID(对于我的测试目的来说足够了,一次只吃一口大象)

这里的另一个关键组件是JWT令牌格式化程序,它负责从票据构建JWT令牌。在我的实现中,我在其构造函数中注入了一个函数来检索EF数据上下文,因为格式化程序需要它来获取访问群体的密钥。所需的访问群体ID来自上述代码设置的元数据属性,用于查找存储中的
访问群体
实体。如果找不到,我会退回到我的
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();
    }
}
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\u Start/Startup.Auth.cs
)在一个单独的文件中:这有两个用于OAuth和JWT的选项包装类。请注意,对于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);
    }
}
在验证的同时,我进行实际的检查,以便从请求的正文中检索
客户机id
,在我的访问群体存储中查找,如果找到,则进行验证。这似乎解决了上面提到的问题,因此现在我在
GrantResourceOwnerCredentials
中获得了一个非空的客户端ID;我还可以检查JWT内容,并在
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."}

我自己实现了一个JWTOAuth身份验证(使用承载令牌)。 我认为你可以让你的代码比你现在拥有的更轻

这是我找到的关于如何使用OAuth+JWT保护Web API的基础知识的最好的文章

我现在没有时间进一步回答你的问题。祝你好运

此外:


我不知道这是否相关,但据我所知,谷歌将在明天4月15日之前让OAuth退出,取而代之的是OAuth2。谢谢,如果我的标题太短,那是我的错,但用“OAuth”我暗示了OAuth2。这是ASPNET Identity 2中使用的内容,请参见例如:谢谢,这些链接看起来很有趣,我会在找到学习时间后立即查看。如果我能找到解决方案,对于我的问题,我会发回这里。无论如何,我也会对具体的答案感兴趣,因为为了学习,我真的很想知道我在上面的示例代码中做错了什么。我还必须添加以下链接:
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);
    }
}
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);
}
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."}