我做了以下工作(它应该工作,但它不工作),没有重定向,没有错误,没有什么,它只是显示页面没有auth,我做了什么错误?
ASP.NET Core3.1Bazor
Microsoft.AspNetCore.Authentication.OpenIdConnect 步骤1.安装-包
步骤2.编辑Statup.cs
在"ConfigurationServices“下添加
services.AddAuthentication(options =>
{
options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
})
.AddCookie()
.AddOpenIdConnect(OpenIdConnectDefaults.AuthenticationScheme, options =>
{
options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.Authority = "http://localhost:5000";
options.RequireHttpsMetadata = false; //false for development only
options.ClientId = "mywebclient";
options.ResponseType = "code";
options.UsePkce = true;
options.Scope.Add("profile");
options.Scope.Add("offline_access");
options.SaveTokens = true;
});在“配置”下添加
...
services.AddAuthorization();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
....步骤3.向blazor页面添加属性授权
@page "/item"
@attribute [Authorize] 发布于 2020-01-09 22:17:57
你的代码有一些毛病..。主要问题是,您的代码没有提供身份验证质询请求机制,从而允许重定向到身份验证代理(如IdentityServer )。这只有在HttpContext中才能实现,SignalR (Blazor )中没有这种功能。为了解决这个问题,我们将添加几个HttpContext可用的Razor页面。答案更多..。
以下是这个问题的完整和可行的解决办法:
<AuthorizeView> <Authorized> <a href="logout">Hello, @context.User.Identity.Name !</a> <form method="get" action="logout"> <button type="submit" class="nav-link btn btn-link">Log out</button> </form> </Authorized> <NotAuthorized> <a href="login?redirectUri=/">Log in</a> </NotAuthorized> </AuthorizeView>
将LoginDisplay组件添加到MainLayout组件中,就在About锚元素的上方,如下面的<div class="top-row px-4"> <LoginDisplay /> <a href="https://learn.microsoft.com/aspnet/" target="_blank">About</a> </div>注意:为了将登录请求和注销请求重定向到IdentityServer,我们必须创建两个Razor页面,如下所示: 1.创建login页面Login.cshtml (Login.cshtml.cs),并将它们放在pages文件夹中,如下所示:
Login.cshtml.cs
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.IdentityModel.Tokens;
public class LoginModel : PageModel
{
public async Task OnGet(string redirectUri)
{
await HttpContext.ChallengeAsync("oidc", new
AuthenticationProperties { RedirectUri = redirectUri } );
}
}此代码启动在Startup类中定义的Open身份验证方案的挑战。
using Microsoft.AspNetCore.Authentication;
public class LogoutModel : PageModel { public async Task<IActionResult> OnGetAsync() { await HttpContext.SignOutAsync(); return Redirect("/"); } }这段代码指示你退出,将你重定向到你的Blazor应用程序的主页。
用以下代码替换App.razor中的代码:
@inject NavigationManager NavigationManager
<CascadingAuthenticationState>
<Router AppAssembly="@typeof(Program).Assembly">
<Found Context="routeData">
<AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)">
<NotAuthorized>
@{
var returnUrl = NavigationManager.ToBaseRelativePath(NavigationManager.Uri);
NavigationManager.NavigateTo($"login?redirectUri={returnUrl}", forceLoad: true);
}
</NotAuthorized>
<Authorizing>
Wait...
</Authorizing>
</AuthorizeRouteView>
</Found>
<NotFound>
<LayoutView Layout="@typeof(MainLayout)">
<p>Sorry, there's nothing at this address.</p>
</LayoutView>
</NotFound>
</Router>
</CascadingAuthenticationState>将Startup类中的代码替换为以下代码:
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc.Authorization;
using System.Net.Http;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.IdentityModel.Tokens;
using Microsoft.IdentityModel.Protocols.OpenIdConnect;
using Microsoft.IdentityModel.Logging;
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
services.AddRazorPages();
services.AddServerSideBlazor();
services.AddAuthorizationCore();
services.AddSingleton<WeatherForecastService>();
services.AddAuthentication(sharedOptions =>
{
sharedOptions.DefaultAuthenticateScheme =
CookieAuthenticationDefaults.AuthenticationScheme;
sharedOptions.DefaultSignInScheme =
CookieAuthenticationDefaults.AuthenticationScheme;
sharedOptions.DefaultChallengeScheme =
OpenIdConnectDefaults.AuthenticationScheme;
})
.AddCookie()
.AddOpenIdConnect("oidc", options =>
{
options.Authority = "https://demo.identityserver.io/";
options.ClientId = "interactive.confidential.short";
options.ClientSecret = "secret";
options.ResponseType = "code";
options.SaveTokens = true;
options.GetClaimsFromUserInfoEndpoint = true;
options.UseTokenLifetime = false;
options.Scope.Add("openid");
options.Scope.Add("profile");
options.TokenValidationParameters = new
TokenValidationParameters
{
NameClaimType = "name"
};
options.Events = new OpenIdConnectEvents
{
OnAccessDenied = context =>
{
context.HandleResponse();
context.Response.Redirect("/");
return Task.CompletedTask;
}
};
});
}
// This method gets called by the runtime. Use this method to configure
the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapBlazorHub();
endpoints.MapFallbackToPage("/_Host");
});
}
}重要:在上面的所有代码示例中,您必须根据需要添加使用语句。其中大多数都是默认提供的。这里提供的使用是启用身份验证和授权流所必需的。
注意:当您在试用应用程序时,您应该清除浏览数据,如果您想重定向到身份服务器的登录页面,否则浏览器可能会使用缓存的数据。记住,这是一个基于曲奇的授权机制.
请注意,像这里这样创建登录机制并不能使您的应用程序比以前更加安全。任何用户都可以访问您的web资源,而不需要登录。为了保护网站的部分安全,您还必须实现授权,通常,通过身份验证的用户有权访问安全资源,除非实现了其他措施,如角色、策略等。下面是如何从未经授权的用户保护Fetchdata页面的演示(同样,经过身份验证的用户被认为有权访问Fetchdata页面)。
@attribute [Authorize]当未经身份验证的用户试图访问Fetchdata页面时,将执行AuthorizeRouteView.NotAuthorized委托属性,因此我们可以添加一些代码将用户重定向到相同身份服务器的登录页以进行身份验证。<NotAuthorized> @{ var returnUrl = NavigationManager.ToBaseRelativePath(NavigationManager.Uri); NavigationManager.NavigateTo($"login?redirectUri= {returnUrl}", forceLoad: true); } </NotAuthorized>这将检索您试图访问的上一页的url,即Fetchdata页,然后导航到执行密码挑战的Login Razor页面,即将用户重定向到标识服务器的登录页以进行身份验证。
用户通过身份验证后,他将被重定向到Fetchdata页面。
祝你好运。
发布于 2020-01-08 07:29:37
目前还没有官方支持的IdentityServer和OIDC流在布拉泽。我已经在aspnetcore github上使用了已打开 几个 问题,但是它们总是在没有正确答案的情况下关闭。
我目前发现的最佳来源是以下博客:
https://mcguirev10.com/2019/12/15/blazor-authentication-with-openid-connect.html
https://wellsb.com/csharp/aspnet/blazor-httpclientfactory-and-web-api/
发布于 2020-01-08 04:19:17
它只会显示页面而不显示,我做错了什么?
很可能你没有为你的应用程序添加一个AuthorizeRouteView。请注意,@attribute [Authorize]只是一个为该页面组件添加[AuthorizeAttribute]的指令。要启用路由授权,您需要:
<CascadingAuthenticationState><AuthorizeRouteView>以启用路由授权。请参阅官方文件<AuthorizeView>进行普通组件授权。添加<NotAuthorized>以在未授权时显示组件。并在授权用户的同时使用Authorizing显示组件。请参阅官方文件例如,您的BlazorApp.razor可能如下所示:
<CascadingAuthenticationState>
<Router AppAssembly="@typeof(Program).Assembly">
<Found Context="routeData">
<AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)" >
<NotAuthorized>
You're not allowed!
</NotAuthorized>
<Authorizing>
<h1>Authentication in progress</h1>
</Authorizing>
</AuthorizeRouteView>
</Found>
<NotFound>
<LayoutView Layout="@typeof(MainLayout)">
<p>Sorry, there's nothing at this address.</p>
</LayoutView>
</NotFound>
</Router>
</CascadingAuthenticationState>https://stackoverflow.com/questions/59638965
复制相似问题