public void ConfigureAuth(IAppBuilder app)
        {
            WindowsAzureActiveDirectoryBearerAuthenticationOptions options = new WindowsAzureActiveDirectoryBearerAuthenticationOptions();

            options.Tenant = ConfigurationManager.AppSettings["ida:Tenant"];
            options.TokenValidationParameters = new TokenValidationParameters
            {
                ValidateAudience = Convert.ToBoolean(ConfigurationManager.AppSettings["ida:ValidateAudience"]),
                //ValidAudience = ConfigurationManager.AppSettings["ida:Audience"],
                AudienceValidator = ((audiences, jwt, validationParameters) =>
                {
                    // Write some code here to validate the audiences in the audiences parameter
                    return(true);
                })
            };
            options.Provider = new OAuthBearerAuthenticationProvider()
            {
                OnValidateIdentity = context =>
                {
                    // Add custom claims here
                    context.Ticket.Identity.AddClaim(
                        new Claim(ClaimTypes.Role, "Admin"));
                    return(Task.FromResult(0));
                }
            };

            app.UseWindowsAzureActiveDirectoryBearerAuthentication(options);
        }
Beispiel #2
0
        public void ConfigureAuth(IAppBuilder app)
        {
            WindowsAzureActiveDirectoryBearerAuthenticationOptions options = new WindowsAzureActiveDirectoryBearerAuthenticationOptions()
            {
                Tenant = ConfigurationManager.AppSettings["aad:Audience"],
                TokenValidationParameters = new System.IdentityModel.Tokens.TokenValidationParameters()
                {
                    ValidAudience = ConfigurationManager.AppSettings["aad:Audience"]
                },
            };

            app.UseWindowsAzureActiveDirectoryBearerAuthentication(options);
        }
        public void ConfigureAuth(IAppBuilder app)
        {
            WindowsAzureActiveDirectoryBearerAuthenticationOptions options = new WindowsAzureActiveDirectoryBearerAuthenticationOptions();

            options.Tenant = ConfigurationManager.AppSettings["ida:Tenant"];
            options.TokenValidationParameters = new TokenValidationParameters
            {
                ValidateAudience = Convert.ToBoolean(ConfigurationManager.AppSettings["ida:ValidateAudience"]),
                ValidAudience    = ConfigurationManager.AppSettings["ida:Audience"]
            };

            app.UseWindowsAzureActiveDirectoryBearerAuthentication(options);
        }
        private void ConfigureAuth(IAppBuilder app)
        {
            var azureADBearerAuthOptions = new WindowsAzureActiveDirectoryBearerAuthenticationOptions
            {
                Tenant = ConfigurationManager.AppSettings["ida:Tenant"]
            };

            azureADBearerAuthOptions.TokenValidationParameters = new System.IdentityModel.Tokens.TokenValidationParameters()
            {
                ValidAudience = ConfigurationManager.AppSettings["ida:Audience"]
            };

            app.UseWindowsAzureActiveDirectoryBearerAuthentication(azureADBearerAuthOptions);
        }
        private void ConfigureAuth(IAppBuilder app)
        {
            var AzureADBearerAuthOptions = new WindowsAzureActiveDirectoryBearerAuthenticationOptions
            {
                Tenant = ConfigurationManager.AppSettings["ida:Tenant"]
            };

            AzureADBearerAuthOptions.TokenValidationParameters =
                new System.IdentityModel.Tokens.TokenValidationParameters()
            {
                // Audience is going to be the App Id URI of my service
                ValidAudience = ConfigurationManager.AppSettings["ida:Audience"]
            };

            // I will access tokens over HTTP header
            app.UseWindowsAzureActiveDirectoryBearerAuthentication(AzureADBearerAuthOptions);
        }
        public IEnumerable <OwinMiddlewareRegistration> GetOwinMiddlewares()
        {
            var middlewares = new List <OwinMiddlewareRegistration>();

            AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.NameIdentifier;

            var openIdOptions = new OpenIdConnectAuthenticationOptions {
                ClientId              = _azureClientId,
                Authority             = string.Format(CultureInfo.InvariantCulture, _azureADInstance, _azureTenant),
                PostLogoutRedirectUri = _logoutRedirectUri,
                Notifications         = new OpenIdConnectAuthenticationNotifications()
            };

            var cookieOptions = new CookieAuthenticationOptions();

            var bearerAuthOptions = new WindowsAzureActiveDirectoryBearerAuthenticationOptions {
                TokenValidationParameters = new TokenValidationParameters {
                    ValidAudience = string.Format(_sslEnabled ? "https://{0}/{1}" : "http://{0}/{1}", _azureTenant, _azureAppName)
                }
            };

            if (_azureWebSiteProtectionEnabled)
            {
                middlewares.Add(new OwinMiddlewareRegistration {
                    Priority  = "9",
                    Configure = app => { app.SetDataProtectionProvider(new MachineKeyProtectionProvider()); }
                });
            }

            middlewares.Add(new OwinMiddlewareRegistration {
                Priority  = "10",
                Configure = app => {
                    app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

                    app.UseCookieAuthentication(cookieOptions);

                    app.UseOpenIdConnectAuthentication(openIdOptions);

                    //This is throwing an XML DTD is prohibited error?
                    //app.UseWindowsAzureActiveDirectoryBearerAuthentication(bearerAuthOptions);
                }
            });

            return(middlewares);
        }
