首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何通过IdentityServer4将IdentityServer4添加到ASP.NET核心ServerSide Blazor web应用程序中?

如何通过IdentityServer4将IdentityServer4添加到ASP.NET核心ServerSide Blazor web应用程序中?
EN

Stack Overflow用户
提问于 2020-01-08 03:19:37
回答 3查看 8.9K关注 0票数 4

我做了以下工作(它应该工作,但它不工作),没有重定向,没有错误,没有什么,它只是显示页面没有auth,我做了什么错误?

ASP.NET Core3.1Bazor

Microsoft.AspNetCore.Authentication.OpenIdConnect 步骤1.安装-包

步骤2.编辑Statup.cs

在"ConfigurationServices“下添加

代码语言:javascript
复制
        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;
        });

在“配置”下添加

代码语言:javascript
复制
        ...
        services.AddAuthorization();

        app.UseStaticFiles();

        app.UseRouting();


        app.UseAuthentication();
        app.UseAuthorization();

        ....

步骤3.向blazor页面添加属性授权

代码语言:javascript
复制
        @page "/item"
        @attribute [Authorize] 
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2020-01-09 22:17:57

你的代码有一些毛病..。主要问题是,您的代码没有提供身份验证质询请求机制,从而允许重定向到身份验证代理(如IdentityServer )。这只有在HttpContext中才能实现,SignalR (Blazor )中没有这种功能。为了解决这个问题,我们将添加几个HttpContext可用的Razor页面。答案更多..。

以下是这个问题的完整和可行的解决办法:

  1. 创建一个Blazor服务器应用程序。
  2. 安装-软件包Microsoft.AspNetCore.Authentication.OpenIdConnect -Version 3.1.0
  3. 创建一个名为LoginDisplay (LoginDisplay.razor)的组件,并将其放在共享文件夹中。此组件用于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组件中,就在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

代码语言:javascript
复制
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身份验证方案的挑战。

  1. 创建一个Logout页面Logout.cshtml (Logout.cshtml.cs),并将它们放在Pages文件夹中: Logout.cshtml.cs using Microsoft.AspNetCore.Authentication; public class LogoutModel : PageModel { public async Task<IActionResult> OnGetAsync() { await HttpContext.SignOutAsync(); return Redirect("/"); } }

这段代码指示你退出,将你重定向到你的Blazor应用程序的主页。

用以下代码替换App.razor中的代码:

代码语言:javascript
复制
@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类中的代码替换为以下代码:

代码语言:javascript
复制
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");
        });
    }
}

重要:在上面的所有代码示例中,您必须根据需要添加使用语句。其中大多数都是默认提供的。这里提供的使用是启用身份验证和授权流所必需的。

  • 运行您的应用程序,单击登录按钮进行身份验证。您将被重定向到IdentityServer测试服务器,该服务器允许您执行OIDC登录。您可以输入用户名: bob和密码bob,单击OK按钮后,您将被重定向到您的主页。还请注意,您可以使用外部登录提供程序Google (尝试一下)。注意,在您使用identity服务器登录后,LoginDisplay组件将显示字符串"Hello,“。

注意:当您在试用应用程序时,您应该清除浏览数据,如果您想重定向到身份服务器的登录页面,否则浏览器可能会使用缓存的数据。记住,这是一个基于曲奇的授权机制.

请注意,像这里这样创建登录机制并不能使您的应用程序比以前更加安全。任何用户都可以访问您的web资源,而不需要登录。为了保护网站的部分安全,您还必须实现授权,通常,通过身份验证的用户有权访问安全资源,除非实现了其他措施,如角色、策略等。下面是如何从未经授权的用户保护Fetchdata页面的演示(同样,经过身份验证的用户被认为有权访问Fetchdata页面)。

  1. 在Fetchdata组件页面的顶部添加授权属性的@attribute指令,如:@attribute [Authorize]当未经身份验证的用户试图访问Fetchdata页面时,将执行AuthorizeRouteView.NotAuthorized委托属性,因此我们可以添加一些代码将用户重定向到相同身份服务器的登录页以进行身份验证。
  2. NotAuthorized元素中的代码如下所示: <NotAuthorized> @{ var returnUrl = NavigationManager.ToBaseRelativePath(NavigationManager.Uri); NavigationManager.NavigateTo($"login?redirectUri= {returnUrl}", forceLoad: true); } </NotAuthorized>

这将检索您试图访问的上一页的url,即Fetchdata页,然后导航到执行密码挑战的Login Razor页面,即将用户重定向到标识服务器的登录页以进行身份验证。

用户通过身份验证后,他将被重定向到Fetchdata页面。

祝你好运。

票数 15
EN

Stack Overflow用户

发布于 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/

票数 2
EN

Stack Overflow用户

发布于 2020-01-08 04:19:17

它只会显示页面而不显示,我做错了什么?

很可能你没有为你的应用程序添加一个AuthorizeRouteView。请注意,@attribute [Authorize]只是一个为该页面组件添加[AuthorizeAttribute]的指令。要启用路由授权,您需要:

  1. 在最顶层添加一个<CascadingAuthenticationState>
  2. 添加<AuthorizeRouteView>以启用路由授权。请参阅官方文件
  3. 使用<AuthorizeView>进行普通组件授权。添加<NotAuthorized>以在未授权时显示组件。并在授权用户的同时使用Authorizing显示组件。请参阅官方文件

例如,您的BlazorApp.razor可能如下所示:

代码语言:javascript
复制
<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>
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59638965

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档