Auth0和ASP.NET核心2.0剃刀页面授权控制 [英] Auth0 and ASP.NET core 2.0 razor pages authorization control

查看:96
本文介绍了Auth0和ASP.NET核心2.0剃刀页面授权控制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在mvc .net核心2.1中集成了authO并使用了剃刀页面,如果我想控制剃刀页面访问权限,则无法理解如何使用授权,因此登录和注销正在进行,但用户不是经过身份验证并保持用户在同一页面上,但是当我在注销期间尝试访问URL时,当我尝试访问url时出现错误: https:// localhost:5001 /冲突 [ ^ ]



I've integrated authO in mvc .net core 2.1 and using razor pages,unable to understand how to use authorization if i want to control razor pages access,so sign in and sign out is happening properly but id the user is not authenticated in and to keep the user on the same page , but right now when i tried to access the URL during logout i get an error when i tried access the url :https://localhost:5001/Conflicts[^]

This localhost page can’t be found
No webpage was found for the web address: https://localhost:5001/Account/Login?ReturnUrl=%2FConflicts
HTTP ERROR 404



生成的网址是: https:// localhost:5001 /帐户/登录?ReturnUrl =%2FConflicts [ ^ ]







默认页面是MainPage,我想让用户保持在同一页面上,如果他们没有经过身份验证,则尝试访问URL,例如冲突页面,他们应该保留在主页面上



我的尝试:



and
the url which is generating is :https://localhost:5001/Account/Login?ReturnUrl=%2FConflicts[^]



the default page is MainPage and i want to keep the user on the same page if they are not authenticated id the try to access the URL for example Conflicts page they should remain on main page

What I have tried:

 public class Startup
   {
       public Startup(IConfiguration configuration)
       {
           Configuration = configuration;
           HostingEnvironment = HostingEnvironment;
       }

       public IConfiguration Configuration { get; }
       public IHostingEnvironment HostingEnvironment { get; }

       // This method gets called by the runtime. Use this method to add services to the container.
       public void ConfigureServices(IServiceCollection services)
       {
           services.Configure<IISOptions>(options =>
           {
               options.ForwardClientCertificate = false;
           });

           services.AddAuthentication(options =>
           {
               options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
               options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
               options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
           })
        .AddCookie()
        .AddOpenIdConnect("Auth0", options =>
        {
            // Set the authority to your Auth0 domain
            options.Authority = $"https://{Configuration["Auth0:Domain"]}";

            // Configure the Auth0 Client ID and Client Secret
            options.ClientId = Configuration["Auth0:ClientId"];
            options.ClientSecret = Configuration["Auth0:ClientSecret"];

            // Set response type to code
            options.ResponseType = "code";

            // Configure the scope
            options.Scope.Clear();
            options.Scope.Add("openid");

            // Set the callback path, so Auth0 will call back to http://localhost:5000/signin-auth0
            // Also ensure that you have added the URL as an Allowed Callback URL in your Auth0 dashboard
            options.CallbackPath = new PathString("/signin-auth0");

            // Configure the Claims Issuer to be Auth0
            options.ClaimsIssuer = "Auth0";

            // Saves tokens to the AuthenticationProperties
            options.SaveTokens = true;

            options.Events = new OpenIdConnectEvents
            {
                // handle the logout redirection
                OnRedirectToIdentityProviderForSignOut = (context) =>
             {
                 var logoutUri = $"https://{Configuration["Auth0:Domain"]}/v2/logout?client_id={Configuration["Auth0:ClientId"]}";

                 var postLogoutUri = context.Properties.RedirectUri;
                 if (!string.IsNullOrEmpty(postLogoutUri))
                 {
                     if (postLogoutUri.StartsWith("/"))
                     {
                            // transform to absolute
                            var request = context.Request;
                         postLogoutUri = request.Scheme + "://" + request.Host + request.PathBase + postLogoutUri;
                     }
                     logoutUri += $"&returnTo={ Uri.EscapeDataString(postLogoutUri)}";
                 }

                 context.Response.Redirect(logoutUri);
                 context.HandleResponse();

                 return Task.CompletedTask;
             }
            };
        });


           services.Configure<CookiePolicyOptions>(options =>
           {
               // This lambda determines whether user consent for non-essential cookies is needed for a given request.
               options.CheckConsentNeeded = context => true;
               options.MinimumSameSitePolicy = SameSiteMode.None;
           });

           services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
           services.AddMvc().AddRazorPagesOptions(options =>
           {
               options.Conventions.AddPageRoute("/MainPage", "");
options.Conventions.AuthorizePage("/Conflicts");
           });
       }

       // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
       public void Configure(IApplicationBuilder app, IHostingEnvironment env)
       {
           if (env.IsDevelopment())
           {
               app.UseDeveloperExceptionPage();
           }
           else
           {
               app.UseExceptionHandler("/Error");
               app.UseHsts();
           }

           app.UseHttpsRedirection();
           app.UseStaticFiles();
           app.UseCookiePolicy();
           app.UseCorsMiddleware();
           app.UseAuthentication();
           app.UseCors("CorsPolicy");
           app.UseMvc();
           //app.UseMvc(rb =>
           //{
           //    rb.MapRoute(
           //        name: "default",
           //        template: "{controller}/{action}/{id?}",
           //        defaults: new { controller = "Home", action = "Index" });
           //});
       }
   }