Beispiel #7
0
        /// <summary>
        /// Adds Windows Azure Active Directory (WAAD) issued JWT bearer token middleware to your web application pipeline.
        /// </summary>
        /// <param name="app">The IAppBuilder passed to your configuration method.</param>
        /// <param name="options">An options class that controls the middleware behavior.</param>
        /// <returns>The original app parameter.</returns>
        public static IAppBuilder UseWindowsAzureActiveDirectoryBearerAuthentication(this IAppBuilder app, WindowsAzureActiveDirectoryBearerAuthenticationOptions options)
        {
            if (options == null)
            {
                throw new ArgumentNullException("options");
            }
            if (string.IsNullOrWhiteSpace(options.Tenant))
            {
                throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, Resources.Exception_OptionMustBeProvided, "Tenant"));
            }

            var bearerOptions = new OAuthBearerAuthenticationOptions
            {
                Realm             = options.Realm,
                Provider          = options.Provider,
                AccessTokenFormat = new JwtFormat(options.Audience,
                                                  new WsFedCachingSecurityTokenProvider(
                                                      string.Format(CultureInfo.InvariantCulture, SecurityTokenServiceAddressFormat, options.Tenant),
                                                      options.BackchannelCertificateValidator, options.BackchannelTimeout, options.BackchannelHttpHandler)),
                AuthenticationMode = options.AuthenticationMode,
                AuthenticationType = options.AuthenticationType,
                Description        = options.Description
            };

            app.UseOAuthBearerAuthentication(bearerOptions);

            return(app);
        }
        public IEnumerable <OwinMiddlewareRegistration> GetOwinMiddlewares()
        {
            var middlewares = new List <OwinMiddlewareRegistration>();

            AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.NameIdentifier;

            /*var openIdOptions = new OpenIdConnectAuthenticationOptions
             * {
             *  ClientId = _azureClientId,
             *  Authority = string.Format(CultureInfo.InvariantCulture, _azureADInstance, _azureTenant),
             *  PostLogoutRedirectUri = _logoutRedirectUri,
             *  Notifications = new OpenIdConnectAuthenticationNotifications()
             * };*/

            var cookieOptions = new CookieAuthenticationOptions();

            var bearerAuthOptions = new WindowsAzureActiveDirectoryBearerAuthenticationOptions
            {
                TokenValidationParameters = new TokenValidationParameters
                {
                    ValidAudience = string.Format(_sslEnabled ? "https://{0}/{1}" : "http://{0}/{1}", _azureTenant, _azureAppName)
                }
            };

            /*if (_azureWebSiteProtectionEnabled)
             * {
             *  middlewares.Add(new OwinMiddlewareRegistration
             *  {
             *      Priority = "9",
             *      Configure = app => { app.SetDataProtectionProvider(new MachineKeyProtectionProvider()); }
             *  });
             * }*/

            middlewares.Add(new OwinMiddlewareRegistration
            {
                Priority  = "10",
                Configure = app => {
                    app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

                    app.UseCookieAuthentication(cookieOptions);

                    //app.UseOpenIdConnectAuthentication(openIdOptions);
                    if (!String.IsNullOrWhiteSpace(_signupPolicies))
                    {
                        app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
                        {
                            // For each policy, give OWIN the policy-specific metadata address, and
                            // set the authentication type to the id of the policy
                            MetadataAddress    = String.Format(_azureADInstance, _azureTenant, _signupPolicies),
                            AuthenticationType = _signupPolicies,

                            // These are standard OpenID Connect parameters, with values pulled from web.config
                            ClientId              = _azureClientId,
                            RedirectUri           = _logoutRedirectUri,
                            PostLogoutRedirectUri = _logoutRedirectUri,
                            Scope             = "openid",
                            ResponseType      = "id_token",
                            ProtocolValidator = new Microsoft.IdentityModel.Protocols.OpenIdConnectProtocolValidator()
                            {
                                RequireNonce = false
                            },
                            // This piece is optional - it is used for displaying the user's name in the navigation bar.
                            TokenValidationParameters = new TokenValidationParameters
                            {
                                NameClaimType = "name",
                            },
                        });
                    }
                    if (!String.IsNullOrWhiteSpace(_signinPolicies))
                    {
                        app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
                        {
                            // For each policy, give OWIN the policy-specific metadata address, and
                            // set the authentication type to the id of the policy
                            MetadataAddress    = String.Format(_azureADInstance, _azureTenant, _signinPolicies),
                            AuthenticationType = _signinPolicies,

                            // These are standard OpenID Connect parameters, with values pulled from web.config
                            ClientId              = _azureClientId,
                            RedirectUri           = _logoutRedirectUri,
                            PostLogoutRedirectUri = _logoutRedirectUri,
                            Scope             = "openid",
                            ResponseType      = "id_token",
                            ProtocolValidator = new Microsoft.IdentityModel.Protocols.OpenIdConnectProtocolValidator()
                            {
                                RequireNonce = false
                            },
                            // This piece is optional - it is used for displaying the user's name in the navigation bar.
                            TokenValidationParameters = new TokenValidationParameters
                            {
                                NameClaimType = "name",
                            },
                        });
                    }
                    if (!String.IsNullOrWhiteSpace(_profilePolicies))
                    {
                        app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
                        {
                            // For each policy, give OWIN the policy-specific metadata address, and
                            // set the authentication type to the id of the policy
                            MetadataAddress    = String.Format(_azureADInstance, _azureTenant, _profilePolicies),
                            AuthenticationType = _profilePolicies,

                            // These are standard OpenID Connect parameters, with values pulled from web.config
                            ClientId              = _azureClientId,
                            RedirectUri           = _logoutRedirectUri,
                            PostLogoutRedirectUri = _logoutRedirectUri,
                            Scope             = "openid",
                            ResponseType      = "id_token",
                            ProtocolValidator = new Microsoft.IdentityModel.Protocols.OpenIdConnectProtocolValidator()
                            {
                                RequireNonce = false
                            },
                            // This piece is optional - it is used for displaying the user's name in the navigation bar.
                            TokenValidationParameters = new TokenValidationParameters
                            {
                                NameClaimType = "name",
                            },
                        });
                    }

                    //This is throwing an XML DTD is prohibited error?
                    //app.UseWindowsAzureActiveDirectoryBearerAuthentication(bearerAuthOptions);
                }
            });

            return(middlewares);
        }
        /// <summary>
        /// Adds Windows Azure Active Directory (WAAD) issued JWT bearer token middleware to your web application pipeline.
        /// </summary>
        /// <param name="app">The IAppBuilder passed to your configuration method.</param>
        /// <param name="options">An options class that controls the middleware behavior.</param>
        /// <returns>The original app parameter.</returns>
        public static IAppBuilder UseWindowsAzureActiveDirectoryBearerAuthentication(this IAppBuilder app, WindowsAzureActiveDirectoryBearerAuthenticationOptions options)
        {
            if (options == null)
            {
                throw new ArgumentNullException("options");
            }

            if (string.IsNullOrWhiteSpace(options.MetadataAddress))
            {
                if (string.IsNullOrWhiteSpace(options.Tenant))
                {
                    throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, Resources.Exception_OptionMustBeProvided, "Tenant"));
                }
                options.MetadataAddress = string.Format(CultureInfo.InvariantCulture, SecurityTokenServiceAddressFormat, options.Tenant);
            }

            var cachingSecurityTokenProvider = new WsFedCachingSecurityTokenProvider(options.MetadataAddress,
                                                                                     options.BackchannelCertificateValidator, options.BackchannelTimeout, options.BackchannelHttpHandler);

