Azure AD身份验证,具有在ASP.NET MVC 5.0中的SQL Server中维护的自定义角色

发布于 2025-01-29 09:23:10 字数 5486 浏览 3 评论 0原文

首先,我不会从Azure AD中维护角色(索赔),因为我必须将其维护在SQL Server中。因此,为了进行身份验证,我正在使用Azure AD。经过身份验证后,我会查询我的索赔表(AspnetMembership)并将其添加到身份。

目前,以下代码似乎工作正常。但是由于我有这些问题,我一点也不自信,因为我只是不知道我是否对其进行了正确的编码。

这是我的代码,以下是我的问题:

  1. 就像我们对表单AUTH所做的一样,一旦经过身份验证,我应该设置thread.currentprincipal和context.user.user即使使用azure ad ad authentication或自动进行此类代码行为我做到这一点(我登录一次Azure广告可以恰当地验证)

    httpcontext.current.getOwinContext()

  2. 如果是对上述问题,我真的很困惑我必须如何将上述代码线与Azure AD AD验证的身份进行委托书(以及Contect.user)?

  3. 我从来不知道这一点,但是MVC 5.0中的[授权]属性是否会自动进行调用以检查请求是否已“认证”?

  4. 如何访问我在控制器内启动中添加的自定义索赔?

  5. 您能解释一下我需要如何使用Azure广告认证处理cookie?

提前致谢!

这是我的代码:

public void ConfigureAuth(IAppBuilder app)
        {
            // Configure the db context, user manager and signin manager to use a single instance per request
            app.CreatePerOwinContext(ApplicationDbContext.Create);
            app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
         //   app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);
            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
            
            //app.UseCookieAuthentication(new CookieAuthenticationOptions 
            //{
            //    CookieDomain = "localhost",
            //    SlidingExpiration = true,
            //    ExpireTimeSpan = TimeSpan.FromHours(2)
            //});


            app.UseCookieAuthentication(new CookieAuthenticationOptions());
            app.UseOpenIdConnectAuthentication(
                new OpenIdConnectAuthenticationOptions
                {
                    // Sets the ClientId, authority, RedirectUri as obtained from web.config
                    ClientId = clientId,
                    Authority = authority,
                    RedirectUri = null,
                    // PostLogoutRedirectUri is the page that users will be redirected to after sign-out. In this case, it is using the home page
                    PostLogoutRedirectUri = redirectUri,
                    Scope = OpenIdConnectScope.OpenIdProfile,
                    // ResponseType is set to request the code id_token - which contains basic information about the signed-in user
                    ResponseType = OpenIdConnectResponseType.CodeIdToken,
                    // ValidateIssuer set to false to allow personal and work accounts from any organization to sign in to your application
                    // To only allow users from a single organizations, set ValidateIssuer to true and 'tenant' setting in web.config to the tenant name
                    // To allow users from only a list of specific organizations, set ValidateIssuer to true and use ValidIssuers parameter
  
                    TokenValidationParameters = new TokenValidationParameters()
                    {
                        //NameClaimType = "preferred_username",
                        ValidateIssuer = false // TODO:  SET THIS TO TRUE EVENTUALLY. 
                       
                    },
                    // OpenIdConnectAuthenticationNotifications configures OWIN to send notification of failed authentications to OnAuthenticationFailed method
                    Notifications = new OpenIdConnectAuthenticationNotifications
                    {
                        AuthenticationFailed = OnAuthenticationFailed,
                        SecurityTokenValidated = async (x) =>
                        {
                            var identity = x.AuthenticationTicket.Identity; //Check this.     
                            
                           
                            await Task.FromResult(0);
                            var claims = identity.Claims;
                            var name = claims.First(claim => claim.Type == "name").Value;
                            var email = claims.First(claim => claim.Type == "preferred_username").Value;

                            var user = UserManager.FindByEmail(email);

                            var customClaims = UserManager.GetClaims(user.Id);
                            foreach (var claim in customClaims)
                            {
                                identity.AddClaim(new Claim(claim.Type, claim.Value));
                            }

                            

                            HttpContext.Current.GetOwinContext().Authentication.SignIn(identity); //THis is the key here.

                            var principal = new ClaimsPrincipal(identity);

                            System.Threading.Thread.CurrentPrincipal = principal;
                            if (System.Web.HttpContext.Current != null)
                                System.Web.HttpContext.Current.User = principal;
                        }
                    }

                }

            );
         
        }

在我的控制器方法中,我正在使用此方法访问上面添加的主张。请确认这是否正确,或者我应该使用螺纹。CurrentPrincipal以某种方式?

