主頁 > .NET開發 > 使用WebApi和Asp.Net Core Identity 認證 Blazor WebAssembly(Blazor客戶端應用)

使用WebApi和Asp.Net Core Identity 認證 Blazor WebAssembly(Blazor客戶端應用)

2020-09-21 15:52:26 .NET開發

原文:https://chrissainty.com/securing-your-blazor-apps-authentication-with-clientside-blazor-using-webapi-aspnet-core-identity/

由于Blazor框架已經有所更新,翻譯中有些內容我根據實際情況做了更改,

設定:創建解決方案

選擇Blazor應用

專案名稱

選擇Blazor WebAssembly App(這里要勾選Asp.Net Core Host),如果找不到Blazor WebAssembly App,請先在命令列執行以下命令:

dotnet new -i Microsoft.AspNetCore.Blazor.Templates::3.1.0-preview1.19508.20

解決方案創建之后,我們將開始對AuthenticationWithBlazorWebAssembly.Server這個專案進行一些更改,

配置WebAPI

在配置WebAPI之前我先安裝一些NuGet包:

    <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="3.0.0" />
    <PackageReference Include="Microsoft.AspNetCore.Blazor.Server" Version="3.0.0-preview9.19465.2" />
    <PackageReference Include="Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore" Version="3.0.0" />
    <PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="3.0.0" />
    <PackageReference Include="Microsoft.AspNetCore.Identity.UI" Version="3.0.0" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="3.0.0" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="3.0.0">
    <PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="3.0.0" />

設定Identity資料庫:連接字串

在進行任何設定之前,資料庫方面需要一個連接字串,這通常是保存在appsettings.json中的,但Blazor托管模版并未提供此檔案,所以我們需要手動添加此檔案,

在AuthenticationWithBlazorWebAssembly.Server專案右鍵添加 -> 新建項,然后選擇應用設定檔案

{
  "ConnectionStrings": {
    "DefaultConnection": "Server=(localdb)\\MSSQLLocalDB;Database=AuthenticationWithBlazorWebAssembly;Trusted_Connection=True;MultipleActiveResultSets=true"
  }
}

該檔案帶有一個已經設定好的連接字串,你可以隨時將其指向需要的地方,我們只需要添加一個資料庫名就可以了,其余的保持默認值,

設定Identity資料庫:DbContext

在AuthenticationWithBlazorWebAssembly.Server專案跟目錄創建一個名為Data的目錄,然后使用下面代碼添加一個名為ApplicationDbContext的類檔案,

    public class ApplicationDbContext : IdentityDbContext
    {
        public ApplicationDbContext(DbContextOptions options) : base(options) {
        }
    }

 因為我們使用Identity需要將資訊存盤在資料庫中,所以我們不是從DbContext繼承,而是從IdentityDbContext繼承,IdentityDbContext基類包含EF配置管理Identity資料庫表需要的所有配置,

設定Identity資料庫:注冊服務

Startup類中,我們需要添加一個建構式,接收IConfiguration引數和一個屬性來存盤它,IConfiguration允許我們訪問appsettings.json檔案,如:連接字串,

 

        public IConfiguration Configuration { get; }

        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

接下來我們將以下代碼添加到ConfigureServices方法的頂部,

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<ApplicationDbContext>(options =>
                options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

            services.AddDefaultIdentity<IdentityUser>()
                .AddEntityFrameworkStores<ApplicationDbContext>();

      //這里省略掉其他代碼
        }

這里兩行代碼將ApplicationDbContext添加到服務集合中,然后為ASP.NET Core Identity注冊各種服務并通過ApplicationDbContext使用Entity Framework作為資料存盤,

設定Identity資料庫:創建資料庫

現在可以為資料庫創建初始遷移,在程式包管理器控制臺運行以下命令,

Add-Migration CreateIdentitySchema -o Data/Migations

命令運行完成,你應該能在DataMigrations檔案夾中看到遷移檔案,在控制臺中運行命令Update-Database將遷移應用到資料庫,

在運行遷移命令時遇到任何問題,請確保在程式包管理器中選擇AuthenticationWithBlazorWebAssembly.Server專案作為默認專案,

啟用身份驗證:注冊服務

接下來在API中啟用身份驗證,同樣,在ConfigureServices中,在上一節添加的代碼之后添加以下代碼,

