如何通过 IdentityServer4 将 OpenId Connect 添加到 ASP.NET 核心服务器端 Blazor Web 应用程序?
How to add OpenIdConnect via IdentityServer4 to ASP.NET Core ServerSide Blazor web app?
我做了以下操作(应该可以,但没有),没有重定向,没有错误,什么都没有,它只是显示没有授权的页面,我做错了什么?
ASP.NET Core 3.1 Blazor
步骤 1. 安装包 Microsoft.AspNetCore.Authentication.OpenIdConnect
步骤 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;
});
在"Configure"下添加
...
services.AddAuthorization();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
....
步骤 3. 将属性授权添加到 blazor 页面
@page "/item"
@attribute [Authorize]
it just displays the page without auth, what am I doing wrong
您可能没有为您的应用添加 AuthorizeRouteView。请注意,@attribute [Authorize]
只是为该页面组件添加 [AuthorizeAttribute]
的指令。要启用路由授权,您需要:
- 在最顶层添加一个
<CascadingAuthenticationState>
- 添加
<AuthorizeRouteView>
以启用路由授权。参见 official docs
- 使用
<AuthorizeView>
进行普通组件授权。添加一个 <NotAuthorized>
以在未授权时显示该组件。并在授权用户时使用 Authorizing
显示组件。参见 official docs
例如,您 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>
Blazor 中尚无对 IdentityServer 和 OIDC 流的官方支持。我已经 opened several issues 在 aspnetcore github 上,但他们总是在没有正确答案的情况下关闭。
目前我找到的最佳资源是以下博客:
https://mcguirev10.com/2019/12/15/blazor-authentication-with-openid-connect.html
https://wellsb.com/csharp/aspnet/blazor-httpclientfactory-and-web-api/
您的代码有几个问题...主要问题是您的代码没有提供身份验证质询请求机制,该机制可以重定向到身份验证代理,例如 IdentityServer。这仅适用于 HttpContext,它在 SignalR(Blazor Server App)中不可用。为了解决这个问题,我们将添加几个 HttpContext 可用的 Razor 页面。更多答案...
以下是问题的完整有效解决方案:
- 创建 Blazor 服务器应用。
- 安装包 Microsoft.AspNetCore.Authentication.OpenIdConnect - 版本 3.1.0
创建一个名为 LoginDisplay (LoginDisplay.razor) 的组件,并将其放在 Shared 文件夹中。 MainLayout组件中使用了该组件
<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 组件,就在关于
锚元素,像这样
<div class="top-row px-4">
<LoginDisplay />
<a href="https://docs.microsoft.com/aspnet/" target="_blank">About</a>
</div>
注意:为了将登录和注销请求重定向到 IdentityServer,我们必须创建两个 Razor 页面,如下所示:
1. 创建一个 Login Razor 页面 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 } );
}
}
此代码开始挑战您在启动 class 中定义的 Open Id Connect 身份验证方案。
创建注销 Razor 页面 Logout.cshtml (Logout.cshtml.cs) 并将它们也放在页面文件夹中:
Logout.cshtml.cs
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 class 中的代码替换为以下代码:
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");
});
}
}
重要提示:在上面的所有代码示例中,您必须根据需要添加 using 语句。其中大部分是默认提供的。此处提供的 using 是启用身份验证和授权流程所必需的。
- 运行 您的应用程序,单击登录按钮进行身份验证。您将被重定向到 IdentityServer 测试服务器,该服务器允许您执行 OIDC 登录。您可以输入用户名:bob 和密码bob,然后单击“确定”按钮后,您将被重定向到您的主页。另请注意,您可以使用外部登录提供程序 Google(试试看)。请注意,在您使用身份服务器登录后,LoginDisplay 组件会显示字符串 "Hello, ".
注意:当您正在试验您的应用程序时,如果您想被重定向到身份服务器的登录页面,您应该清除浏览数据,否则,您的浏览器可能会使用缓存数据。请记住,这是一种基于 cookie 的授权机制...
请注意,按照此处创建的登录机制不会使您的应用比以前更安全。任何用户都无需登录即可访问您的网络资源。为了保护网站的某些部分,您还必须实施授权,通常情况下,经过身份验证的用户被授权访问受保护的资源,除非实施了其他措施,例如角色、策略等。以下是如何进行的演示您可以保护您的 Fetchdata 页面免受未经授权的用户访问(同样,经过身份验证的用户被视为有权访问 Fetchdata 页面)。
- 在 Fetchdata 组件页面的顶部,为 Authorize 属性添加 @attribute 指令,如下所示:
@attribute [Authorize]
当未经身份验证的用户尝试访问 Fetchdata 页面时,将执行 AuthorizeRouteView.NotAuthorized
委托 属性,因此我们可以添加一些代码将用户重定向到同一身份服务器的登录页面以进行身份验证。
NotAuthorized 元素中的代码如下所示:
<NotAuthorized>
@{
var returnUrl =
NavigationManager.ToBaseRelativePath(NavigationManager.Uri);
NavigationManager.NavigateTo($"login?redirectUri=
{returnUrl}", forceLoad: true);
}
</NotAuthorized>
这会检索您尝试访问的最后一个页面的 url,即 Fetchdata 页面,然后导航到执行密码挑战的 Login Razor 页面,即用户被重定向到身份服务器的登录页面进行身份验证。
用户通过身份验证后,他将被重定向到 Fetchdata 页面。
祝你好运...
我做了以下操作(应该可以,但没有),没有重定向,没有错误,什么都没有,它只是显示没有授权的页面,我做错了什么?
ASP.NET Core 3.1 Blazor
步骤 1. 安装包 Microsoft.AspNetCore.Authentication.OpenIdConnect
步骤 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;
});
在"Configure"下添加
...
services.AddAuthorization();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
....
步骤 3. 将属性授权添加到 blazor 页面
@page "/item"
@attribute [Authorize]
it just displays the page without auth, what am I doing wrong
您可能没有为您的应用添加 AuthorizeRouteView。请注意,@attribute [Authorize]
只是为该页面组件添加 [AuthorizeAttribute]
的指令。要启用路由授权,您需要:
- 在最顶层添加一个
<CascadingAuthenticationState>
- 添加
<AuthorizeRouteView>
以启用路由授权。参见 official docs - 使用
<AuthorizeView>
进行普通组件授权。添加一个<NotAuthorized>
以在未授权时显示该组件。并在授权用户时使用Authorizing
显示组件。参见 official docs
例如,您 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>
Blazor 中尚无对 IdentityServer 和 OIDC 流的官方支持。我已经 opened several issues 在 aspnetcore github 上,但他们总是在没有正确答案的情况下关闭。
目前我找到的最佳资源是以下博客:
https://mcguirev10.com/2019/12/15/blazor-authentication-with-openid-connect.html
https://wellsb.com/csharp/aspnet/blazor-httpclientfactory-and-web-api/
您的代码有几个问题...主要问题是您的代码没有提供身份验证质询请求机制,该机制可以重定向到身份验证代理,例如 IdentityServer。这仅适用于 HttpContext,它在 SignalR(Blazor Server App)中不可用。为了解决这个问题,我们将添加几个 HttpContext 可用的 Razor 页面。更多答案...
以下是问题的完整有效解决方案:
- 创建 Blazor 服务器应用。
- 安装包 Microsoft.AspNetCore.Authentication.OpenIdConnect - 版本 3.1.0
创建一个名为 LoginDisplay (LoginDisplay.razor) 的组件,并将其放在 Shared 文件夹中。 MainLayout组件中使用了该组件
<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 组件,就在关于 锚元素,像这样
<div class="top-row px-4"> <LoginDisplay /> <a href="https://docs.microsoft.com/aspnet/" target="_blank">About</a> </div>
注意:为了将登录和注销请求重定向到 IdentityServer,我们必须创建两个 Razor 页面,如下所示: 1. 创建一个 Login Razor 页面 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 } );
}
}
此代码开始挑战您在启动 class 中定义的 Open Id Connect 身份验证方案。
创建注销 Razor 页面 Logout.cshtml (Logout.cshtml.cs) 并将它们也放在页面文件夹中:
Logout.cshtml.cs
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 class 中的代码替换为以下代码:
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");
});
}
}
重要提示:在上面的所有代码示例中,您必须根据需要添加 using 语句。其中大部分是默认提供的。此处提供的 using 是启用身份验证和授权流程所必需的。
- 运行 您的应用程序,单击登录按钮进行身份验证。您将被重定向到 IdentityServer 测试服务器,该服务器允许您执行 OIDC 登录。您可以输入用户名:bob 和密码bob,然后单击“确定”按钮后,您将被重定向到您的主页。另请注意,您可以使用外部登录提供程序 Google(试试看)。请注意,在您使用身份服务器登录后,LoginDisplay 组件会显示字符串 "Hello, ".
注意:当您正在试验您的应用程序时,如果您想被重定向到身份服务器的登录页面,您应该清除浏览数据,否则,您的浏览器可能会使用缓存数据。请记住,这是一种基于 cookie 的授权机制...
请注意,按照此处创建的登录机制不会使您的应用比以前更安全。任何用户都无需登录即可访问您的网络资源。为了保护网站的某些部分,您还必须实施授权,通常情况下,经过身份验证的用户被授权访问受保护的资源,除非实施了其他措施,例如角色、策略等。以下是如何进行的演示您可以保护您的 Fetchdata 页面免受未经授权的用户访问(同样,经过身份验证的用户被视为有权访问 Fetchdata 页面)。
- 在 Fetchdata 组件页面的顶部,为 Authorize 属性添加 @attribute 指令,如下所示:
@attribute [Authorize]
当未经身份验证的用户尝试访问 Fetchdata 页面时,将执行AuthorizeRouteView.NotAuthorized
委托 属性,因此我们可以添加一些代码将用户重定向到同一身份服务器的登录页面以进行身份验证。 NotAuthorized 元素中的代码如下所示:
<NotAuthorized> @{ var returnUrl = NavigationManager.ToBaseRelativePath(NavigationManager.Uri); NavigationManager.NavigateTo($"login?redirectUri= {returnUrl}", forceLoad: true); } </NotAuthorized>
这会检索您尝试访问的最后一个页面的 url,即 Fetchdata 页面,然后导航到执行密码挑战的 Login Razor 页面,即用户被重定向到身份服务器的登录页面进行身份验证。
用户通过身份验证后,他将被重定向到 Fetchdata 页面。
祝你好运...