#pragma warning disable 618
            JwtFormat jwtFormat = null;
            if (options.TokenValidationParameters != null)
            {
                if (!string.IsNullOrWhiteSpace(options.Audience))
                {
                    // Carry over obsolete property if set
                    if (string.IsNullOrWhiteSpace(options.TokenValidationParameters.ValidAudience))
                    {
                        options.TokenValidationParameters.ValidAudience = options.Audience;
                    }
                    else if (options.TokenValidationParameters.ValidAudiences == null)
                    {
                        options.TokenValidationParameters.ValidAudiences = new[] { options.Audience };
                    }
                    else
                    {
                        options.TokenValidationParameters.ValidAudiences = options.TokenValidationParameters.ValidAudiences.Concat(new[] { options.Audience });
                    }
                }

                jwtFormat = new JwtFormat(options.TokenValidationParameters, cachingSecurityTokenProvider);
            }
            else
            {
                jwtFormat = new JwtFormat(options.Audience, cachingSecurityTokenProvider);
            }
#pragma warning restore 618
            if (options.TokenHandler != null)
            {
                jwtFormat.TokenHandler = options.TokenHandler;
            }

            var bearerOptions = new OAuthBearerAuthenticationOptions
            {
                Realm              = options.Realm,
                Provider           = options.Provider,
                AccessTokenFormat  = jwtFormat,
                AuthenticationMode = options.AuthenticationMode,
                AuthenticationType = options.AuthenticationType,
                Description        = options.Description
            };

            app.UseOAuthBearerAuthentication(bearerOptions);

            return(app);
        }