受欢迎的博客标签

ASP.NET Core Blazor 8.x(Server-side)-Authentication and Authorization(wjl)

Published

Table of Contents

.Net 8.x

 

 

step 1: login

\Presentation\WeiXinAdmin\Pages\Login.cshtml.cs

 public async Task<IActionResult> OnGetAsync(string paramUsername, string paramPassword)
        {

           

            string returnUrl = Url.Content("~/");
            try
            {
                // Clear the existing external cookie
                await HttpContext
                    .SignOutAsync(
                    CookieAuthenticationDefaults.AuthenticationScheme);
            }
            catch { }

            if (paramUsername == "[email protected]")
            {

                var claims = new List<Claim>
            {
                new Claim(ClaimTypes.Name, paramUsername),
                new Claim(ClaimTypes.Role, "Administrator"),
            };
                var claimsIdentity = new ClaimsIdentity(
                    claims, CookieAuthenticationDefaults.AuthenticationScheme);
                var authProperties = new AuthenticationProperties
                {
                    IsPersistent = true,
                    RedirectUri = this.Request.Host.Value
                };
                try
                {
                    await HttpContext.SignInAsync(
                    CookieAuthenticationDefaults.AuthenticationScheme,
                    new ClaimsPrincipal(claimsIdentity),
                    authProperties);
                }
                catch (Exception ex)
                {
                    string error = ex.Message;
                }
            }

            return LocalRedirect(returnUrl);
        }

step 2: add Application Authentication cookie  

Program.cs

app.UseStaticFiles();

app.UseRouting();

// ******
// BLAZOR COOKIE Auth Code (begin)
app.UseCookiePolicy();
app.UseAuthentication();
app.UseAuthorization();
// BLAZOR COOKIE Auth Code (end)
// ******

app.MapBlazorHub();
app.MapFallbackToPage("/_Host");

app.Run();

 

 

step 3: add <CascadingAuthenticationState>

 you need to wrap a <CascadingAuthenticationState> around some part of your UI tree, in App.razor as follows:

\src\Presentation\WeiXinAdmin\App.razor

<CascadingAuthenticationState>
    <Router AppAssembly="@typeof(Program).Assembly">
        <Found Context="routeData">
            <AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)">
                <NotAuthorized>
                    <h1>Error</h1>
                    <h1>錯誤</h1>
                    <p>尚未登入或者登入的使用者帳號沒有權限使用這個頁面</p>
                </NotAuthorized>
                @*<Authorizing>
                        <h1>Authentication in progress</h1>
                        <p>Only visible while authentication is in progress.</p>
                    </Authorizing>*@
            </AuthorizeRouteView>
        </Found>
        <NotFound>
            <LayoutView Layout="@typeof(MainLayout)">
                <p>Sorry, there's nothing at this address.</p>
            </LayoutView>
        </NotFound>
    </Router>
</CascadingAuthenticationState>

step 4:  

src\Presentation\WeiXinAdmin\Pages\FetchData.razor

@page "/fetchdata"
@using Microsoft.AspNetCore.Authorization
@attribute [Authorize]

src\Presentation\WeiXinAdmin\Pages\Account\Account.razor

@page "/Pages/Account"

@using Microsoft.AspNetCore.Authorization
@attribute [Authorize(Roles ="Administrator")]

 

AuthorizeView

path:\Shared\NavMenu.razor

  <AuthorizeView Roles="Administrator">
            <li class="nav-item px-3">
                <NavLink class="nav-link" href="Pages/Account">
                    <span class="oi oi-list-rich" aria-hidden="true"></span> Account
                </NavLink>
            </li>
            <li class="nav-item px-3">
                <NavLink class="nav-link" href="Pages/User/List">
                    <span class="oi oi-list-rich" aria-hidden="true"></span> User(微信公众号用户)
                </NavLink>
            </li>
        </AuthorizeView>

 

create LoginComponent.razor

G:\x\src\Presentation\WeiXin.Admin\Components\Account\LoginComponent.razor

F:\*\src\Presentation\WeiXin.Admin\Components\Account\LoginComponent.razor

@using Microsoft.AspNetCore.Components.Authorization
@inject AuthenticationStateProvider AuthenticationStateProvider





<AuthorizeView>
    <Authorized>
        <b>Hello, @context.User.Identity.Name!</b>
        <a class="ml-md-auto btn btn-primary"
           href="/logout?returnUrl=/"
           target="_top">Logout</a>
    </Authorized>
    <NotAuthorized>
        <input type="text"
               placeholder="User Name"
               @bind="@Username" />
        &nbsp;&nbsp;
        <input type="password"
               placeholder="Password"
               @bind="@Password" />
        <a class="ml-md-auto btn btn-primary"
           href="/login?paramUsername=@Username&paramPassword=@Password"
           target="_top">Login</a>
    </NotAuthorized>
</AuthorizeView>
@code {
    string Username = "";
    string Password = "";
}

 

 <AuthorizeView>
     <Authorized>
         <div class="nav-item px-3">
             <NavLink class="nav-link" href="Account/Manage">
                 <span class="bi bi-person-fill-nav-menu" aria-hidden="true"></span> @context.User.Identity?.Name
             </NavLink>
         </div>
         <div class="nav-item px-3">
             <form action="Account/Logout" method="post">
                 <AntiforgeryToken />
                 <input type="hidden" name="ReturnUrl" value="@currentUrl" />
                 <button type="submit" class="nav-link">
                     <span class="bi bi-arrow-bar-left-nav-menu" aria-hidden="true"></span> Logout
                 </button>
             </form>
         </div>
     </Authorized>
     <NotAuthorized>
         <div class="nav-item px-3">
             <NavLink class="nav-link" href="Account/Register">
                 <span class="bi bi-person-nav-menu" aria-hidden="true"></span> Register
             </NavLink>
         </div>
         <div class="nav-item px-3">
             <NavLink class="nav-link" href="Account/Login">
                 <span class="bi bi-person-badge-nav-menu" aria-hidden="true"></span> Login
             </NavLink>
         </div>
     </NotAuthorized>
 </AuthorizeView>

 

<AuthorizeView Roles="admin, superuser">
    <p>You can only see this if you're an admin or superuser.</p>
</AuthorizeView>

microsoft ASP.NET Core Blazor authentication and authorization

https://docs.microsoft.com/en-us/aspnet/core/security/blazor/?view=aspnetcore-3.0&tabs=visual-studio

 

服务器端Blazor中实现认证和授权

https://juejin.cn/post/7167628806750994439