本文介绍了验证通过AspNet.Security.OpenIdConnect.Server颁发令牌(ASP.NET vNext)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我使用Visual Studio 2015年企业和ASP.NET vNext Beta8建立,这两个问题,消耗JWT令牌的端点。我最初接触这个通过生成自己的标记,如所描述here.
后来一个有用的article通过@Pinpoint透露,AspNet.Security.OpenIdConnect.Server(又名OIDC)可以被配置为颁发和消费令牌我。

I am using Visual Studio 2015 Enterprise and ASP.NET vNext Beta8 to build an endpoint that both issues and consumes JWT tokens. I Originally approached this by generating the tokens myself, as described here.Later a helpful article by @Pinpoint revealed that AspNet.Security.OpenIdConnect.Server (a.k.a. OIDC) can be configured to issue and consume the tokens for me.

于是我跟着这些指示,站起来一个端点,并通过的我收到回一个合法的标记:

So I followed those instructions, stood up an endpoint, and by submitting an x-www-form-urlencoded post from postman I receive back a legit token:

{
  "token_type": "bearer",
  "access_token": "eyJ0eXAiO....",
  "expires_in": "3599"
}

这是伟大的,但也是我卡住。现在,我怎么注释的控制器操作,因此需要这个承载令牌?

This is great but also where I get stuck. Now, how do I annotate a controller action so that it demands this bearer token?

我以为所有我必须做的是装饰我的控制器方法与
[授权(旗手),增加一个认证方案:

I thought all I would have to do is decorate my controller method with the[Authorize("Bearer")], add an authentication scheme:

        services.AddAuthorization
        (
            options =>
            {
                options.AddPolicy
                (
                    JwtBearerDefaults.AuthenticationScheme,
                    builder =>
                    {
                        builder.
                        AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme).
                        RequireAuthenticatedUser().
                        Build();
                    }
                );
            }
        );

然后叫我用控制器动作授权承载eyJ0eXAiO ......头,因为我曾在我的previous例子完成。可悲的是,这一切做法似乎虽然做的是产生一个异常:

And then call my controller action with the "Authorization bearer eyJ0eXAiO...." header as I had done in my previous example. Sadly, all this approach seems to do though is generate an exception:

在处理请求时发生未处理的异常。

SocketException:无连接可以作出,因为目标机器积极地拒绝它127.0.0.1:50000

SocketException: No connection could be made because the target machine actively refused it 127.0.0.1:50000

引发WebException:无法连接到远程服务器

WebException: Unable to connect to the remote server

Htt的prequestException:发送请求时发生错误

HttpRequestException: An error occurred while sending the request.

IOException异常:IDX10804:无法检索文件:。
  Microsoft.IdentityModel.Logging.LogHelper.Throw(字符串消息,类型exceptionType,EventLevel日志级别,异常的InnerException)

IOException: IDX10804: Unable to retrieve document from: 'http://localhost:50000/.well-known/openid-configuration'. Microsoft.IdentityModel.Logging.LogHelper.Throw(String message, Type exceptionType, EventLevel logLevel, Exception innerException)

出现InvalidOperationException:IDX10803:无法从配置:'。内部异常:IDX10804:无法检索文件:。

InvalidOperationException: IDX10803: Unable to obtain configuration from: 'http://localhost:50000/.well-known/openid-configuration'. Inner Exception: 'IDX10804: Unable to retrieve document from: 'http://localhost:50000/.well-known/openid-configuration'.'.



考虑以下的步骤重现(但请不要认为这是值得的生产code):


