[英]ASP.NET 5 OAuth bearer token authentication
I'm trying to implement OAuth bearer token authentication in ASP.NET 5 and am struggling to find an example of how to do this because the OWIN stuff has changed in ASP.NET 5. 我正在尝试在ASP.NET 5中实现OAuth承载令牌身份验证,并且很难找到如何执行此操作的示例,因为ASP.NET 5中的OWIN内容已经发生了变化。
For example IApplicationBuilder.UseOAuthAuthorizationServer() and IApplicationBuilder. 例如IApplicationBuilder.UseOAuthAuthorizationServer()和IApplicationBuilder。 UseOAuthBearerAuthentication() either don't exist anymore or I'm missing a reference? UseOAuthBearerAuthentication()要不再存在,要么我错过了引用?
Any pointers would be greatly appreciated. 任何指针都将非常感激。
I did it work, but with setting up Thinktecture's identity server v 3 as my token provider but I think if you have another token provider it will be the same flow.... 我做了它的工作,但设置了Thinktecture的身份服务器v 3作为我的令牌提供程序,但我认为如果你有另一个令牌提供程序,它将是相同的流程....
(update : I added a github repo with the code : here ) (更新:我在代码中添加了一个github repo: here )
here is my startup class: (Identityserver v3 also runs on Vnext with some little tweaking). 这是我的启动类:( Identityserver v3也在Vnext上运行,稍加调整)。 notice I have the server and the web api in same web app. 注意我在同一个Web应用程序中有服务器和web api。 it's also ok if you have two different web project but here it's for the sake of demo... 如果你有两个不同的网络项目也可以,但这里是为了演示......
public class Startup
{
// For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
}
public void Configure(IApplicationBuilder app)
{
app.Map("/core", core =>
{
var factory = InMemoryFactory.Create(
users: Users.Get(),
clients: Clients.Get(),
scopes: Scopes.Get());
var idsrvOptions = new IdentityServerOptions
{
IssuerUri = "https://idsrv3.com",
SiteName = "test vnext Identity server",
Factory = factory,
SigningCertificate = Certificate.Get(),
RequireSsl = false,
CorsPolicy = CorsPolicy.AllowAll,
AuthenticationOptions = new AuthenticationOptions
{
}
};
core.UseIdentityServer(idsrvOptions);
});
app.Map("/api", api =>
{
api.UseOAuthBearerAuthentication(options => {
options.Authority = Constants.AuthorizationUrl;
options.MetadataAddress = Constants.AuthorizationUrl + "/.well-known/openid-configuration";
options.TokenValidationParameters.ValidAudience = "https://idsrv3.com/resources";
});
api.UseMvc();
});
}
}
from here you can see that my IdentityServerV3 is mapped to '/core' and in the same web app project (it could be another one), I have an web api that uses MVC. 从这里你可以看到我的IdentityServerV3被映射到'/ core'并且在同一个web应用程序项目中(它可能是另一个),我有一个使用MVC的web api。 below is the controller: 以下是控制器:
[Authorize]
[Route("[controller]")]
public class Test : Controller
{
[HttpGet]
public JsonResult Get()
{
return Json(new
{
message = "You See this then it's ok auth is :" + User.Identity.IsAuthenticated,
});
}
}
I have configure a Client in my identity server : 我在我的身份服务器中配置了一个客户端:
new Client
{
//Resource Owner Flow Client (our web UI)
ClientName = "WebUI",
Enabled = true,
ClientId = "IdentityWebUI",
ClientSecrets = new List<ClientSecret>
{
new ClientSecret("secret".Sha256())
},
Flow = Flows.ResourceOwner,
AccessTokenType = AccessTokenType.Jwt,
AccessTokenLifetime = 3600
}
and here is the User (used InMemory user): 这是用户(使用InMemory用户):
return new List<InMemoryUser>
{
new InMemoryUser
{
Username = "testUser",
Password = "testPwd",
Subject = "I am the Subject"
}
};
In fidler I issue the following POST to get a bearer token: 在fidler中,我发出以下POST来获取持票人令牌:
POST : http://localhost:4357/core/connect/token
User-Agent: Fiddler
Host: localhost:4357
Content-Length: 67
Content-Type: application/x-www-form-urlencoded
Authorization: Basic SWRlbnRpdHlXZWJVSTpzZWNyZXQ=
grant_type=password&username=testUser&password=testPwd&scope=openid
in the response you will get an Access_token 在响应中,您将获得Access_token
{"access_token":"eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6ImEzck1VZ01Gdjl0UGNsTGE2eUYzekFrZnF1RSIsImtpZCI6ImEzck1VZ01Gdjl0UGNsTGE2eUYzekFrZnF1RSJ9.eyJjbGllbnRfaWQiOiJJZGVudGl0eVdlYlVJIiwic2NvcGUiOiJvcGVuaWQiLCJzdWIiOiJJIGFtIHRoZSBTdWJqZWN0IiwiYW1yIjoicGFzc3dvcmQiLCJhdXRoX3RpbWUiOjE0MjgzOTQ3MzAsImlkcCI6Imlkc3J2IiwiaXNzIjoiaHR0cHM6Ly9pZHNydjMuY29tIiwiYXVkIjoiaHR0cHM6Ly9pZHNydjMuY29tL3Jlc291cmNlcyIsImV4cCI6MTQyODM5ODMzMCwibmJmIjoxNDI4Mzk0NzMwfQ.cbB4YrRXaaRDNw8BjeI4Q1DvXN28xmJScMJBGWCM_zSLcH1i63cQVTmR8X86rGP5VrR0Ly4-EmWZ8911Vh4jc4Ua0Kgz2n7RbmQ6VqQX5Z_lM3F8EIgD81kpUn0v3hhSFW06aJ2Lo1XOZG_re84xGgqre-H4dC0XZR6IQMEAQ9Q5dOXBh8V1NxyLSh0PzyrRRmOnEndoaY4uaIFtbp9j7KnXxQ3ZdGmaYAO96xuhHfO1DbgRdw6fYyf4nnC795yhnwDh1QZGxPsFaysJSA_3-cjmw-29m-Ga0hD1ALfVE7R57iNLxkB6dyEuz1UFJhJyibRDW9sNspo2gQFZZGxMKQ","expires_in":3600,"token_type":"Bearer"}
then I use that access_token to call my web api 然后我使用access_token来调用我的web api
here is the fiddler (in composer pane) 这里是小提琴手(在作曲家窗格中)
GET http://localhost:4357/api/Test
User-Agent: Fiddler
Host: localhost:4357
Content-Length: 0
Content-Type: application/x-www-form-urlencoded
Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6ImEzck1VZ01Gdjl0UGNsTGE2eUYzekFrZnF1RSIsImtpZCI6ImEzck1VZ01Gdjl0UGNsTGE2eUYzekFrZnF1RSJ9.eyJjbGllbnRfaWQiOiJJZGVudGl0eVdlYlVJIiwic2NvcGUiOiJvcGVuaWQiLCJzdWIiOiJJIGFtIHRoZSBTdWJqZWN0IiwiYW1yIjoicGFzc3dvcmQiLCJhdXRoX3RpbWUiOjE0MjgzOTQ3MzAsImlkcCI6Imlkc3J2IiwiaXNzIjoiaHR0cHM6Ly9pZHNydjMuY29tIiwiYXVkIjoiaHR0cHM6Ly9pZHNydjMuY29tL3Jlc291cmNlcyIsImV4cCI6MTQyODM5ODMzMCwibmJmIjoxNDI4Mzk0NzMwfQ.cbB4YrRXaaRDNw8BjeI4Q1DvXN28xmJScMJBGWCM_zSLcH1i63cQVTmR8X86rGP5VrR0Ly4-EmWZ8911Vh4jc4Ua0Kgz2n7RbmQ6VqQX5Z_lM3F8EIgD81kpUn0v3hhSFW06aJ2Lo1XOZG_re84xGgqre-H4dC0XZR6IQMEAQ9Q5dOXBh8V1NxyLSh0PzyrRRmOnEndoaY4uaIFtbp9j7KnXxQ3ZdGmaYAO96xuhHfO1DbgRdw6fYyf4nnC795yhnwDh1QZGxPsFaysJSA_3-cjmw-29m-Ga0hD1ALfVE7R57iNLxkB6dyEuz1UFJhJyibRDW9sNspo2gQFZZGxMKQ
Then I get the response still in fidler: 然后我仍然得到fidler的响应:
you can have more info by following this link below, but it's not related to vnext. 您可以通过以下链接获得更多信息,但它与vnext无关。 I will create a post on this as I need an angularJS app to authenticate and use an implicit flow instead of resource owner flow... with visual studio 2015 preview 我将在此创建一个帖子,因为我需要一个angularJS应用程序来验证并使用隐式流而不是资源所有者流...使用visual studio 2015预览
I am not sure where UseOAuthAuthorizationServer is, but for UseOAuthBearerAuthentication , try adding the Microsoft.AspNet.Security.OAuthBearer NuGet Package and then in your startup Configure Method add: 我不确定UseOAuthAuthorizationServer在哪里,但对于UseOAuthBearerAuthentication ,尝试添加Microsoft.AspNet.Security.OAuthBearer NuGet包,然后在启动配置方法中添加:
app.UseOAuthBearerAuthentication(options =>
{
options.Audience = {your audience};
options.Authority = {your authority}}); //or whatever options you need
The real kicker here is the token generation. 这里真正的踢球者是令牌生成。 I've managed to build one using the default Microsoft.AspNet.Security.OAuthBearer
package, but it wasn't easy. 我已经设法使用默认的Microsoft.AspNet.Security.OAuthBearer
包构建一个,但这并不容易。
// Injected from the constructor; this is why we configured the options above rather
// than simply passing them to the UseOAuthBearerAuthentication()
private readonly OAuthBearerAuthenticationOptions bearerOptions;
// In your /Token action...
var handler = bearerOptions.SecurityTokenValidators.OfType<System.IdentityModel.Tokens.JwtSecurityTokenHandler>()
.First();
// The identity here is the ClaimsIdentity you want to authenticate the user as.
// You can get this using the SignInManager if you're using Identity.
var securityToken = handler.CreateToken(
issuer: bearerOptions.TokenValidationParameters.ValidIssuer,
audience: bearerOptions.TokenValidationParameters.ValidAudience,
subject: identity);
var token = handler.WriteToken(securityToken);
// The var token is your bearer token
My full solution is detailed here: Token Based Authentication in ASP.Net 5 (vNext) . 我的完整解决方案详述如下: ASP.Net 5中的基于令牌的身份验证(vNext) 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.