public void ConfigureServices(IServiceCollection services)
{
  //這里省略到其他代碼
  services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                .AddJwtBearer(options =>
                {
                    options.TokenValidationParameters = new TokenValidationParameters
                    {
                        ValidateIssuer = true,
                        ValidateAudience = true,
                        ValidateLifetime = true,
                        ValidateIssuerSigningKey = true,
                        ValidIssuer = Configuration["JwtIssuer"],
                        ValidAudience = Configuration["JwtAudience"],
                        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["JwtSecurityKey"]))
                    };
                });
  //這里省略掉其他代碼
}

上面代碼想服務容器添加和設定一些身份驗證所需的服務,然后為JSON Web Tokens(JWT)添加處理程式,并配置接收到的JWTs應該如何驗證,你可以根據需求調整這些設定,

啟用身份驗證:應用程式設定

有一些設定要從appsettings.json檔案中加載,

  • Configuration["JwtIssuer"]
  • Configuration["JwtAudience"]
  • Configuration["JwtSecurityKey"]

我們還未將它們添加到appsettings檔案中,現在添加它們并添加一個設定用來控制令牌的持續時間,稍后我們會使用這個設定,

"JwtSecurityKey": "RANDOM_KEY_MUST_NOT_BE_SHARED",
"JwtIssuer": "https://localhost",
"JwtAudience": "https://localhost",
"JwtExpiryInDays": 1,

保證JwtSecurityKey 的安全是非常重要的,因為這是用來對API產生的令牌簽名的,如果泄露那么你的應用程式將不在安全,

由于我們在本地運行所有內容,所以我將IssuerAudience設定為localhost,如果在生產環境使用它,我們需要將Issuer 設定為API運行的域名,將Audience設定為客戶端應用程式運行的域名,

啟用身份驗證:添加中間件

最后,我們需要在Configure 方法中將必要的中間件添加到管道中,這將在API中啟用身份驗證和授權功能,將以下代碼添加到app.UseEndpoints中間件前面,

app.UseAuthentication();
app.UseAuthorization();

這就是Startup類所需要的所有東西,現在API已經啟用了身份驗證,

你可以通過向WeatherForecastController中的Get方法添加[Authorize]屬性來測驗一切是否正常,然后啟用應用程式并導航到Fetch Data頁面,應該不會加載任何資料,應該會在控制臺中看到401錯誤,

添加賬戶(account)控制器

為了讓人們登錄到我們的應用程式,他們需要能夠注冊,我們將添加一個帳戶控制器,它將負責創建新帳戶,

    [Route("api/[controller]")]
    [ApiController]
    public class AccountsController : ControllerBase
    {
        //private static UserModel LoggedOutUser = new UserModel { IsAuthenticated = false };

        private readonly UserManager<IdentityUser> _userManager;

        public AccountsController(UserManager<IdentityUser> userManager)
        {
            _userManager = userManager;
        }

        [HttpPost]
        public async Task<IActionResult> Post([FromBody]RegisterModel model)
        {
            var newUser = new IdentityUser { UserName = model.Email, Email = model.Email };

            var result = await _userManager.CreateAsync(newUser, model.Password);

            if (!result.Succeeded)
            {
                var errors = result.Errors.Select(x => x.Description);

                return BadRequest(new RegisterResult { Successful = false, Errors = errors });

            }

            return Ok(new RegisterResult { Successful = true });
        }
    }

 

Post操作使用ASP.NET Core Identity從RegisterModel來創建系統的新用戶,