Consider the following steps to reproduce (but please don't consider this production worthy code):


    描述
  • 应用ASP.NET Beta8工具这里

打开Visual Studio 2015年企业和创建新的Web API ASP.NET 5 preVIEW模板项目

Open Visual Studio Enterprise 2015 and create a new Web API ASP.NET 5 Preview Template project

更改project.json

Change project.json

{

  根目录:wwwroot文件,

  版本:1.0.0- *,



  依赖:{

    Microsoft.AspNet.IISPlatformHandler:1.0.0-beta8,

    Microsoft.AspNet.Mvc:6.0.0-beta8,

    Microsoft.AspNet.Server.Kestrel:1.0.0-beta8,

    Microsoft.AspNet.Authentication.JwtBearer:1.0.0-beta8,

    AspNet.Security.OpenIdConnect.Server:1.0.0-β3,

    Microsoft.AspNet.Authentication.OpenIdConnect:1.0.0-beta8,

    Microsoft.Framework.ConfigurationModel.Json:1.0.0-BETA4,

    Microsoft.AspNet.Diagnostics:1.0.0-beta8

  },



  命令:{

    网络:Microsoft.AspNet.Server.Kestrel

  },



  框架:{

    dnx451:{}

  },



  排除:[

    wwwroot文件,

    node_modules

  ],

  publishExclude:[

    。用户,

    
.vspscc

  ]

}

{
"webroot": "wwwroot",
"version": "1.0.0-*",

"dependencies": {
"Microsoft.AspNet.IISPlatformHandler": "1.0.0-beta8",
"Microsoft.AspNet.Mvc": "6.0.0-beta8",
"Microsoft.AspNet.Server.Kestrel": "1.0.0-beta8",
"Microsoft.AspNet.Authentication.JwtBearer": "1.0.0-beta8",
"AspNet.Security.OpenIdConnect.Server": "1.0.0-beta3",
"Microsoft.AspNet.Authentication.OpenIdConnect": "1.0.0-beta8",
"Microsoft.Framework.ConfigurationModel.Json": "1.0.0-beta4",
"Microsoft.AspNet.Diagnostics": "1.0.0-beta8"
},

"commands": {
"web": "Microsoft.AspNet.Server.Kestrel"
},

"frameworks": {
"dnx451": { }
},

"exclude": [
"wwwroot",
"node_modules"
],
"publishExclude": [
".user",
"
.vspscc"
]
}

更改Startup.cs如下(这是@的Pinpoint的原创文章的礼貌,我已删除留言,并添加了AddAuthorization剪断):

Change Startup.cs as follows (this is courtesy of @Pinpoint's original article; I have removed comments and added the AddAuthorization snip):

public class Startup
{
    public Startup(IHostingEnvironment env)
    {
    }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddAuthorization
        (
            options =>
            {
                options.AddPolicy
                (
                    JwtBearerDefaults.AuthenticationScheme,
                    builder =>
                    {
                        builder.
                        AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme).
                        RequireAuthenticatedUser().
                        Build();
                    }
                );
            }
        );
        services.AddAuthentication();
        services.AddCaching();
        services.AddMvc();
        services.AddOptions();
    }

    // Configure is called after ConfigureServices is called.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, IOptions<AppSettings> appSettings)
    {
        app.UseDeveloperExceptionPage();

        // Add a new middleware validating access tokens issued by the OIDC server.
        app.UseJwtBearerAuthentication(options => {
            options.AutomaticAuthentication = true;
            options.Audience = "http://localhost:50000/";
            options.Authority = "http://localhost:50000/";
            options.ConfigurationManager = new ConfigurationManager<OpenIdConnectConfiguration>
            (
                metadataAddress : options.Authority + ".well-known/openid-configuration",
                configRetriever : new OpenIdConnectConfigurationRetriever(),
                docRetriever    : new HttpDocumentRetriever { RequireHttps = false }
            );
        });

        // Add a new middleware issuing tokens.
        app.UseOpenIdConnectServer
        (
            configuration =>
            {
                configuration.Options.TokenEndpointPath= "/authorization/v1";
                configuration.Options.AllowInsecureHttp = true;
                configuration.Provider = new OpenIdConnectServerProvider {

                    OnValidateClientAuthentication = context =>
                    {
                        context.Skipped();
                        return Task.FromResult<object>(null);
                    },

                    OnGrantResourceOwnerCredentials = context =>
                    {
                        var identity = new ClaimsIdentity(OpenIdConnectDefaults.AuthenticationScheme);
                        identity.AddClaim( new Claim(ClaimTypes.NameIdentifier, "todo")  );
                        identity.AddClaim( new Claim("urn:customclaim", "value", "token id_token"));
                        context.Validated(new ClaimsPrincipal(identity));
                        return Task.FromResult<object>(null);
                    }
                };
            }
        );

        app.UseMvc();
    }
}


  • 更改wizarded Values​​Controller.cs指定的授权属性:

  • [Route("api/[controller]")]
    public class ValuesController : Controller
    {
        // GET: api/values
        [Authorize("Bearer")]
        [HttpGet]
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }
    }
    


    • 运行该项目,并使用获得的令牌。为了获得令牌使用X WWW的形式urlen codeD POST与密码grant_type,用户名任何事情,密码任何东西,资源的API端点的地址。我的例如特定的URL为

      • Run the project, and acquire a token using postman. To acquire a token use x-www-form-urlencoded POST with "grant_type" of "password", "username" anything, "password" anything and "resource" the address of the API endpoint. My particular URL for example is http://localhost:37734/authorization/v1.

        中的Base64复制EN codeD令牌,然后使用该令牌调用使用的。要使用该令牌使与头部的Content-Type应用/ JSON和授权承载eyJ0eXAiO ....(令牌)的GET。我的特定URL是

        Copy the Base64 encoded token, then use the token to call the wizarded values controller using postman. To use the token make a GET with the headers Content-Type application/json and Authorization bearer eyJ0eXAiO....(your token). My particular URL is http://localhost:37734/api/values.

        观察例外提到previously。

        Observe the exception mentioned previously.

        如果在[授权(旗手)的做法,我想上面是错误的路要走,我会很AP preciative如果有人可以帮助我了解如何摄取JWT令牌使用的最佳实践OIDC。

        If the [Authorize("Bearer")] approach I'm trying above is the wrong way to go I would be very appreciative if someone could help me understand best practices for how to ingest the JWT token using OIDC.

        感谢您。

        推荐答案

        options.Authority 对应于发行人的地址(即你的OIDC服务器的地址)。

        options.Authority corresponds to the issuer address (i.e the address of your OIDC server).

        的http://本地主机:50000 / 似乎并不为你使用的是正确的的http://本地主机:37734 / 在你的问题后。尽量固定网址,并给它的另一个尝试。

        http://localhost:50000/ doesn't seem to be correct as you're using http://localhost:37734/ later in your question. Try fixing the URL and give it another try.

        这篇关于验证通过AspNet.Security.OpenIdConnect.Server颁发令牌(ASP.NET vNext)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

        1403页,肝出来的..

09-06 15:41