42v*_*ons 6 asp.net jwt openid-connect aspnet-contrib
我正在使用Visual Studio 2015 Enterprise和ASP.NET vNext Beta8构建一个既发布又使用JWT令牌的端点.我最初由生成令牌自己走近这个,描述在这里.后来@Pinpoint的一篇有用的文章显示,AspNet.Security.OpenIdConnect.Server(又名OIDC)可以配置为我发布和使用令牌.
所以我按照这些说明,站起来,通过从邮递员提交x-www-form-urlencoded帖子,我收到了一个合法的令牌:
{
"token_type": "bearer",
"access_token": "eyJ0eXAiO....",
"expires_in": "3599"
}
Run Code Online (Sandbox Code Playgroud)
这很棒,但也是我卡住的地方.现在,如何注释控制器操作以便它需要此持有者令牌?
我认为我所要做的就是用[Authorize("Bearer")]装饰我的控制器方法,添加一个认证方案:
services.AddAuthorization
(
options =>
{
options.AddPolicy
(
JwtBearerDefaults.AuthenticationScheme,
builder =>
{
builder.
AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme).
RequireAuthenticatedUser().
Build();
}
);
}
);
Run Code Online (Sandbox Code Playgroud)
然后像我在前面的例子中所做的那样用"授权持有者eyJ0eXAiO ...."标题调用我的控制器动作.可悲的是,所有这些方法似乎都会产生异常:
处理请求时发生未处理的异常.
SocketException:无法建立连接,因为目标计算机主动拒绝它127.0.0.1:50000
WebException:无法连接到远程服务器
HttpRequestException:发送请求时发生错误.
IOException:IDX10804:无法从以下位置检索文档:' http:// localhost:50000/.well-known/openid-configuration '.Microsoft.IdentityModel.Logging.LogHelper.Throw(String message,Type exceptionType,EventLevel logLevel,Exception innerException)
InvalidOperationException:IDX10803:无法从以下位置获取配置:' http:// localhost:50000/.well-known/openid-configuration '.内部异常:'IDX10804:无法从以下位置检索文档:' http:// localhost:50000/.well-known/openid-configuration '.'.
请考虑以下步骤来重现(但请不要考虑这个生产有价值的代码):
描述应用ASP.NET Beta8工装这里
打开Visual Studio Enterprise 2015并创建新的Web API ASP.NET 5预览模板项目
改变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-beta3版",
"Microsoft.AspNet.Authentication.OpenIdConnect": "1.0.0-beta8",
"Microsoft.Framework.ConfigurationModel.Json": "1.0.0-BETA4",
" 微软.AspNet.Diagnostics":"1.0.0-beta8"
},
"命令":{
"web":"Microsoft.AspNet.Server.Kestrel"
},
"frameworks":{
"dnx451":{}
},
"排除":[
"wwwroot的",
"node_modules"
],
"publishExclude":[
" .用户",
" .vspscc"
]
}
更改Startup.cs如下(这是@ Pinpoint原始文章的礼貌;我已删除评论并添加了AddAuthorization剪辑):
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();
}
}
Run Code Online (Sandbox Code Playgroud)
[Route("api/[controller]")]
public class ValuesController : Controller
{
// GET: api/values
[Authorize("Bearer")]
[HttpGet]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
}
Run Code Online (Sandbox Code Playgroud)
运行项目,并使用邮递员获取令牌.要获取令牌,请使用x-www-form-urlencoded POST,其中"grant_type"为"password","username"为"password","password"为any,"resource"为API端点的地址.我的特定URL例如是http:// localhost:37734/authorization/v1.
复制Base64编码的令牌,然后使用令牌使用邮递员调用wizarded值控制器.要使用令牌,请使用标题Content-Type application/json和Authorization bearer eyJ0eXAiO ....(您的令牌)进行GET.我的特定URL是http:// localhost:37734/api/values.
观察前面提到的例外情况.
如果我正在尝试的[授权("承载")]方法是错误的方法,我会非常感激,如果有人可以帮助我理解如何使用OIDC摄取JWT令牌的最佳实践.
谢谢.
options.Authority对应于发行人地址(即您的OIDC服务器的地址)。
http://localhost:50000/http://localhost:37734/当您稍后在问题中使用时,这似乎不正确。尝试修复 URL,然后再试一次。
| 归档时间: |
|
| 查看次数: |
4225 次 |
| 最近记录: |