我們還沒用添加注冊模型,現在使用以下代碼添加到AuthenticationWithBlazorWebAssembly.Shared專案中,稍后我們的Blazor應用程式將會使用到它,

    public class RegisterModel
    {
        [Required]
        [EmailAddress]
        [Display(Name = "Email")]
        public string Email { get; set; }

        [Required]
        [StringLength(100, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 6)]
        [DataType(DataType.Password)]
        [Display(Name = "Password")]
        public string Password { get; set; }

        [DataType(DataType.Password)]
        [Display(Name = "Confirm password")]
        [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
        public string ConfirmPassword { get; set; }
    }

如果一切順利,則會回傳一個成功的RegisterResult,否則會回傳一個失敗的RegisterResult,我們一樣將它添加到AuthenticationWithBlazorWebAssembly.Shared專案中,

    public class RegisterResult
    {
        public bool Successful { get; set; }
        public IEnumerable<string> Errors { get; set; }
    }

添加登錄(login)控制器

現在我們有了用戶注冊的方式,我們還需要用戶登錄方式,

 [Route("api/[controller]")]
    [ApiController]
    public class LoginController : ControllerBase
    {
        private readonly IConfiguration _configuration;
        private readonly SignInManager<IdentityUser> _signInManager;

        public LoginController(IConfiguration configuration,
            SignInManager<IdentityUser> signInManager)
        {
            _configuration = configuration;
            _signInManager = signInManager;
        }

        [HttpPost]
        public async Task<IActionResult> Login([FromBody] LoginModel login)
        {
            var result = await _signInManager.PasswordSignInAsync(login.Email, login.Password, false, false);

            if (!result.Succeeded) return BadRequest(new LoginResult { Successful = false, Error = "Username and password are invalid." });

            var claims = new[]
            {
                new Claim(ClaimTypes.Name, login.Email)
            };

            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["JwtSecurityKey"]));
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            var expiry = DateTime.Now.AddDays(Convert.ToInt32(_configuration["JwtExpiryInDays"]));

            var token = new JwtSecurityToken(
                _configuration["JwtIssuer"],
                _configuration["JwtAudience"],
                claims,
                expires: expiry,
                signingCredentials: creds
            );

            return Ok(new LoginResult { Successful = true, Token = new JwtSecurityTokenHandler().WriteToken(token) });
        }
    }

登錄控制器(login controller)使用ASP.NET Core Identity SignInManger驗證用戶名和密碼,如果它們都正確,則生成一個新的JSON Web Token并在LoginResult回傳給客戶端,

像之前一樣,我們需要將LoginModelLoginResult添加到AuthenticationWithBlazorWebAssembly.Shared專案中,

    public class LoginModel
    {
        [Required]
        public string Email { get; set; }

        [Required]
        public string Password { get; set; }

        public bool RememberMe { get; set; }
    }
    public class LoginResult
    {
        public bool Successful { get; set; }
        public string Error { get; set; }
        public string Token { get; set; }
    }

這就是API需要的所有東西,我們現在已經將其配置為通過JSON web tokens進行身份驗證,接下來我們需要為Blazor WebAssembly(客戶端)應用程式添加注冊新用戶和登錄控制器,

配置Blazor客戶端

接下來我們關注Blazor,首先需要安裝Blazored.LocalStorage,我們稍后將需要它在登錄時從API中持久化驗證令牌,

我們還需要在App組件中使用AuthorizeRouteView組件替換RouteView組件(這里需要使用Microsoft.AspNetCore.Components.Authorization NuGet包并在_Imports.razor添加@using Microsoft.AspNetCore.Components.Authorization),

<Router AppAssembly="@typeof(Program).Assembly">
    <Found Context="routeData">
        <AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)" />
    </Found>
    <NotFound>
        <LayoutView Layout="@typeof(MainLayout)">
            <p>Sorry, there's nothing at this address.</p>
        </LayoutView>
    </NotFound>
</Router>

此組件提供型別為Task<AuthenticationState>的級聯引數,AuthorizeView通過使用它來確定當前用戶的身份驗證狀態,

但是任何組件都可以請求引數并使用它來執行程序邏輯,例如:

@page "/"

<button @onclick="@LogUsername">Log username</button>

@code {
    [CascadingParameter]
    private Task<AuthenticationState> authenticationStateTask { get; set; }

    private async Task LogUsername()
    {
        var authState = await authenticationStateTask;
        var user = authState.User;

        if (user.Identity.IsAuthenticated)
        {
            Console.WriteLine($"{user.Identity.Name} is authenticated.");
        }
        else
        {
            Console.WriteLine("The user is NOT authenticated.");
        }
    }
}

創建自定義AuthenticationStateProvider

因為我們使用Blazor WebAssembly,所以我們需要為AuthenticationStateProvider提供自定義實作,因為在客戶端應用程式有太多的選項,所以無法設計一個適用于所有人的默認類,

我們需要重寫GetAuthenticationStateAsync方法,在此方法中,我們需要確定當前用戶是否經過身份驗證,我們還將添加兩個輔助方法,當用戶登錄或注銷時,我們將使用這些方法更新身份驗證狀態,