推荐答案

https:// {Configuration [Auth0:Domain ]};

//配置Auth0客户端ID和客户端密钥
options.ClientId = Configuration [Auth0:ClientId];
options.ClientSecret = Configuration [Auth0:ClientSecret];

//将响应类型设置为代码
options.ResponseType =code;

//配置范围
options.Scope.Clear();
options.Scope.Add(openid);

//设置回调路径,因此Auth0将回调http:// localhost:5000 / signin-auth0
//同时确保已将URL添加为允许回调Auth0仪表板中的URL
options.CallbackPath = new PathString(/ signin-auth0);

//将Claim Issuer配置为Auth0
options.ClaimsIssuer =Auth0;

//将令牌保存到AuthenticationProperties
options.SaveTokens = true;

options.Events = new OpenIdConnectEvents
{
//处理注销重定向
OnRedirectToIdentityProviderForSignOut =(context)=>
{
var logoutUri =
"https://{Configuration["Auth0:Domain"]}"; // Configure the Auth0 Client ID and Client Secret options.ClientId = Configuration["Auth0:ClientId"]; options.ClientSecret = Configuration["Auth0:ClientSecret"]; // Set response type to code options.ResponseType = "code"; // Configure the scope options.Scope.Clear(); options.Scope.Add("openid"); // Set the callback path, so Auth0 will call back to http://localhost:5000/signin-auth0 // Also ensure that you have added the URL as an Allowed Callback URL in your Auth0 dashboard options.CallbackPath = new PathString("/signin-auth0"); // Configure the Claims Issuer to be Auth0 options.ClaimsIssuer = "Auth0"; // Saves tokens to the AuthenticationProperties options.SaveTokens = true; options.Events = new OpenIdConnectEvents { // handle the logout redirection OnRedirectToIdentityProviderForSignOut = (context) => { var logoutUri =


https:// {Configuration [Auth0:Domain]} / v2 / logout?client_id = {Configuration [Auth0 :客户端Id ]};

var postLogoutUri = context.Properties.RedirectUri;
if(!string.IsNullOrEmpty(postLogoutUri))
{
if(postLogoutUri.StartsWith(/))
{
//转换为绝对
var request = context.Request;
postLogoutUri = request.Scheme +://+ request.Host + request.PathBase + postLogoutUri;
}
logoutUri + =
"https://{Configuration["Auth0:Domain"]}/v2/logout?client_id={Configuration["Auth0:ClientId"]}"; var postLogoutUri = context.Properties.RedirectUri; if (!string.IsNullOrEmpty(postLogoutUri)) { if (postLogoutUri.StartsWith("/")) { // transform to absolute var request = context.Request; postLogoutUri = request.Scheme + "://" + request.Host + request.PathBase + postLogoutUri; } logoutUri +=


& returnTo = {Uri.EscapeDataString(postLogoutUri)};
}

context.Response.Redirect(logoutUri);
context.HandleResponse();

返回Task.CompletedTask;
}
};
});


services.Configure< CookiePolicyOptions>(options =>
{
//此lambda确定是否需要用户同意非必要的cookie请求。
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});

services.AddMvc()。SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
services.AddMvc()。AddRazorPagesOptions(options =>
{
options.Conventions.AddPageRoute(/ MainPage,);
options.Conventions.AuthorizePage( / Conflicts);
});
}

//运行时调用此方法。使用此方法配置HTTP请求管道。
public void配置(IApplicationBuilder app,IHostingEnvironment env)
{
if(env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler(/ Error);
app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseCorsMiddleware();
app.UseAuthentication();
app.UseCors(CorsPolicy);
app.UseMvc();
//app.UseMvc(rb =>
// {
// rb.MapRoute(
//名称:默认,
//模板:{controller} / {action} / {id?},
//默认值:new {controller =Home,action =Index});
//});
}
}
"&returnTo={ Uri.EscapeDataString(postLogoutUri)}"; } context.Response.Redirect(logoutUri); context.HandleResponse(); return Task.CompletedTask; } }; }); services.Configure<CookiePolicyOptions>(options => { // This lambda determines whether user consent for non-essential cookies is needed for a given request. options.CheckConsentNeeded = context => true; options.MinimumSameSitePolicy = SameSiteMode.None; }); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); services.AddMvc().AddRazorPagesOptions(options => { options.Conventions.AddPageRoute("/MainPage", ""); options.Conventions.AuthorizePage("/Conflicts"); }); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Error"); app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseCookiePolicy(); app.UseCorsMiddleware(); app.UseAuthentication(); app.UseCors("CorsPolicy"); app.UseMvc(); //app.UseMvc(rb => //{ // rb.MapRoute( // name: "default", // template: "{controller}/{action}/{id?}", // defaults: new { controller = "Home", action = "Index" }); //}); } }


这篇关于Auth0和ASP.NET核心2.0剃刀页面授权控制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