我正在研究一些MVC 6和ASP.NET 5示例,在查找有关使用承载令牌保护API安全的任何有价值的文档时遇到问题。我能够使这样的示例与VS2013、MVC 5一起工作,但我无法将它们移植到VS2015和MVC 6。有人知道在MVC 6中实现承载令牌以确保API安全的任何好例子吗?
为了使用承载令牌对请求进行身份验证,可以下载Microsoft.AspNet.Security.AuthBearer包。然后,可以使用UseOAuthBearerAuthentication
扩展方法将OAuthBearerAuthenticationMiddleware
中间件添加到管道中。
示例:
public void Configure(IApplicationBuilder app)
{
// ...
app.UseOAuthBearerAuthentication(options =>
{
options.Audience = "Redplace-With-Real-Audience-Info";
options.Authority = "Redplace-With-Real-Authority-Info";
});
}
另外,请查看WebApp-WebAPI-OpenIdConnect-AspNet5示例。
Asp.Net Core中没有中间件,它生成承载令牌。您可以创建自己的解决方案或实施一些基于社区的方法,如
- OpenIdConnect
- OpenIdDict
- 标识服务器4
我已经使用MVC 6、OpenId和Aurelia前端框架实现了一个具有基于令牌的身份验证实现的单页应用程序。在Startup.cs中,Configure方法如下所示:
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
app.UseIISPlatformHandler();
// Add a new middleware validating access tokens.
app.UseJwtBearerAuthentication(options => {
// Automatic authentication must be enabled
// for SignalR to receive the access token.
options.AutomaticAuthenticate = true;
// Automatically disable the HTTPS requirement for development scenarios.
options.RequireHttpsMetadata = !env.IsDevelopment();
// Note: the audience must correspond to the address of the SignalR server.
options.Audience = clientUri;
// Note: the authority must match the address of the identity server.
options.Authority = serverUri;
});
// Add a new middleware issuing access tokens.
app.UseOpenIdConnectServer(options => {
options.Provider = new AuthenticationProvider();
});
app.UseIISPlatformHandler(options => options.AuthenticationDescriptions.Clear());
app.UseStaticFiles();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
身份验证提供者的定义如下:
public class AuthenticationProvider : OpenIdConnectServerProvider
{
public override Task ValidateClientAuthentication(ValidateClientAuthenticationContext context)
{
if (context.ClientId == "AureliaNetAuthApp")
{
// Note: the context is marked as skipped instead of validated because the client
// is not trusted (JavaScript applications cannot keep their credentials secret).
context.Skipped();
}
else {
// If the client_id doesn't correspond to the
// intended identifier, reject the request.
context.Rejected();
}
return Task.FromResult(0);
}
public override Task GrantResourceOwnerCredentials(GrantResourceOwnerCredentialsContext context)
{
var user = new { Id = "users-123", Email = "alex@123.com", Password = "AureliaNetAuth" };
if (context.UserName != user.Email || context.Password != user.Password)
{
context.Rejected("Invalid username or password.");
return Task.FromResult(0);
}
var identity = new ClaimsIdentity(OpenIdConnectDefaults.AuthenticationScheme);
identity.AddClaim(ClaimTypes.NameIdentifier, user.Id, "id_token token");
identity.AddClaim(ClaimTypes.Name, user.Email, "id_token token");
context.Validated(new ClaimsPrincipal(identity));
return Task.FromResult(0);
}
}
这定义了可以在url /connect/token
处到达的令牌端点。
因此,要从客户端请求令牌,以下是javascript代码,取自authSvc.js:中的AuthService
login(username, password) {
var baseUrl = yourBaseUrl;
var data = "client_id=" + yourAppClientId
+ "&grant_type=password"
+ "&username=" + username
+ "&password=" + password
+ "&resource=" + encodeURIComponent(baseUrl);
return this.http.fetch(baseUrl + 'connect/token', {
method: 'post',
body : data
});
}
完整的来源可以在这里看到:
https://github.com/alexandre-spieser/AureliaAspNetCoreAuth
希望这能有所帮助,
最佳,
Alex