public class ApiAuthenticationStateProvider : AuthenticationStateProvider
    {
        private readonly HttpClient _httpClient;
        private readonly ILocalStorageService _localStorage;

        public ApiAuthenticationStateProvider(HttpClient httpClient, ILocalStorageService localStorage)
        {
            _httpClient = httpClient;
            _localStorage = localStorage;
        }

        public override async Task<AuthenticationState> GetAuthenticationStateAsync()
        {
            var savedToken = await _localStorage.GetItemAsync<string>("authToken");

            if (string.IsNullOrWhiteSpace(savedToken))
            {
                return new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity()));
            }

            _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", savedToken);

            return new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity(ParseClaimsFromJwt(savedToken), "jwt")));
        }

        public void MarkUserAsAuthenticated(string token)
        {
            var authenticatedUser = new ClaimsPrincipal(new ClaimsIdentity(ParseClaimsFromJwt(token), "jwt"));
            var authState = Task.FromResult(new AuthenticationState(authenticatedUser));
            NotifyAuthenticationStateChanged(authState);
        }

        public void MarkUserAsLoggedOut()
        {
            var anonymousUser = new ClaimsPrincipal(new ClaimsIdentity());
            var authState = Task.FromResult(new AuthenticationState(anonymousUser));
            NotifyAuthenticationStateChanged(authState);
        }

        private IEnumerable<Claim> ParseClaimsFromJwt(string jwt)
        {
            var claims = new List<Claim>();
            var payload = jwt.Split('.')[1];
            var jsonBytes = ParseBase64WithoutPadding(payload);
            var keyValuePairs = JsonSerializer.Deserialize<Dictionary<string, object>>(jsonBytes);

            keyValuePairs.TryGetValue(ClaimTypes.Role, out object roles);

            if (roles != null)
            {
                if (roles.ToString().Trim().StartsWith("["))
                {
                    var parsedRoles = JsonSerializer.Deserialize<string[]>(roles.ToString());

                    foreach (var parsedRole in parsedRoles)
                    {
                        claims.Add(new Claim(ClaimTypes.Role, parsedRole));
                    }
                }
                else
                {
                    claims.Add(new Claim(ClaimTypes.Role, roles.ToString()));
                }

                keyValuePairs.Remove(ClaimTypes.Role);
            }

            claims.AddRange(keyValuePairs.Select(kvp => new Claim(kvp.Key, kvp.Value.ToString())));

            return claims;
        }

        private byte[] ParseBase64WithoutPadding(string base64)
        {
            switch (base64.Length % 4)
            {
                case 2: base64 += "=="; break;
                case 3: base64 += "="; break;
            }
            return Convert.FromBase64String(base64);
        }
    }

這里有很多代碼,讓我們一步一步來分析,

CascadingAuthenticationState組件呼叫GetAuthenticationStateAsync方法來確定當前用戶是否經過驗證,

上面的代碼,我們檢查local storge是否有驗證令牌,如果local storge中沒有令牌,那么我們將回傳一個新的AuthenticationState,其中包含一個空的ClaimsPrincipal,這就說明當前用戶用戶沒有經過身份驗證,

如果有令牌,讀取并設定HttpClient的默認Authorization Header,并回傳一個包含ClaimsPrincipal新的AuthenticationState的令牌宣告,該宣告(Claims)使用ParseClaimsFromJwt方法從令牌中提取,此方法解碼令牌并回傳其中包含的宣告,

MarkUserAsAuthenticated輔助方法用于登錄時呼叫NotifyAuthenticationStateChanged方法,該方法觸發AuthenticationStateChanged事件,這將通過CascadingAuthenticationState組件級聯新的身份驗證狀態,

MarkUserAsLoggedOut用于用戶注銷時,

Auth Service

Auth Service將在組件中注冊用戶并登錄到應用程式和用戶注銷使用,

