简体   繁体   English

blazor 服务器身份验证不适用于 httpcontext cookie

[英]blazor server authentication dont work with httpcontext cookie

i want authorize user with api controller and save claims to cookie我想授权用户 api controller 并将声明保存到 cookie

and after that authorize my blazor server with it然后用它授权我的 blazor 服务器

this is my code for api Controller这是我的代码 api Controller

public async Task<IActionResult> Login([FromBody] userPassModel userPass)
        {
            try
            {

                DIMAuthUser user = await authService.GetUser(userPass.UserName);
                if (user == null) return Unauthorized();
                bool resCheck = await authService.CheckUserCredentialAsync(userPass.UserName, userPass.Password);
                if (resCheck == false) return Unauthorized();
                ClaimsPrincipal principal = new ClaimsPrincipal(new ClaimsIdentity(user.AllSettedClaims, CookieAuthenticationDefaults.AuthenticationScheme));
                await HttpContext.SignInAsync(principal);
                return Ok();
            }
            catch (Exception ex)
            {
                Log.Error(ex.Message,this);
                return StatusCode(500);
            }
        }

user successfully loggin and cookie sent back to user... but when i want redirect login page to main page my blazor server said not authorize用户成功登录并将 cookie 发送回用户...但是当我想将登录页面重定向到主页时,我的 blazor 服务器说未授权

this is login page code这是登录页面代码

async Task OnClickLogin()
        {
            if (string.IsNullOrWhiteSpace(username)) return;
            if (string.IsNullOrWhiteSpace(password)) return;
            
            HttpResponseMessage mess = await HttpClient.PostAsJsonAsync( "/api/Athentication/login", new userPassModel
            {
                UserName=username,
                Password=password
            });
            if (mess.IsSuccessStatusCode)
            {
                if (mess.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    NavigationManager.NavigateTo("/");
                    return;
                }
                else if (mess.StatusCode == System.Net.HttpStatusCode.Unauthorized)
                {
                    await SweetAlert2Service.ShowWarning("user or pass incorrect");
                    return;
                }
            }
            await SweetAlert2Service.ShowWarning("somthing went wrong");
        }

and this is main poge code这是主要的 poge 代码

@page "/"
@attribute [Authorize]
<AuthorizeView>
    <Authorized>
        Authed
    </Authorized>
    <NotAuthorized>
        Noted
    </NotAuthorized>
</AuthorizeView>
<h1>INDEX</h1>

and this is program.cs这是 program.cs

builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie();
app.UseStaticFiles();
app.UseRouting();

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

app.MapControllers();

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

app.Run();

after successful login with controller and redirected to main page show me "Noted"使用 controller 成功登录并重定向到主页后显示“已注意到”

i want user identity in cookie that can log activity in middleware with httpcontext...我希望 cookie 中的用户身份可以使用 httpcontext 在中间件中记录活动...

Blazor Don't Completely access To httpContext So if You Want user Cookie Authentication that use httpcontex don't Make Login page with blazor ( make login page with Razor Or MVC Page ) Blazor 不要完全访问 httpContext 因此,如果您想要使用 httpcontex 的用户 Cookie 身份验证,请不要使用 blazor 创建登录页面(使用 Razor 或 MVC 页面创建登录页面)

in previously i sent authentication request from blazor page to controller and after that i navigate user to index, that is wrong...之前我将身份验证请求从 blazor 页面发送到 controller 然后我将用户导航到索引,这是错误的......

before every blazor page, authentication process must be done and after that navigate user to blazor page...在每个 blazor 页面之前,必须完成身份验证过程,然后将用户导航到 blazor 页面...

so i must authentication process out of blazor pages and after that navigate to blazor pages所以我必须对 blazor 页进行身份验证,然后导航到 blazor 页

so:所以:

i make a razor page in my Blazor project:我在我的 Blazor 项目中制作了一个 razor 页面:

在此处输入图像描述

and all athentication logic added to it以及添加到其中的所有认证逻辑

public async Task<IActionResult> OnPost()
        {
            string username = Request.Form["username"].FirstOrDefault();
            string password = Request.Form["password"].FirstOrDefault();
            if(string.IsNullOrWhiteSpace(username) || string.IsNullOrWhiteSpace(password)) return Page();
            DIMAuthUser user = await authService.GetUser(username);
            if (user == null)
            {
                AuthResult = "Wrong User";
                return Page();
            }
            bool resCred = await authService.CheckUserCredentialAsync(username, password);
            if (resCred == false)
            {
                AuthResult = "Wrong USer Or Password";
                return Page();
            }
            else
            {
                await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme,
                    user.ClaimsPrincipal);
                authService.AuthedUser = user;
                Log.Logger
                    .ForContext("Username",user.UserName)
                    .Information($"{user.UserName} Logged In ...",this);
                return Redirect("/");
            }
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM