[英]how to use oauth2 in blazor hosted wasm
我的項目是由 dotnet cli 創建的
dotnet new blazorwasm --hosted
我的項目結構是
我添加了具有 client_secret/client_id 和其他配置的 PingOne Oauth 提供程序...
服務器文件夾:Program.cs
builder.Services.AddControllersWithViews();
builder.Services.AddRazorPages();
ConfigureAuthentication(builder.Services);
void ConfigureAuthentication(IServiceCollection serviceCollection)
{
// serviceCollection
serviceCollection.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = "PingOne";
}).AddCookie().AddOAuth("PingOne", options =>
{
options.AuthorizationEndpoint = "https://xxx.xxx.xxx/xxx/xxx/authorization.oauth2";
options.CallbackPath = "/callback";
options.ClientId = "xxx";
options.ClientSecret = "xxx";
options.TokenEndpoint = "https://xxx.xxx.xxx/xxx/xx/token.oauth2";
options.UserInformationEndpoint = "https://xxx.xx.xx/xx/xxx/userinfo.openid";
options.SaveTokens = true;
options.Events = new OAuthEvents
{
OnCreatingTicket = async context =>
{
var request = new HttpRequestMessage(HttpMethod.Get, context.Options.UserInformationEndpoint);
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", context.AccessToken);
var response = await context.Backchannel.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, context.HttpContext.RequestAborted);
response.EnsureSuccessStatusCode();
Console.WriteLine(await response.Content.ReadAsStringAsync());
var responseText = await response.Content.ReadAsStringAsync();
var user = JsonDocument.Parse(responseText);
context.RunClaimActions(user.RootElement);
}
};
});
}
客戶端文件夾:Program.cs
using Microsoft.AspNetCore.Components.Web;
using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
using BlazorOAuth.Client;
var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.RootComponents.Add<App>("#app");
builder.RootComponents.Add<HeadOutlet>("head::after");
builder.Services.AddAuthorizationCore();
builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });
await builder.Build().RunAsync();
客戶端文件夾:_Imports.razor:
@using System.Net.Http
@using System.Net.Http.Json
@using Microsoft.AspNetCore.Components.Forms
@using Microsoft.AspNetCore.Components.Routing
@using Microsoft.AspNetCore.Components.Web
@using Microsoft.AspNetCore.Components.Web.Virtualization
@using Microsoft.AspNetCore.Components.WebAssembly.Http
@using Microsoft.JSInterop
@using BlazorOAuth.Client
@using BlazorOAuth.Client.Shared
@using Microsoft.AspNetCore.Authorization
@using Microsoft.AspNetCore.Components.Authorization
@attribute [Authorize]
在櫃台.razor:
@page "/counter"
@attribute [Authorize]
<PageTitle>Counter</PageTitle>
<h1>Counter</h1>
<p role="status">Current count: @currentCount</p>
<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>
@code {
private int currentCount = 0;
private void IncrementCount()
{
currentCount++;
}
}
我不知道如何自動跳轉到 PingOne 或其他 oauth 提供商的身份驗證頁面。 blazor 客戶端不會自動跳轉到身份驗證頁面,因為我沒有配置一些東西。另外我有一個帶有 Authorize 屬性的 WeatherForecastController。 客戶端向 api 發送請求,但也沒有跳轉到 oauth 授權頁面。 我以為我配置了 services.AddOuth() 就可以了。
我捕獲了請求。 我發現它重定向到授權端點 url。 但響應是 html 代碼。 我不知道如何在屏幕上顯示
請幫助我或粘貼教程。 真的很感激。
'<' 是值的無效開始。
這個錯誤的原因是:工作流程是請求具有授權屬性的天氣預報服務。但尚未授權。 所以服務去授權端點。然后是oauth提供者,這是PingOne身份。授權提供者響應一堆html代碼。 我不知道如何在屏幕上顯示或重定向到端點 url。在這種情況下,客戶端可以輸入密碼授權並請求天氣服務
當使用 Blazor WebAssembly(或任何 spa 框架,例如 angular)時,最佳實踐是使用授權碼流實現 openid 連接身份驗證。
您的客戶端應重定向到 oauth 提供程序,並在用戶登錄您的客戶端后從 oauth 提供程序獲取訪問令牌。 客戶端將此訪問令牌發送到 api 請求到您的服務器。
示例客戶端 Program.cs:
// BaseAddressAuthorizationMessageHandler attaches access token to outgoing requests
builder.Services
.AddHttpClient("ServerAPI", client => client.BaseAddress = new Uri(builder.HostEnvironment.BaseAddress))
.AddHttpMessageHandler<BaseAddressAuthorizationMessageHandler>();
builder.Services.AddScoped(sp => sp.GetRequiredService<IHttpClientFactory>().CreateClient("ServerAPI"));
builder.Services
.AddOidcAuthentication(options =>
{
options.ProviderOptions.Authority = "https://xxx";
options.ProviderOptions.ClientId = "xxx";
options.ProviderOptions.ResponseType = "code";
options.ProviderOptions.DefaultScopes.Add("scope1");
options.ProviderOptions.DefaultScopes.Add("scope2");
});
然后,您的服務器需要通過詢問 oauth 提供程序來驗證此訪問令牌。 示例服務器配置:
services
.AddAuthentication("Bearer")
.AddJwtBearer("Bearer", options =>
{
options.Authority = "https://xxx";
});
這是有關如何登錄您的 oidc 提供商並獲取訪問令牌的文檔: https://docs.microsoft.com/en-us/aspnet/core/blazor/security/webassembly/standalone-with-authentication-library?視圖=aspnetcore-6.0&tabs=visual-studio
這是如何將訪問令牌附加到 api 請求到您的服務器: https://docs.microsoft.com/en-us/aspnet/core/blazor/security/webassembly/additional-scenarios?view=aspnetcore-6.0#attach-令牌到傳出請求
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.