我正在使用ASP.NET Core应用程序。我正在尝试实现基于令牌的身份验证,但无法弄清楚如何在我的情况下使用新的Security System。 我经历了examples,但他们对我没什么帮助,他们使用的是cookie身份验证或外部身份验证(GitHub,Microsoft,Twitter)。
我的场景是什么:angularjs应用程序应该请求/token
url传递用户名和密码。 WebApi应授权用户并返回access_token
,这将由angularjs app在以下请求中使用。
我找到了很好的文章,关于在当前版本的ASP.NET中实现我需要的内容 - Token Based Authentication using ASP.NET Web API 2, Owin, and Identity。但对我来说,如何在ASP.NET Core中做同样的事情并不明显。
我的问题是:如何配置ASP.NET Core WebApi应用程序以使用基于令牌的身份验证?
答案 0 :(得分:123)
此答案的先前版本使用RSA;如果生成令牌的相同代码也在验证令牌,则实际上没有必要。但是,如果您要分配责任,您可能仍希望使用Microsoft.IdentityModel.Tokens.RsaSecurityKey
的实例执行此操作。
创建一些我们稍后会使用的常量;这是我做的:
const string TokenAudience = "Myself";
const string TokenIssuer = "MyProject";
将此添加到Startup.cs的ConfigureServices
。我们稍后将使用依赖注入来访问这些设置。我假设您的authenticationConfiguration
是ConfigurationSection
或Configuration
对象,这样您就可以拥有不同的调试和生产配置。确保您安全地存放钥匙!它可以是任何字符串。
var keySecret = authenticationConfiguration["JwtSigningKey"];
var symmetricKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(keySecret));
services.AddTransient(_ => new JwtSignInHandler(symmetricKey));
services.AddAuthentication(options =>
{
// This causes the default authentication scheme to be JWT.
// Without this, the Authorization header is not checked and
// you'll get no results. However, this also means that if
// you're already using cookies in your app, they won't be
// checked by default.
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
options.TokenValidationParameters.ValidateIssuerSigningKey = true;
options.TokenValidationParameters.IssuerSigningKey = symmetricKey;
options.TokenValidationParameters.ValidAudience = JwtSignInHandler.TokenAudience;
options.TokenValidationParameters.ValidIssuer = JwtSignInHandler.TokenIssuer;
});
我看到其他答案会更改其他设置,例如ClockSkew
;设置默认值,使其适用于时钟不完全同步的分布式环境。这些是您需要更改的唯一设置。
设置身份验证。您应该在需要User
信息的任何中间件之前使用此行,例如app.UseMvc()
。
app.UseAuthentication();
请注意,这不会导致您的令牌与SignInManager
或其他任何内容一起发出。您需要提供自己的输出JWT的机制 - 见下文。
您可能需要指定AuthorizationPolicy
。这将允许您指定仅允许使用[Authorize("Bearer")]
进行身份验证的承载令牌的控制器和操作。
services.AddAuthorization(auth =>
{
auth.AddPolicy("Bearer", new AuthorizationPolicyBuilder()
.AddAuthenticationTypes(JwtBearerDefaults.AuthenticationType)
.RequireAuthenticatedUser().Build());
});
这里有一个棘手的部分:构建令牌。
class JwtSignInHandler
{
public const string TokenAudience = "Myself";
public const string TokenIssuer = "MyProject";
private readonly SymmetricSecurityKey key;
public JwtSignInHandler(SymmetricSecurityKey symmetricKey)
{
this.key = symmetricKey;
}
public string BuildJwt(ClaimsPrincipal principal)
{
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken(
issuer: TokenIssuer,
audience: TokenAudience,
claims: principal.Claims,
expires: DateTime.Now.AddMinutes(20),
signingCredentials: creds
);
return new JwtSecurityTokenHandler().WriteToken(token);
}
}
然后,在您需要令牌的控制器中,如下所示:
[HttpPost]
public string AnonymousSignIn([FromServices] JwtSignInHandler tokenFactory)
{
var principal = new System.Security.Claims.ClaimsPrincipal(new[]
{
new System.Security.Claims.ClaimsIdentity(new[]
{
new System.Security.Claims.Claim(System.Security.Claims.ClaimTypes.Name, "Demo User")
})
});
return tokenFactory.BuildJwt(principal);
}
在这里,我假设你已经有了校长。如果您使用的是身份,则可以使用IUserClaimsPrincipalFactory<>
将User
转换为ClaimsPrincipal
。
要对其进行测试:获取令牌,将其放入jwt.io的表单中。我上面提供的说明还允许您使用配置中的秘密来验证签名!
如果您在HTML页面上的部分视图中与.Net 4.5中的仅承载身份验证一起呈现此内容,您现在可以使用ViewComponent
执行相同的操作。它与上面的Controller Action代码大致相同。
答案 1 :(得分:80)
在Matt Dekrey's fabulous answer工作,我创建了一个基于令牌的身份验证的完整工作示例,针对ASP.NET Core(1.0.1)。您可以找到完整代码in this repository on GitHub(1.0.0-rc1,beta8,beta7的替代分支),但简而言之,重要的步骤是:
为您的应用生成密钥
在我的示例中,每次应用程序启动时都会生成一个随机密钥,您需要生成一个随机密钥并将其存储在某个位置并将其提供给您的应用程序。 See this file for how I'm generating a random key and how you might import it from a .json file。正如@kspearrin的评论中所建议的那样,Data Protection API似乎是理想的候选人,正确管理密钥&#34;但是,如果可能的话,我还没有成功。 。如果您解决了,请提交拉取请求!
Startup.cs - ConfigureServices
在这里,我们需要为我们的令牌加载私钥,我们还将使用它来验证令牌。我们将密钥存储在类级变量key
中,我们将在下面的配置方法中重复使用它。 TokenAuthOptions是一个简单的类,它包含我们在TokenController中创建密钥所需的签名身份,受众和发布者。
// Replace this with some sort of loading from config / file.
RSAParameters keyParams = RSAKeyUtils.GetRandomKey();
// Create the key, and a set of token options to record signing credentials
// using that key, along with the other parameters we will need in the
// token controlller.
key = new RsaSecurityKey(keyParams);
tokenOptions = new TokenAuthOptions()
{
Audience = TokenAudience,
Issuer = TokenIssuer,
SigningCredentials = new SigningCredentials(key, SecurityAlgorithms.Sha256Digest)
};
// Save the token options into an instance so they're accessible to the
// controller.
services.AddSingleton<TokenAuthOptions>(tokenOptions);
// Enable the use of an [Authorize("Bearer")] attribute on methods and
// classes to protect.
services.AddAuthorization(auth =>
{
auth.AddPolicy("Bearer", new AuthorizationPolicyBuilder()
.AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme)
.RequireAuthenticatedUser().Build());
});
我们还设置了授权政策,允许我们在我们希望保护的端点和类上使用[Authorize("Bearer")]
。
Startup.cs - 配置
在这里,我们需要配置JwtBearerAuthentication:
app.UseJwtBearerAuthentication(new JwtBearerOptions {
TokenValidationParameters = new TokenValidationParameters {
IssuerSigningKey = key,
ValidAudience = tokenOptions.Audience,
ValidIssuer = tokenOptions.Issuer,
// When receiving a token, check that it is still valid.
ValidateLifetime = true,
// This defines the maximum allowable clock skew - i.e.
// provides a tolerance on the token expiry time
// when validating the lifetime. As we're creating the tokens
// locally and validating them on the same machines which
// should have synchronised time, this can be set to zero.
// Where external tokens are used, some leeway here could be
// useful.
ClockSkew = TimeSpan.FromMinutes(0)
}
});
<强> TokenController 强>
在令牌控制器中,您需要有一个方法来使用Startup.cs中加载的密钥生成签名密钥。我们在Startup中注册了一个TokenAuthOptions实例,所以我们需要在TokenController的构造函数中注入它:
[Route("api/[controller]")]
public class TokenController : Controller
{
private readonly TokenAuthOptions tokenOptions;
public TokenController(TokenAuthOptions tokenOptions)
{
this.tokenOptions = tokenOptions;
}
...
然后你需要在你的处理程序中为登录端点生成令牌,在我的例子中,我使用用户名和密码并使用if语句验证那些,但你需要的关键是do是创建或加载基于声明的标识并为其生成标记:
public class AuthRequest
{
public string username { get; set; }
public string password { get; set; }
}
/// <summary>
/// Request a new token for a given username/password pair.
/// </summary>
/// <param name="req"></param>
/// <returns></returns>
[HttpPost]
public dynamic Post([FromBody] AuthRequest req)
{
// Obviously, at this point you need to validate the username and password against whatever system you wish.
if ((req.username == "TEST" && req.password == "TEST") || (req.username == "TEST2" && req.password == "TEST"))
{
DateTime? expires = DateTime.UtcNow.AddMinutes(2);
var token = GetToken(req.username, expires);
return new { authenticated = true, entityId = 1, token = token, tokenExpires = expires };
}
return new { authenticated = false };
}
private string GetToken(string user, DateTime? expires)
{
var handler = new JwtSecurityTokenHandler();
// Here, you should create or look up an identity for the user which is being authenticated.
// For now, just creating a simple generic identity.
ClaimsIdentity identity = new ClaimsIdentity(new GenericIdentity(user, "TokenAuth"), new[] { new Claim("EntityID", "1", ClaimValueTypes.Integer) });
var securityToken = handler.CreateToken(new Microsoft.IdentityModel.Tokens.SecurityTokenDescriptor() {
Issuer = tokenOptions.Issuer,
Audience = tokenOptions.Audience,
SigningCredentials = tokenOptions.SigningCredentials,
Subject = identity,
Expires = expires
});
return handler.WriteToken(securityToken);
}
那应该是它。只需将[Authorize("Bearer")]
添加到您要保护的任何方法或类中,如果您在没有令牌存在的情况下尝试访问它,则应该收到错误。如果要返回401而不是500错误,则需要注册自定义异常处理程序as I have in my example here。
答案 2 :(得分:3)
您可以查看OpenId连接示例,它们说明了如何处理不同的身份验证机制,包括JWT令牌:
https://github.com/aspnet-contrib/AspNet.Security.OpenIdConnect.Samples
如果你看看Cordova后端项目,API的配置是这样的:
// Create a new branch where the registered middleware will be executed only for non API calls.
app.UseWhen(context => !context.Request.Path.StartsWithSegments(new PathString("/api")), branch => {
// Insert a new cookies middleware in the pipeline to store
// the user identity returned by the external identity provider.
branch.UseCookieAuthentication(new CookieAuthenticationOptions {
AutomaticAuthenticate = true,
AutomaticChallenge = true,
AuthenticationScheme = "ServerCookie",
CookieName = CookieAuthenticationDefaults.CookiePrefix + "ServerCookie",
ExpireTimeSpan = TimeSpan.FromMinutes(5),
LoginPath = new PathString("/signin"),
LogoutPath = new PathString("/signout")
});
branch.UseGoogleAuthentication(new GoogleOptions {
ClientId = "560027070069-37ldt4kfuohhu3m495hk2j4pjp92d382.apps.googleusercontent.com",
ClientSecret = "n2Q-GEw9RQjzcRbU3qhfTj8f"
});
branch.UseTwitterAuthentication(new TwitterOptions {
ConsumerKey = "6XaCTaLbMqfj6ww3zvZ5g",
ConsumerSecret = "Il2eFzGIrYhz6BWjYhVXBPQSfZuS4xoHpSSyD9PI"
});
});
/Providers/AuthorizationProvider.cs中的逻辑和该项目的RessourceController也值得一看;)。
或者您也可以使用以下代码验证令牌(还有一个片段可以使其与signalR一起使用):
// Add a new middleware validating access tokens.
app.UseOAuthValidation(options =>
{
// Automatic authentication must be enabled
// for SignalR to receive the access token.
options.AutomaticAuthenticate = true;
options.Events = new OAuthValidationEvents
{
// Note: for SignalR connections, the default Authorization header does not work,
// because the WebSockets JS API doesn't allow setting custom parameters.
// To work around this limitation, the access token is retrieved from the query string.
OnRetrieveToken = context =>
{
// Note: when the token is missing from the query string,
// context.Token is null and the JWT bearer middleware will
// automatically try to retrieve it from the Authorization header.
context.Token = context.Request.Query["access_token"];
return Task.FromResult(0);
}
};
});
对于发布令牌,您可以使用openId Connect服务器包,如下所示:
// Add a new middleware issuing access tokens.
app.UseOpenIdConnectServer(options =>
{
options.Provider = new AuthenticationProvider();
// Enable the authorization, logout, token and userinfo endpoints.
//options.AuthorizationEndpointPath = "/connect/authorize";
//options.LogoutEndpointPath = "/connect/logout";
options.TokenEndpointPath = "/connect/token";
//options.UserinfoEndpointPath = "/connect/userinfo";
// Note: if you don't explicitly register a signing key, one is automatically generated and
// persisted on the disk. If the key cannot be persisted, an exception is thrown.
//
// On production, using a X.509 certificate stored in the machine store is recommended.
// You can generate a self-signed certificate using Pluralsight's self-cert utility:
// https://s3.amazonaws.com/pluralsight-free/keith-brown/samples/SelfCert.zip
//
// options.SigningCredentials.AddCertificate("7D2A741FE34CC2C7369237A5F2078988E17A6A75");
//
// Alternatively, you can also store the certificate as an embedded .pfx resource
// directly in this assembly or in a file published alongside this project:
//
// options.SigningCredentials.AddCertificate(
// assembly: typeof(Startup).GetTypeInfo().Assembly,
// resource: "Nancy.Server.Certificate.pfx",
// password: "Owin.Security.OpenIdConnect.Server");
// Note: see AuthorizationController.cs for more
// information concerning ApplicationCanDisplayErrors.
options.ApplicationCanDisplayErrors = true // in dev only ...;
options.AllowInsecureHttp = true // in dev only...;
});
编辑:我使用Aurelia前端框架和ASP.NET核心实现了一个基于令牌的身份验证实现的单页面应用程序。还有一个信号R持久连接。但是我没有做过任何数据库实现。 代码可以在这里看到: https://github.com/alexandre-spieser/AureliaAspNetCoreAuth
希望这有帮助,
最佳,
亚历
答案 3 :(得分:1)
看看OpenIddict - 它是一个新项目(在撰写本文时),可以轻松配置在ASP.NET 5中创建JWT令牌和刷新令牌。令牌的验证由其他软件处理
假设您将Identity
与Entity Framework
一起使用,最后一行是您添加到ConfigureServices
方法的内容:
services.AddIdentity<ApplicationUser, ApplicationRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders()
.AddOpenIddictCore<Application>(config => config.UseEntityFramework());
在Configure
中,您设置OpenIddict来提供JWT令牌:
app.UseOpenIddictCore(builder =>
{
// tell openiddict you're wanting to use jwt tokens
builder.Options.UseJwtTokens();
// NOTE: for dev consumption only! for live, this is not encouraged!
builder.Options.AllowInsecureHttp = true;
builder.Options.ApplicationCanDisplayErrors = true;
});
您还可以在Configure
中配置令牌验证:
// use jwt bearer authentication
app.UseJwtBearerAuthentication(options =>
{
options.AutomaticAuthenticate = true;
options.AutomaticChallenge = true;
options.RequireHttpsMetadata = false;
options.Audience = "http://localhost:58292/";
options.Authority = "http://localhost:58292/";
});
还有一两件小事,例如你的DbContext需要从OpenIddictContext派生。
您可以在此博文中看到完整的说明:http://capesean.co.za/blog/asp-net-5-jwt-tokens/
可在以下位置找到功能正常的演示:https://github.com/capesean/openiddict-test