Tom*_*ane 6 authentication single-page-application aurelia asp.net-core-webapi
我的 SPA 应用程序(使用 Aurelia)调用我的 ASP.NET Core 2 Web API。我需要使用 Google OIDC 提供商对用户进行身份验证,并使用相同的方法保护 Web API。
目前我能够在客户端 (SPA) 端对用户进行身份验证并检索 id 令牌和访问令牌。对于每个 API 调用,我都会在标头中发送访问令牌。
现在我不确定如何处理服务器端以验证令牌并授予或拒绝对 API 的访问。我按照官方文档如何添加外部登录提供程序,但它似乎只适用于服务器端 MVC 应用程序。
有什么简单的方法可以做到这一点吗?
我认为例如 IdentityServer4 可以支持这种情况,但在我看来它对于我需要做的事情来说太复杂了。毕竟我不需要自己的身份/授权服务器。
更新:
根据 Miroslav Popovic 的回答,我对 ASP.NET Core 2.0 的配置如下所示:
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(o =>
{
o.Authority = "https://accounts.google.com";
o.TokenValidationParameters = new TokenValidationParameters
{
ValidIssuer = "accounts.google.com",
ValidAudience = "xxxxxxxxxxxxx.apps.googleusercontent.com",
ValidateAudience = true,
ValidateIssuer = true
};
});
services.AddMvc();
}
Run Code Online (Sandbox Code Playgroud)
在Configure()我打电话app.UseAuthentication()。
使用此设置时,我收到失败消息No SecurityTokenValidator 可用于令牌。
更新 2:
我让它工作。服务器配置正确。问题是我正在向 API 发送 access_token 而不是 id_token。
由于您已经拥有访问令牌,因此使用它来添加身份验证应该不会太难。你需要一些类似的东西(未经测试):
// Inside Startup.cs, ConfigureServices method
services
.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(
options =>
{
var tokenValidationParameters = new TokenValidationParameters
{
ValidIssuer = "accounts.google.com",
ValidateAudience = false
};
options.MetadataAddress = "https://accounts.google.com/.well-known/openid-configuration";
options.TokenValidationParameters = tokenValidationParameters;
});
// Inside Startup.cs, Configure method
app.UseAuthentication(); // Before MVC middleware
app.UseMvc();
// And of course, on your controllers:
[Authorize]
public class MyApiController : Controller
Run Code Online (Sandbox Code Playgroud)
Paul Rowe 的这篇文章可能会有所帮助,但请注意,它是为 ASP.NET Core 1.x 编写的,并且身份验证 API 在 2.0 中发生了一些变化。
这里还有很多关于SO的信息,比如这个问题。
| 归档时间: |
|
| 查看次数: |
1181 次 |
| 最近记录: |