【发布时间】:2018-03-14 21:28:15
【问题描述】:
我一直在使用各种教程来设置以下场景:
我有一个基于 Ionic 框架构建的移动应用程序作为前端。我有一个 ASP.Net Core 1.1.2 Web API 作为后端。我想在移动应用程序中针对 Azure Active Directory 对用户进行身份验证,然后才允许他们访问 API。
这是我对如何实现这一点的概念理解:
- 在 AAD 门户中注册两个应用程序,一个为应用程序类型 Web App/API(称为 WebAPI),另一个为应用程序类型 Native(称为 MobileApp)。
- 在 AAD 的 Delegated Permissions 中添加移动应用访问 WebAPI 的权限。
- 使用 MobileApp 从 AAD 请求令牌。
- 将令牌与任何请求一起发送到 WebAPI。
- 使用 app.UseJwtBearerAuthentication 中间件来验证令牌并管理对来自 WebAPI 的内容的访问。
我的第一个问题是,我的策略是否正确?如果是这样,我在中间件的实现中一定做错了。
我目前正在应用内针对 AAD 进行身份验证并收到一个返回的令牌,其有效负载如下:
{
"aud": "https://crm.mycompany.com/",
"iss": "https://sts.windows.net/someID/",
"iat": 1506539211,
"nbf": 1506539211,
"exp": 1506543111,
"acr": "1",
"aio": "someOtherID",
"amr": [
"pwd"
],
"appid": "appID",
"appidacr": "0",
"e_exp": 262800,
"family_name": "Walter",
"given_name": "Philip",
"ipaddr": "someAddress",
"name": "Philip Walter",
"oid": "someOtherID",
"onprem_sid": "someOtherID",
"puid": "stuff",
"scp": "user_impersonation",
"sub": "e_X7WlAoVS2vzXm1pr3kcDOrET7czcC0f8-YRU_2DJ8",
"tenant_region_scope": "NA",
"tid": "ourTenantID",
"unique_name": "pwalter@advtis.com",
"upn": "pwalter@advtis.com",
"uti": "RLvLlibQHESwmujVBBdlAA",
"ver": "1.0"
}
我可以在 Authentication: Bearer [token] 标头中将令牌发送到我的 API,但我收到了 401 Unauthorized 响应。我一直在尝试将以下教程用于我的中间件实现:
ASP.NET Core Token Authentication Guide
这看起来很简单,但显然我错过了一些东西。这是我的 Startup.cs:
public class Startup
{
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<AdvancedDBContext>();
// Add framework services.
services.AddCors();
services.AddMvc();
}
// 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)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
app.UseCors(builder =>
{
builder.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod();
});
app.UseJwtBearerAuthentication(new JwtBearerOptions
{
TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidIssuer = "https://sts.windows.net/e618ef87-13b6-491b-babf-4e4f4139e3f3/",
ValidateAudience = true,
ValidAudience = "https://crm.mycompany.com"
},
AutomaticAuthenticate = true
});
app.UseMvc();
}
}
}
然后我根据需要使用 [Authorize] 属性来保护路由。
这个实现与教程中的实现之间的主要区别是我没有在任何地方指定密钥,但我不确定如何实现它,因为 AAD 正在发布令牌。也许我需要从 AAD 获得一个?
任何帮助将不胜感激!
【问题讨论】:
标签: asp.net azure authentication asp.net-web-api