簡體   English   中英

如何通過 Web Api 控制器轉發所有 SPA 頁面請求?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM