加入收藏 | 设为首页 | 会员中心 | 我要投稿 安卓应用网 (https://www.0791zz.com/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc – 使用JWT实现的最小WebAPI2 OAuth:401始终返回

发布时间:2020-05-24 15:11:08 所属栏目:asp.Net 来源:互联网
导读:我正在尝试使用JWT令牌实现一个简单的WebAPI2项目来保护我的API函数.由于我对此很陌生,我主要关注这些教程作为指导: http://bitoftech.net/2015/01/21/asp-net-identity-2-with-asp-net-web-api-2-accounts-management/,其代码分别为 https://github.com/tjo

我正在尝试使用JWT令牌实现一个简单的WebAPI2项目来保护我的API函数.由于我对此很陌生,我主要关注这些教程作为指导: 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-with-katana-and-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,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,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派生的数据上下文及其实体(用户和受众). User实体只是为名字和姓氏添加了几个字符串属性.受众实体用于为多个受众提供基础设施;它有一个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并用我想要在我的令牌中发布的经过身份验证的用户声明填充它;然后,我使用此加上一些元数据属性(此处为受众标识)来创建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(足够我的测试目的,一次吃一口大象).

(编辑:安卓应用网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读