[英]How to forward all SPA page requests through a Web Api controller?
我有一個angular application
,我希望所有通過它的請求首先通過API Controller
以檢查角色或授權。我不想更改我的所有urls
以便它們與Controller
匹配:
我希望該服務器上的所有請求首先通過控制器:
路線示例
localhost:4200/index
localhost:4200/details
localhost:4200/data/3
目前,我在Startup
管道如下所示:
public void Configure(IApplicationBuilder app, IHostingEnvironment env) {
app.UseStaticFiles();
app.UseSpaStaticFiles();
app.UseMvc(routes => {
routes.MapRoute(
name: "default",
template: "{controller}/{action=Index}/{id?}");
});
app.UseSpa(spa => {
spa.Options.SourcePath = "WorkingApp";
if (env.IsDevelopment()) {
spa.UseAngularCliServer(npmScript: "start");
}
});
}
控制器
using Serilog;
public class AuthController : ControllerBase {
[HttpGet("[action]")]
public async Task<ActionResult<AuthenticationResult>> GetUsernameAndRolesAsync() {
try {
var result = new AuthenticationResult() {
Username = User.Identity.Name,
Roles = User.Claims.Where(x => x.Type == ClaimTypes.Role)
.Select(x => x.Value)
.ToList()
};
Log.Information($"GetUsernameAndRolesAsync returned IsAuthenticated={User.Identity.IsAuthenticated} for username {result.Username}");
foreach (var role in result.Roles) {
Log.Information($"GetUsernameAndRolesAsync returned role: {role} for username: {result.Username}");
}
return result;
} catch (Exception ex) {
return new StatusCodeResult(500);
}
}
}
public class AuthenticationResult {
public string Username { get; set; }
public List<string> Roles { get; set; }
}
我如何更改我的MVC
模板和管道,以便所有請求無縫地通過我的控制器?
對於這個要求
我希望所有通過它的請求首先通過 API 控制器以檢查角色或授權
這不是推薦的方法,因為如果您想檢查用戶訪問資源的權限,angular 已經提供了一個guard
。 Guard 用於檢查用戶權限和授權。
.Net Core web api 有Authorize
屬性來檢查用戶通常使用 SPA 訪問 API 資源的權限,你需要實現 JWT。 令牌將存儲在客戶端,當用戶請求 API 資源時,我們將請求與標頭中的令牌一起發送,以讓服務器知道誰在請求資源
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.