コード例 #1
0
        public void ConfigureAuth(IAppBuilder app)
        {
            ApplicationDbContext db = new ApplicationDbContext();

            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

            app.UseCookieAuthentication(new CookieAuthenticationOptions());

            app.UseOpenIdConnectAuthentication(
                new OpenIdConnectAuthenticationOptions
            {
                ClientId                  = clientId,
                Authority                 = Authority,
                PostLogoutRedirectUri     = postLogoutRedirectUri,
                TokenValidationParameters = new System.IdentityModel.Tokens.TokenValidationParameters
                {
                    // instead of using the default validation (validating against a single issuer value, as we do in line of business apps),
                    // we inject our own multitenant validation logic
                    ValidateIssuer = false,
                },
                Notifications = new OpenIdConnectAuthenticationNotifications()
                {
                    // If there is a code in the OpenID Connect response, redeem it for an access token and refresh token, and store those away.
                    AuthorizationCodeReceived = (context) =>
                    {
                        var code = context.Code;
                        ClientCredential credential       = new ClientCredential(clientId, appKey);
                        string signedInUserID             = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value;
                        AuthenticationContext authContext = new AuthenticationContext(Authority, new ADALTokenCache(signedInUserID));
                        AuthenticationResult result       = authContext.AcquireTokenByAuthorizationCode(
                            code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential, graphResourceId);

                        //cache the token in session state
                        HttpContext.Current.Session[SettingsHelper.UserTokenCacheKey] = result;

                        return(Task.FromResult(0));
                    },
                    RedirectToIdentityProvider = (context) =>
                    {
                        FormDataCookie cookie = new FormDataCookie(SettingsHelper.SavedFormDataName);
                        cookie.SaveRequestFormToCookie();
                        return(Task.FromResult(0));
                    }
                }
            });
        }
コード例 #2
0
        public static ActivationParameters LoadActivationParameters(HttpContext context)
        {
            ActivationParameters parameters = null;

            FormDataCookie cookie = new FormDataCookie(SettingsHelper.SavedFormDataName);

            if (context.Request.Form != null && context.Request.Form.AllKeys.Count <string>() != 0)
            {
                // get from current request's form data
                parameters = new ActivationParameters(context.Request.Form);
            }
            else if (cookie.Load() && cookie.IsLoaded && cookie.FormData.AllKeys.Count <string>() > 0)
            {
                // if form data does not exist, it must be because of the sign in redirection, at the time form data is saved in the cookie
                parameters = new ActivationParameters(cookie.FormData);
                // clear the cookie after using it
                cookie.Clear();
            }
            else
            {
                parameters = (ActivationParameters)context.Session[SettingsHelper.SavedFormDataName];
            }
            return(parameters);
        }
コード例 #3
0
        public void ConfigureAuth(IAppBuilder app)
        {
            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

            app.Use(typeof(ConditionalMiddlewareInvoker));

            app.UseCookieAuthentication(new CookieAuthenticationOptions());

            app.UseOpenIdConnectAuthentication(
                new OpenIdConnectAuthenticationOptions
            {
                ClientId  = AADAppSettings.ClientId,
                Authority = AADAppSettings.Authority,

                // ProtocolValidator = new OpenIdConnectProtocolValidator()
                // {
                //    RequireNonce = false,
                // },

                TokenValidationParameters = new System.IdentityModel.Tokens.TokenValidationParameters
                {
                    // instead of using the default validation (validating against a single issuer value, as we do in line of business apps (single tenant apps)),
                    // we turn off validation
                    //
                    // NOTE:
                    // * In a multitenant scenario you can never validate against a fixed issuer string, as every tenant will send a different one.
                    // * If you don’t care about validating tenants, as is the case for apps giving access to 1st party resources, you just turn off validation.
                    // * If you do care about validating tenants, think of the case in which your app sells access to premium content and you want to limit access only to the tenant that paid a fee,
                    //       you still need to turn off the default validation but you do need to add logic that compares the incoming issuer to a list of tenants that paid you,
                    //       and block access if that’s not the case.
                    // * Refer to the following sample for a custom validation logic: https://github.com/AzureADSamples/WebApp-WebAPI-MultiTenant-OpenIdConnect-DotNet

                    ValidateIssuer = false
                },

                Notifications = new OpenIdConnectAuthenticationNotifications()
                {
                    //If there is a code in the OpenID Connect response, redeem it for an access token and refresh token, and store those away.
                    AuthorizationCodeReceived = (context) =>
                    {
                        var code = context.Code;

                        ClientCredential credential = new ClientCredential(AADAppSettings.ClientId, AADAppSettings.AppKey);
                        string tenantId             = context.AuthenticationTicket.Identity.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;
                        string signInUserId         = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value;

                        AuthenticationContext authContext = new AuthenticationContext(string.Format(AADAppSettings.AuthorizationUri, tenantId), new ADALTokenCache(signInUserId));

                        // Get the access token for AAD Graph. Doing this will also initialize the token cache associated with the authentication context
                        // In theory, you could acquire token for any service your application has access to here so that you can initialize the token cache
                        AuthenticationResult result = authContext.AcquireTokenByAuthorizationCode(code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential, AADAppSettings.AADGraphResourceId);

                        return(Task.FromResult(0));
                    },

                    RedirectToIdentityProvider = (context) =>
                    {
                        // This ensures that the address used for sign in and sign out is picked up dynamically from the request
                        // this allows you to deploy your app (to Azure Web Sites, for example)without having to change settings
                        // Remember that the base URL of the address used here must be provisioned in Azure AD beforehand.
                        string appBaseUrl = context.Request.Scheme + "://" + context.Request.Host + context.Request.PathBase;
                        context.ProtocolMessage.RedirectUri           = appBaseUrl + "/";
                        context.ProtocolMessage.PostLogoutRedirectUri = appBaseUrl;

                        // Save the form in the cookie to prevent it from getting lost in the login redirect
                        FormDataCookie cookie = new FormDataCookie(AADAppSettings.SavedFormDataName);
                        cookie.SaveRequestFormToCookie();

                        return(Task.FromResult(0));
                    }

                    // AuthenticationFailed = (context) =>
                    // {
                    //    // Suppress the exception if you don't want to see the error
                    //   // context.HandleResponse();
                    //    return Task.FromResult(0);
                    // }
                }
            });
        }