[Authorize]
    public class HomeController : BaseController
    {
        private ApplicationUserManager _userManager;
        public ActionResult Index()
        {
            
            //{

            var identity = User.Identity as ClaimsIdentity;
            
            var count = identity.Claims.Count(); //I get to see all the claims here that I set in startup

            return View();
        }

First up, I am NOT going to be maintaining roles (claims) from within Azure AD, as I have to maintain it within SQL Server. So, for Authentication, I am using Azure AD. Once authenticated, I query my claims tables (aspnetmembership) and add it to the identity.

Right now, the below code seems to be working fine. But I don't feel confident at all due to these questions I have, as I just don't know if I have coded it right.

Here's my code and here are my questions:

  1. Like we do with Forms auth, once authenticated, am I supposed to set the Thread.Currentprincipal, as well as Context.User even with Azure AD authentication or does this line of code automatically do that for me (I sign in once azure ad authenticates fine)

    HttpContext.Current.GetOwinContext().Authentication.SignIn(identity);

  2. If yes to the above question, I am really confused as to how I must sequence the above Signin line of code with setting the Principal (as well as Context.User) with the Azure AD authenticated identity?

  3. I never knew this but does the [Authorize] attribute in MVC 5.0 automatically do the call to check if the request is 'authenticated' as well?

  4. How do I access the custom claims that I added in Startup, within my controllers?

  5. Can you please explain how I need to be handling the cookies with AZure AD authentication?

Thanks in advance!

Here's my code:

public void ConfigureAuth(IAppBuilder app)
        {
            // Configure the db context, user manager and signin manager to use a single instance per request
            app.CreatePerOwinContext(ApplicationDbContext.Create);
            app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
         //   app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);
            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
            
            //app.UseCookieAuthentication(new CookieAuthenticationOptions 
            //{
            //    CookieDomain = "localhost",
            //    SlidingExpiration = true,
            //    ExpireTimeSpan = TimeSpan.FromHours(2)
            //});


            app.UseCookieAuthentication(new CookieAuthenticationOptions());
            app.UseOpenIdConnectAuthentication(
                new OpenIdConnectAuthenticationOptions
                {
                    // Sets the ClientId, authority, RedirectUri as obtained from web.config
                    ClientId = clientId,
                    Authority = authority,
                    RedirectUri = null,
                    // PostLogoutRedirectUri is the page that users will be redirected to after sign-out. In this case, it is using the home page
                    PostLogoutRedirectUri = redirectUri,
                    Scope = OpenIdConnectScope.OpenIdProfile,
                    // ResponseType is set to request the code id_token - which contains basic information about the signed-in user
                    ResponseType = OpenIdConnectResponseType.CodeIdToken,
                    // ValidateIssuer set to false to allow personal and work accounts from any organization to sign in to your application
                    // To only allow users from a single organizations, set ValidateIssuer to true and 'tenant' setting in web.config to the tenant name
                    // To allow users from only a list of specific organizations, set ValidateIssuer to true and use ValidIssuers parameter
  
                    TokenValidationParameters = new TokenValidationParameters()
                    {
                        //NameClaimType = "preferred_username",
                        ValidateIssuer = false // TODO:  SET THIS TO TRUE EVENTUALLY. 
                       
                    },
                    // OpenIdConnectAuthenticationNotifications configures OWIN to send notification of failed authentications to OnAuthenticationFailed method
                    Notifications = new OpenIdConnectAuthenticationNotifications
                    {
                        AuthenticationFailed = OnAuthenticationFailed,
                        SecurityTokenValidated = async (x) =>
                        {
                            var identity = x.AuthenticationTicket.Identity; //Check this.     
                            
                           
                            await Task.FromResult(0);
                            var claims = identity.Claims;
                            var name = claims.First(claim => claim.Type == "name").Value;
                            var email = claims.First(claim => claim.Type == "preferred_username").Value;

                            var user = UserManager.FindByEmail(email);

                            var customClaims = UserManager.GetClaims(user.Id);
                            foreach (var claim in customClaims)
                            {
                                identity.AddClaim(new Claim(claim.Type, claim.Value));
                            }

                            

                            HttpContext.Current.GetOwinContext().Authentication.SignIn(identity); //THis is the key here.

                            var principal = new ClaimsPrincipal(identity);

                            System.Threading.Thread.CurrentPrincipal = principal;
                            if (System.Web.HttpContext.Current != null)
                                System.Web.HttpContext.Current.User = principal;
                        }
                    }

                }

            );
         
        }

And in my controller methods I am accessing my claims that I added above, using this method. Please confirm if this is correct or should I use the Thread.CurrentPrincipal somehow?

[Authorize]
    public class HomeController : BaseController
    {
        private ApplicationUserManager _userManager;
        public ActionResult Index()
        {
            
            //{

            var identity = User.Identity as ClaimsIdentity;
            
            var count = identity.Claims.Count(); //I get to see all the claims here that I set in startup

            return View();
        }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文