问题描述
我有一个 blazor 服务器端项目。我的目标是在与真正的 api 通信之前创建模拟 Cookie 身份验证。如果用户未通过身份验证,我想将用户重定向到登录页面。
我的代码点:
AuthenticateController.cs:
[Route("/[controller]")]
[ApiController]
public class AuthenticateController : ControllerBase
{
[HttpPost]
public async Task<ActionResult> Login(UserLoginDto userLoginDto)
{
// Clear the existing external cookie
await HttpContext
.SignOutAsync(
CookieAuthenticationDefaults.AuthenticationScheme);
var identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme);
identity.AddClaim(new Claim(ClaimTypes.Name,userLoginDto.UserName));
identity.AddClaim(new Claim("Token","Ilyas12345"));
await HttpContext.SignInAsync(
CookieAuthenticationDefaults.AuthenticationScheme,new ClaimsPrincipal(identity),new AuthenticationProperties
{
IsPersistent = true,AllowRefresh = true,ExpiresUtc = DateTime.UtcNow.AddDays(1)
}).ConfigureAwait(false);
return Redirect("/");
}
}
login.razor 的代码部分:
@code {
private UserLoginDto user { get; set; }
protected override async Task OnInitializedAsync()
{
user = new UserLoginDto();
}
private async Task UserLogin()
{
http.BaseAddress = new Uri(Navigation.BaseUri);
var res = await http.PostAsync("/authenticate",new StringContent(JsonSerializer.Serialize(user),Encoding.UTF8,"application/json"));
Navigation.Navigateto("dashboard",true);
}
}
我的 startup.cs 配置:
public void ConfigureServices(IServiceCollection services)
{
services.AddRazorPages();
services.AddServerSideBlazor();
services.Configure<CookiePolicyOptions>(options =>
{
options.CheckConsentNeeded = context => false;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie();
services.AddHttpClient();
services.AddHttpClient("api",hc =>
{
hc.BaseAddress = new Uri("http://localhost:5000/");
});
}
public void Configure(IApplicationBuilder app,IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
}
app.UseStaticFiles();
app.UseRouting();
app.UseCookiePolicy();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapBlazorHub();
endpoints.MapFallbackToPage("/_Host");
});
}
app.razor:
<CascadingAuthenticationState>
<Router AppAssembly="@typeof(Program).Assembly">
<Found Context="routeData">
<AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)">
<NotAuthorized>
<RedirectToLogin />
</NotAuthorized>
</AuthorizeRouteView>
</Found>
<NotFound>
<LayoutView Layout="@typeof(MainLayout)">
<p>Sorry,there's nothing at this address.</p>
</LayoutView>
</NotFound>
</Router>
</CascadingAuthenticationState>
RedirectToLogin.razor:
@inject NavigationManager Navigation
@code {
protected override async Task OnInitializedAsync()
{
Navigation.Navigateto("login",true);
}
}
登录事件后:
用户似乎已通过身份验证,但程序总是重定向到登录页面。 你知道这是为什么吗?
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)