8

このチュートリアルに従いました: https://medium.com/@st.mas29/microsoft-blazor-web-api-with-jwt-authentication-part-1-f33a44abab9d

サンプルをダウンロードしました: https://github.com/StuwiiDev/DotnetCoreJwtAuthentication/tree/Part2

トークンが作成されたことはわかりますが、タグSampleDataControllerを持つにアクセスするたびに 401 が返されるため、クライアント側でトークンをどのように保存するか、または保存する必要があるかがわかりません。Authorize

Postman を使用してトークンを呼び出して追加すると、機能します。

ユーザーが認証されるために何が欠けていますか? Microsoft.AspNetCore.Authentication.JwtBearerクライアント部分 (トークンの保存) を処理しませんか?

4

3 に答える 3

2

次のクラスは、クライアントでログイン プロセスを処理し、JWT トークンをlocalストレージに格納します。注: JWT トークンを保存してサーバーに渡すのは、開発者の責任です。クライアント (Blazor、Angular など) は、自動的にそれを行いません。

public class SignInManager
    {
        // Receive 'http' instance from DI
        private readonly HttpClient http;
        public SignInManager(HttpClient http)
        {
            this.http = http;
        }

        [Inject]
        protected LocalStorage localStorage;


        public bool IsAuthenticated()
        {
            var token = localStorage.GetItem<string>("token");

            return (token != null); 
        }

        public string getToken()
        {
            return localStorage.GetItem<string>("token");
        }

        public void Clear()
        {
            localStorage.Clear();
        }


        // model.Email, model.Password, model.RememberMe, lockoutOnFailure: false
        public async Task<bool> PasswordSignInAsync(LoginViewModel model)
        {
            SearchInProgress = true;
            NotifyStateChanged();

            var result = await http.PostJsonAsync<Object>("/api/Account", model);

            if (result)// result.Succeeded
           {
              _logger.LogInformation("User logged in.");

              // Save the JWT token in the LocalStorage
              // https://github.com/BlazorExtensions/Storage
              await localStorage.SetItem<Object>("token", result);


              // Returns true to indicate the user has been logged in and the JWT token 
              // is saved on the user browser
             return true;

           }

        }
    }

// これは Web API を呼び出して、現在のユーザーの // JWT トークンを送信する方法です

public async Task<IList<Profile>> GetProfiles()
        {   
            SearchInProgress = true;
            NotifyStateChanged();

            var token = signInManager.getToken();
            if (token == null) {
                throw new ArgumentNullException(nameof(AppState)); //"No token";
            }

            this.http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);

            // .set('Content-Type', 'application/json')
            // this.http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);

            Profiles = await this.http.GetJsonAsync<Profile[]>("/api/Profiles");


            SearchInProgress = false;
            NotifyStateChanged();
        } 

// また、次のようにクライアントで Startup クラスを設定する必要があります。

public void ConfigureServices(IServiceCollection services)
    {
        // Add Blazor.Extensions.Storage
       // Both SessionStorage and LocalStorage are registered
       // https://github.com/BlazorExtensions/Storage
       **services.AddStorage();**

      ...
    }

// 一般的に言えば、これはクライアントで行う必要があることです。// サーバー上には、JWT トークンを生成する機能を持つアカウント コントローラーなどのメソッドが必要です。JWT ミドルウェアを構成して、必要な属性でコントローラーに注釈を付ける必要があります。実例:

[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]  

等々...

お役に立てれば...

于 2018-10-08T02:46:25.653 に答える