public class AuthService : IAuthService
    {
        private readonly HttpClient _httpClient;
        private readonly AuthenticationStateProvider _authenticationStateProvider;
        private readonly ILocalStorageService _localStorage;

        public AuthService(HttpClient httpClient,
            AuthenticationStateProvider authenticationStateProvider,
            ILocalStorageService localStorage)
        {
            _httpClient = httpClient;
            _authenticationStateProvider = authenticationStateProvider;
            _localStorage = localStorage;
        }

        public async Task<RegisterResult> Register(RegisterModel registerModel)
        {
            var result = await _httpClient.PostJsonAsync<RegisterResult>("api/accounts", registerModel);

            return result;
        }

        public async Task<LoginResult> Login(LoginModel loginModel)
        {
            var loginAsJson = JsonSerializer.Serialize(loginModel);
            var response = await _httpClient.PostAsync("api/Login", new StringContent(loginAsJson, Encoding.UTF8, "application/json"));
            var loginResult = JsonSerializer.Deserialize<LoginResult>(await response.Content.ReadAsStringAsync(), new JsonSerializerOptions { PropertyNameCaseInsensitive = true });

            if (!response.IsSuccessStatusCode)
            {
                return loginResult;
            }

            await _localStorage.SetItemAsync("authToken", loginResult.Token);
            ((ApiAuthenticationStateProvider)_authenticationStateProvider).MarkUserAsAuthenticated(loginResult.Token);
            _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", loginResult.Token);

            return loginResult;
        }

        public async Task Logout()
        {
            await _localStorage.RemoveItemAsync("authToken");
            ((ApiAuthenticationStateProvider)_authenticationStateProvider).MarkUserAsLoggedOut();
            _httpClient.DefaultRequestHeaders.Authorization = null;
        }
    }

Register方法提交registerModel給accounts controller并回傳RegisterResult給呼叫者,

Login 方法類似于Register 方法,它將LoginModel 發送給login controller,但是,當回傳一個成功的結果時,它將回傳一個授權令牌并持久化到local storge,

最后我們呼叫ApiAuthenticationStateProvider上的方法MarkUserAsAuthenticated ,設定HttpClient的默認authorization header,

Logout 這個方法就是執行與Login 方法相反的操作,

注冊組件(Register Component)

我們已經到了最后階段了,現在我們可以將注意力轉向UI,并創建一個允許人們在站點注冊的組件,

@page "/register"
@inject IAuthService AuthService
@inject NavigationManager NavigationManager

<h1>Register</h1>

@if (ShowErrors) {
    <div class="alert alert-danger" role="alert">
        @foreach (var error in Errors) {
            <p>@error</p>
        }
    </div>
}

<div class="card">
    <div class="card-body">
        <h5 class="card-title">Please enter your details</h5>
        <EditForm Model="RegisterModel" OnValidSubmit="HandleRegistration">
            <DataAnnotationsValidator />
            <ValidationSummary />

            <div class="form-group">
                <label for="email">Email address</label>
                <InputText Id="email" class="form-control" @bind-Value=https://www.cnblogs.com/chen8854/p/"RegisterModel.Email" />
                <ValidationMessage For="@(() => RegisterModel.Email)" />
            </div>
            <div class="form-group">
                <label for="password">Password</label>
                <InputText Id="password" type="password" class="form-control" @bind-Value=https://www.cnblogs.com/chen8854/p/"RegisterModel.Password" />
                <ValidationMessage For="@(() => RegisterModel.Password)" />
            </div>
            <div class="form-group">
                <label for="confirmpassword">Confirm Password</label>
                <InputText Id="confirmpassword" type="password" class="form-control" @bind-Value=https://www.cnblogs.com/chen8854/p/"RegisterModel.ConfirmPassword" />
                <ValidationMessage For="@(() => RegisterModel.ConfirmPassword)" />
            </div>
            <button type="submit" class="btn btn-primary">Submit</button>
        </EditForm>
    </div>
</div>

@code {

    private RegisterModel RegisterModel = new RegisterModel();
    private bool ShowErrors;
    private IEnumerable<string> Errors;

    private async Task HandleRegistration() {
        ShowErrors = false;

        var result = await AuthService.Register(RegisterModel);

        if (result.Successful) {
            NavigationManager.NavigateTo("/login");
        } else {
            Errors = result.Errors;
            ShowErrors = true;
        }
    }

}

注冊組件包含一個表單讓用戶輸入他們的電子郵件和密碼,提交表單時,會呼叫AuthService 的方法Register ,如果注冊成功那么用戶會被導航到登錄頁,否則,會將錯誤顯示給用戶,

