I cannot figure out safe way to get only data linked to authenticated users using ASP.net core web api and Angular (PWA).
I tried
1. MSAL inside Angular and called an API function with login ID but Java based client codes do not seem to be safe or I could be wrong.
http.get('https://api.abc.edu/api/students/11223@abc.edu) -->11223 is parent login.
I tried alternative inside the web api to get login ID then call a database to get data.
var userId = _httpContextAccessor.HttpContext.User.FindFirst("preferred_username").Value;
In Angluar way:
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)
))
}
in webapi way:
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();
}
Both worked fine but for security, among my above solutions, should the webapi based solution be considered first over any client based solutions such as Angular? Can hackers , another parents or another bank customers (if my PWA is a banking app) call api with other persons’ user id in Angular or postman once they got auth id and auth token?