从服务器端blazor授权调用WebAPI

时间:2020-09-13 10:57:14

标签: authorization blazor server-side webapi

很抱歉,这是一个愚蠢的问题-我正在努力进行全面的安全设置,并且在该领域没有太多经验。尽我所能阅读,但找不到我想做的明确例子。

我已经从Visual Studio模板中创建了默认的服务器端和wasm blazor项目,并共享了wasm项目,因此我可以按照Carl Franklin的文章重用客户端和服务器端:

http://www.appvnext.com/blog/2020/2/2/reuse-blazor-wasm-ui-in-blazor-server

一切正常。

接下来,我重复一遍,但是在创建时将“个人用户帐户”选项添加到两个项目中,并将db字符串设置为共享的身份数据库。两者都是单独工作的,但是,当我共享客户端代码并从服务器端blazor调用时,webapi调用将失败,并显示“未经授权”错误。

因此,简而言之,我已成功登录到服务器端的blazor项目。当我尝试调用现在位于单独项目(WASM项目)中的webapi时,会发生失败,因此它将在不同的域中运行(不要认为我遇到了cors问题)。当我尝试调用webapi时,出现未授权错误。当我在WASM中运行时,一切正常。

有人可以给我指点一下,我需要采取什么步骤才能使它正常工作吗?剃须刀组件的完整代码如下...

@page "/fetchdata"
@using Microsoft.AspNetCore.Authorization
@using Microsoft.AspNetCore.Components.WebAssembly.Authentication
@using BlazorWasm.Shared
@attribute [Authorize]
@inject HttpClient Http

<h1>Weather forecast</h1>

<p>This component demonstrates fetching data from the server.</p>

@if (forecasts == null)
{
    <p><em>Loading...</em></p>
}
else
{
    <table class="table">
        <thead>
            <tr>
                <th>Date</th>
                <th>Temp. (C)</th>
                <th>Temp. (F)</th>
                <th>Summary</th>
            </tr>
        </thead>
        <tbody>
            @foreach (var forecast in forecasts)
            {
                <tr>
                    <td>@forecast.Date.ToShortDateString()</td>
                    <td>@forecast.TemperatureC</td>
                    <td>@forecast.TemperatureF</td>
                    <td>@forecast.Summary</td>
                </tr>
            }
        </tbody>
    </table>
}

@code {
    private WeatherForecast[] forecasts;

    protected override async Task OnInitializedAsync()
    {
        try
        {
            string url = "https://localhost:44378/WeatherForecast";
            forecasts = await Http.GetFromJsonAsync<WeatherForecast[]>(url);
        }
        catch (AccessTokenNotAvailableException exception)
        {
            exception.Redirect();
        }
        catch(HttpRequestException exception)
        {
            string msg = exception.Message;
        }
    }

}

0 个答案:

没有答案