登錄組件(Login Component)

現在我們可以注冊一個新的帳戶,我們需要能夠登錄,登錄組件將用于此,

@page "/login"
@inject IAuthService AuthService
@inject NavigationManager NavigationManager

<h1>Login</h1>

@if (ShowErrors) {
    <div class="alert alert-danger" role="alert">
        <p>@Error</p>
    </div>
}

<div class="card">
    <div class="card-body">
        <h5 class="card-title">Please enter your details</h5>
        <EditForm Model="loginModel" OnValidSubmit="HandleLogin">
            <DataAnnotationsValidator />
            <ValidationSummary />

            <div class="form-group">
                <label for="email">Email address</label>
                <InputText Id="email" Class="form-control" @bind-Value=https://www.cnblogs.com/chen8854/p/"loginModel.Email" />
                <ValidationMessage For="@(() => loginModel.Email)" />
            </div>
            <div class="form-group">
                <label for="password">Password</label>
                <InputText Id="password" type="password" Class="form-control" @bind-Value=https://www.cnblogs.com/chen8854/p/"loginModel.Password" />
                <ValidationMessage For="@(() => loginModel.Password)" />
            </div>
            <button type="submit" class="btn btn-primary">Submit</button>
        </EditForm>
    </div>
</div>

@code {

    private LoginModel loginModel = new LoginModel();
    private bool ShowErrors;
    private string Error = "";

    private async Task HandleLogin() {
        ShowErrors = false;

        var result = await AuthService.Login(loginModel);

        if (result.Successful) {
            NavigationManager.NavigateTo("/");
        } else {
            Error = result.Error;
            ShowErrors = true;
        }
    }

}

與注冊組件類似的設計,我們也提供一個表單用于用戶輸入電子郵件和密碼,表單提交時,將呼叫AuthService的方法Login,如果登錄成功,用戶將被重定向到主頁,否則將顯示錯誤訊息,

注銷組件(Logout Component)

我們現在可以注冊和登錄,但我們也需要注銷的功能,我用了一個頁面組件來做這個,但是你也可以通過點擊某個地方的按鈕來實作,

@page "/logout"
@inject IAuthService AuthService
@inject NavigationManager NavigationManager


@code {

    protected override async Task OnInitializedAsync() {
        await AuthService.Logout();
        NavigationManager.NavigateTo("/");
    }

}

這個組件沒有用戶界面,當用戶導航到它時,將呼叫AuthService上的方法Logout,然后將用戶重定向回主頁,

添加一個LoginDisplay組件并更新MainLayout組件

最后的任務是添加一個LoginDisplay組件并更新MainLayout 組件,

LoginDisplay 組件與Blazor Server模版一樣,如果未經驗證,它將顯示登錄與注冊鏈接,否則顯示電子郵件和注銷鏈接,

<AuthorizeView>
    <Authorized>
        Hello, @context.User.Identity.Name!
        <a href=https://www.cnblogs.com/chen8854/p/"/logout">Log out</a>
    </Authorized>
    <NotAuthorized>
        <a href=https://www.cnblogs.com/chen8854/p/"/register">Register</a>
        <a href=https://www.cnblogs.com/chen8854/p/"/login">Log in</a>
    </NotAuthorized>
</AuthorizeView>

我們現在只需要更新MainLayout組件,

@inherits LayoutComponentBase

<div class="sidebar">
    <NavMenu />
</div>

<div class="main">
    <div class="top-row px-4">
        <LoginDisplay />
        <a href=https://www.cnblogs.com/chen8854/p/"http://blazor.net" target="_blank" class="ml-md-auto">About</a>
    </div>

    <div class="content px-4">
        @Body
    </div>
</div>

注冊服務(Registering Services)

最后在Startup類中注冊服務,

            services.AddBlazoredLocalStorage();
            services.AddAuthorizationCore();
            services.AddScoped<AuthenticationStateProvider, ApiAuthenticationStateProvider>();
            services.AddScoped<IAuthService, AuthService>();

如果一切都按計劃進行,那么你應該得到這樣的結果,

總結

這篇文章展示了如何WebAPI和ASP.NET Core Identity創建一個帶有身份驗證的Blazor WebAssembly(Blazor客戶端)應用程式,

