我无法找到安全的方法来使用 ASP.net 核心 web api 和 Angular (PWA) 仅获取链接到经过身份验证的用户的数据。
我在 Angular 中尝试
了 1. MSAL,并使用登录 ID 调用了一个 API 函数,但基于 Java 的客户端代码似乎不安全,或者我可能错了。
http.get(' https://api.abc.edu/api/students/11223@abc.edu ) -->11223 是家长登录。
我在 web api 中尝试了替代方法来获取登录 ID,然后调用数据库来获取数据。
var userId = _httpContextAccessor.HttpContext.User.FindFirst("preferred_username").Value;
以角度方式:
getItems(parentID: string): Observable<ParentStudent[]> {
return this.http.get(this.apiEndpointParentStudents + "/" + parentID) //parentID is a logged user name from Azure called from Angular.
.map((response: Response) =>
response
)
.catch(response => (Observable.throw(response)
))
}
以 webapi 方式:
startup.cs
public void ConfigureServices(IServiceCollection services)
{
// Inject default DB connection string.
services.AddDbContext<SchoolContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddAuthentication(sharedOptions =>
{
sharedOptions.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddAzureAdBearer(options => Configuration.Bind("AzureAd", options));
services.AddProtectWebApiWithMicrosoftIdentityPlatformV2(Configuration);
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Latest);
services.AddCors();
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>(); // find a login user.
//services.AddHttpContextAccessor();
services.AddTransient<IUserResolverService, UserResolverService>();
services.AddMvc();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
----
app.UseAuthentication();
------
}
StudentsController.cs
[HttpGet]
public async Task<ActionResult<IEnumerable<Student>>> GetStudents()
{
var userId = _httpContextAccessor.HttpContext.User.FindFirst("preferred_username").Value;
return await _context.Students.Where(t => t.ParentLoginUsername == userId || t.ParentLoginUsername == userId).ToListAsync();
}
两者都工作得很好,但是为了安全,在我的上述解决方案中,是否应该首先考虑基于 webapi 的解决方案而不是任何基于客户端的解决方案,例如 Angular?黑客、其他父母或其他银行客户(如果我的 PWA 是银行应用程序)在获得身份验证 ID 和身份验证令牌后,是否可以在 Angular 或邮递员中使用其他人的用户 ID 调用 API?