更改.net Core 3.1.1 Web应用程序中的AzureAD身份验证的redirectURI和CallbackPath [英] Change redirectURI and CallbackPath for AzureAD authentication in .net core 3.1.1 web app

查看:177
本文介绍了更改.net Core 3.1.1 Web应用程序中的AzureAD身份验证的redirectURI和CallbackPath的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Razor Pages框架创建了一个新的.net core 3.1.1 Web应用程序.创建应用程序时,我将默认身份验证设置为AzureAd.当我运行该应用程序时,身份验证工作正常.生成的appsettings文件如下所示:

I created a new .net core 3.1.1 web application with the Razor Pages framework. When creating the app I set up the default Authentication as AzureAd. When I run the application the authentication works just fine. The generated appsettings file looks like this:

{
  "AzureAd": {
    "Instance": "https://login.microsoftonline.com/",
    "Domain": "myDomain",
    "TenantId": "myTenantId",
    "ClientId": "myClientId",
    "CallbackPath": "/signin-oidc"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*"
}

我在应用中创建了一个新控制器,看起来非常简单,就像:

I created a new controller in my app which looks very simple, just like:

namespace WebApplication1.Controllers
{
    public class AccountController : Controller
    {
        [HttpGet]
        public void SignIn()
        {
           //here comes the logic which checks in what role is the logged User
           //the role management stuff will be implemented in the app
        }
    }
}

这是我的Startup.cs的样子:

This is how my Startup.cs looks like:

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.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddAuthentication(AzureADDefaults.AuthenticationScheme)
            .AddAzureAD(options => Configuration.Bind("AzureAd", options));
        services.AddMvc(options =>
        {
            options.EnableEndpointRouting = false;
        });
        services.AddRazorPages().AddMvcOptions(options =>{});
    }

    // 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.MapRazorPages();
            endpoints.MapControllers();
        });

        app.UseMvc(routes =>
       {
            routes.MapRoute(
            name: "default",
            template: "{controller=Account}/{action=SignIn}");
       });
    }
}

我希望能够将AzureAd/CallbackPath更改为不同于"/signin-oidc"的名称.我想将其更改为帐户/登录".然后,我想从azure捕获回调,并根据记录的用户电子邮件地址,我想修改令牌以添加一些系统角色,并根据用户角色重定向到适当的仪表板页面.管理员和客户端可以有不同的仪表板.

I'd would like to be able to change the AzureAd/CallbackPath to something different than "/signin-oidc" eg. I would like to change it to Account/SignIn. Then I'd like to catch the callback call from azure and based on the logged user email address I'd like to modify the token to add some system roles and make a redirect to the appropriate dashboard page based on the user role. There can be a different dashboard for admin and a client.

因此,我尝试更改"CallbackPath":"/Account/SignIn" ,并且还更新了Azure中的RedirectURI:

So I tried to change the "CallbackPath": "/Account/SignIn" and I also updated RedirectURI in Azure:

然后我再次运行该应用程序,在 void SignIn()中设置一个断点,然后再次登录,而不是点击/Account/SignIn 刚刚被重定向到主页 https://localhost:44321 .我还尝试在浏览器中手动运行 https://localhost:44321/Account/SignIn ,并且看到以下错误消息:

Then I run the app once again, set a breakpoint in void SignIn(), I signed in once again, and instead of hitting the /Account/SignIn I was just redirected to the main page, the https://localhost:44321. I also tried to manually run the https://localhost:44321/Account/SignIn in the browser and I saw the following error message:

An unhandled exception occurred while processing the request.
Exception: OpenIdConnectAuthenticationHandler: message.State is null or empty.

我试图检查

I tried to check if there is something in the documentation but I didn't find anything useful. Any ideas about what should I do to make it work? Cheers

我还使用 Microsoft.AspNetCore.Authentication.AzureAD.UI 框架.

推荐答案

CallbackPath 是服务器在身份验证期间重定向的路径.它由OIDC中间件本身自动处理,这意味着我们无法通过创建新的控制器/动作并将 CallbackPath 设置为逻辑来控制逻辑.下面是一般过程:

The CallbackPath is the path where server will redirect during authentication. It's automatically handled by the OIDC middleware itself, that means we can't control the logic by creating a new controller/action and set CallbackPath to it . Below is the general process :

在身份验证期间,整个过程由OpenID Connect中间件控制,当用户在Azure的登录页面中验证凭据后,Azure Ad会将用户重定向回您在OIDC的配置中设置的应用程序的重定向URL,以便获得授权代码(如果使用代码流)并完成身份验证过程.身份验证之后,用户将被重定向到重定向URL.

During authentication , the whole process is controlled by OpenID Connect middleware , after user validate credential in Azure's login page ,Azure Ad will redirect user back to your application's redirect url which is set in OIDC's configuration , so that you can get the authorization code(if using code flow) and complete the authentication process . After authentication , user will then be redirected to the redirect url .

基于记录的用户电子邮件地址,我想修改令牌以添加一些系统角色,并根据用户角色重定向到适当的仪表板页面.管理员和客户端可以有不同的仪表板.

based on the logged user email address I'd like to modify the token to add some system roles and make a redirect to the appropriate dashboard page based on the user role. There can be a different dashboard for admin and a client.

第一件事是您不能修改令牌,也不需要修改令牌.

The first thing is you can't modify the token and you don't need to modify that .

您可以在OIDC OWIN Middlerware中使用通知事件,该事件被调用以使开发人员可以控制身份验证过程. OnTokenValidated 为您提供了修改从传入令牌获得的ClaimsIdentity的机会,您可以根据本地数据库中的用户ID查询用户的角色并添加到用户的声明中:

You can use notification events in OIDC OWIN Middlerware which invokes to enable developer control over the authentication process . OnTokenValidated offers you the chance to modify the ClaimsIdentity obtained from the incoming token , you can query user's role based on user's id from local database and add to user's claims :

 services.AddAuthentication(AzureADDefaults.AuthenticationScheme)
            .AddAzureAD(options => Configuration.Bind("AzureAd", options));


services.Configure<OpenIdConnectOptions>(AzureADDefaults.OpenIdScheme, options =>
{
    options.Events = new OpenIdConnectEvents
    {
        OnTokenValidated = ctx =>
        {
            //query the database to get the role

            // add claims
            var claims = new List<Claim>
            {
                new Claim(ClaimTypes.Role, "Admin")
            };
            var appIdentity = new ClaimsIdentity(claims);

            ctx.Principal.AddIdentity(appIdentity);

            return Task.CompletedTask;
        },
    };
});

然后在controller中,您可以像这样获得索赔:

Then in controller , you can get the claim like :

var role = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Role)?.Value;

然后,您可以根据特定声明过滤操作.

Then you can filter the actions based on specific claim .

如果要在身份验证后将用户重定向到特定的路由/页面,请将URL放入 AuthenticationProperties :

If you want to redirect user to specific route/page after authentication , put the url to AuthenticationProperties :

if (!User.Identity.IsAuthenticated)
{
    return Challenge(new AuthenticationProperties() { RedirectUri = "/home/redirectOnRole" } , AzureADDefaults.AuthenticationScheme);
}  

在该路径中,您可以根据用户的角色重定向用户.

And in that path , you can redirect user based on user's role .

这篇关于更改.net Core 3.1.1 Web应用程序中的AzureAD身份验证的redirectURI和CallbackPath的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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