展示WebAPI如何處理和簽發令牌(JSON web tokens),以及如何設定各種控制器操作來為客戶端應用程式提供服務,最后,展示如何配置Blazor來使用API和它簽發的令牌來設定應用的身份驗證狀態,

最后也提供我學習本文跟隨作者所寫的原始碼(GITHUB),

轉載請註明出處,本文鏈接:https://www.uj5u.com/net/98059.html

標籤:.NET Core

上一篇:DotNet Core中使用RabbitMQ

下一篇:Asp.Net Core中配置使用Kindeditor富文本編輯器實作圖片上傳和截圖上傳及檔案管理和上傳(開源代碼.net core3.0)

標籤雲
其他(157675) Python(38076) JavaScript(25376) Java(17977) C(15215) 區塊鏈(8255) C#(7972) AI(7469) 爪哇(7425) MySQL(7132) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5869) 数组(5741) R(5409) Linux(5327) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4554) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2429) ASP.NET(2402) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) 功能(1967) .NET技术(1958) Web開發(1951) python-3.x(1918) HtmlCss(1915) 弹簧靴(1913) C++(1909) xml(1889) PostgreSQL(1872) .NETCore(1853) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • WebAPI簡介

    Web體系結構: 有三個核心:資源(resource),URL(統一資源識別符號)和表示 他們的關系是這樣的:一個資源由一個URL進行標識,HTTP客戶端使用URL定位資源,表示是從資源回傳資料,媒體型別是資源回傳的資料格式。 接下來我們說下HTTP. HTTP協議的系統是一種無狀態的方式,使用請求/ ......

    uj5u.com 2020-09-09 22:07:47 more
  • asp.net core 3.1 入口:Program.cs中的Main函式

    本文分析Program.cs 中Main()函式中代碼的運行順序分析asp.net core程式的啟動,重點不是剖析原始碼,而是理清程式開始時執行的順序。到呼叫了哪些實體,哪些法方。asp.net core 3.1 的程式入口在專案Program.cs檔案里,如下。ususing System; us ......

    uj5u.com 2020-09-09 22:07:49 more
  • asp.net網站作為websocket服務端的應用該如何寫

    最近被websocket的一個問題困擾了很久,有一個需求是在web網站中搭建websocket服務。客戶端通過網頁與服務器建立連接,然后服務器根據ip給客戶端網頁發送資訊。 其實,這個需求并不難,只是剛開始對websocket的內容不太了解。上網搜索了一下,有通過asp.net core 實作的、有 ......

    uj5u.com 2020-09-09 22:08:02 more
  • ASP.NET 開源匯入匯出庫Magicodes.IE Docker中使用

    Magicodes.IE在Docker中使用 更新歷史 2019.02.13 【Nuget】版本更新到2.0.2 【匯入】修復單列匯入的Bug,單元測驗“OneColumnImporter_Test”。問題見(https://github.com/dotnetcore/Magicodes.IE/is ......

    uj5u.com 2020-09-09 22:08:05 more
  • 在webform中使用ajax

    如果你用過Asp.net webform, 說明你也算是.NET 開發的老兵了。WEBform應該是2011 2013左右,當時還用visual studio 2005、 visual studio 2008。后來基本都用的是MVC。 如果是新開發的專案,估計沒人會用webform技術。但是有些舊版 ......

    uj5u.com 2020-09-09 22:08:50 more
  • iis添加asp.net網站,訪問提示:由于擴展配置問題而無法提供您請求的

    今天在iis服務器配置asp.net網站,遇到一個問題,記錄一下: 問題:由于擴展配置問題而無法提供您請求的頁面。如果該頁面是腳本,請添加處理程式。如果應下載檔案,請添加 MIME 映射。 WindowServer2012服務器,添加角色安裝完.netframework和iis之后,運行aspx頁面 ......

    uj5u.com 2020-09-09 22:10:00 more
  • WebAPI-處理架構

    帶著問題去思考,大家好! 問題1:HTTP請求和回傳相應的HTTP回應資訊之間發生了什么? 1:首先是最底層,托管層,位于WebAPI和底層HTTP堆疊之間 2:其次是 訊息處理程式管道層,這里比如日志和快取。OWIN的參考是將訊息處理程式管道的一些功能下移到堆疊下端的OWIN中間件了。 3:控制器處理 ......

    uj5u.com 2020-09-09 22:11:13 more
  • 微信門戶開發框架-使用指導說明書

    微信門戶應用管理系統,采用基于 MVC + Bootstrap + Ajax + Enterprise Library的技術路線,界面層采用Boostrap + Metronic組合的前端框架,資料訪問層支持Oracle、SQLServer、MySQL、PostgreSQL等資料庫。框架以MVC5,... ......

    uj5u.com 2020-09-09 22:15:18 more
  • WebAPI-HTTP編程模型

    帶著問題去思考,大家好!它是什么?它包含什么?它能干什么? 訊息 HTTP編程模型的核心就是訊息抽象,表示為:HttPRequestMessage,HttpResponseMessage.用于客戶端和服務端之間交換請求和回應訊息。 HttpMethod類包含了一組靜態屬性: private stat ......

    uj5u.com 2020-09-09 22:15:23 more
  • 部署WebApi隨筆

    一、跨域 NuGet參考Microsoft.AspNet.WebApi.Cors WebApiConfig.cs中配置: // Web API 配置和服務 config.EnableCors(new EnableCorsAttribute("*", "*", "*")); 二、清除默認回傳XML格式 ......

    uj5u.com 2020-09-09 22:15:48 more
最新发布
  • C#多執行緒學習(二) 如何操縱一個執行緒

    <a href="https://www.cnblogs.com/x-zhi/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/2943582/20220801082530.png" alt="" /></...

    uj5u.com 2023-04-19 09:17:20 more
  • C#多執行緒學習(二) 如何操縱一個執行緒

    C#多執行緒學習(二) 如何操縱一個執行緒 執行緒學習第一篇:C#多執行緒學習(一) 多執行緒的相關概念 下面我們就動手來創建一個執行緒,使用Thread類創建執行緒時,只需提供執行緒入口即可。(執行緒入口使程式知道該讓這個執行緒干什么事) 在C#中,執行緒入口是通過ThreadStart代理(delegate)來提供的 ......

    uj5u.com 2023-04-19 09:16:49 more
  • 記一次 .NET某醫療器械清洗系統 卡死分析

    <a href="https://www.cnblogs.com/huangxincheng/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/214741/20200614104537.png" alt="" /&g...

    uj5u.com 2023-04-18 08:39:04 more
  • 記一次 .NET某醫療器械清洗系統 卡死分析

    一:背景 1. 講故事 前段時間協助訓練營里的一位朋友分析了一個程式卡死的問題,回過頭來看這個案例比較經典,這篇稍微整理一下供后來者少踩坑吧。 二:WinDbg 分析 1. 為什么會卡死 因為是表單程式,理所當然就是看主執行緒此時正在做什么? 可以用 ~0s ; k 看一下便知。 0:000> k # ......

    uj5u.com 2023-04-18 08:33:10 more
  • SignalR, No Connection with that ID,IIS

    <a href="https://www.cnblogs.com/smartstar/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/u36196.jpg" alt="" /></a>...

    uj5u.com 2023-03-30 17:21:52 more
  • 一次對pool的誤用導致的.net頻繁gc的診斷分析

    <a href="https://www.cnblogs.com/dotnet-diagnostic/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/3115652/20230225090434.png" alt=""...

    uj5u.com 2023-03-28 10:15:33 more
  • 一次對pool的誤用導致的.net頻繁gc的診斷分析

    <a href="https://www.cnblogs.com/dotnet-diagnostic/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/3115652/20230225090434.png" alt=""...

    uj5u.com 2023-03-28 10:13:31 more
  • C#遍歷指定檔案夾中所有檔案的3種方法

    <a href="https://www.cnblogs.com/xbhp/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/957602/20230310105611.png" alt="" /></a&...

    uj5u.com 2023-03-27 14:46:55 more
  • C#/VB.NET:如何將PDF轉為PDF/A

    <a href="https://www.cnblogs.com/Carina-baby/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/2859233/20220427162558.png" alt="" />...

    uj5u.com 2023-03-27 14:46:35 more
  • 武裝你的WEBAPI-OData聚合查詢

    <a href="https://www.cnblogs.com/podolski/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/616093/20140323000327.png" alt="" /><...

    uj5u.com 2023-03-27 14:46:16 more