// GET: Admin
        public async Task <ActionResult> Index()
        {
            string[] scopes = adminScopes.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
            SessionTokenCacheProvider      sessionTokenCacheProvider = new SessionTokenCacheProvider(this.HttpContext);
            IConfidentialClientApplication cca = AuthorizationCodeProvider.CreateClientApplication(clientId, redirectUri, new ClientCredential(appKey), sessionTokenCacheProvider);

            try
            {
                AuthenticationResult result = await cca.AcquireTokenSilentAsync(scopes, (await cca.GetAccountsAsync()).FirstOrDefault());
            }
            catch (Exception)
            {
                try
                {// when failing, manufacture the URL and assign it
                    string authReqUrl = await OAuth2RequestManager.GenerateAuthorizationRequestUrl(scopes, cca as ConfidentialClientApplication, this.HttpContext, Url);

                    ViewBag.AuthorizationRequest = authReqUrl;
                }
                catch (Exception ee)
                {
                }
            }

            return(View("Admin"));
        }
示例#2
0
        public async override Task Invoke(IOwinContext context)
        {
            string code = context.Request.Query["code"];

            if (code != null)
            {
                //extract state
                string state         = context.Request.Query["state"];
                string session_state = context.Request.Query["session_state"];

                HttpContextBase hcb = context.Environment["System.Web.HttpContextBase"] as HttpContextBase;

                SessionTokenCacheProvider      sessionTokenCacheProvider = new SessionTokenCacheProvider(hcb);
                IConfidentialClientApplication cca = AuthorizationCodeProvider.CreateClientApplication(options.ClientId, options.RedirectUri, new ClientCredential(options.ClientSecret), sessionTokenCacheProvider);

                //validate state
                CodeRedemptionData crd = OAuth2RequestManager.ValidateState(state, hcb);

                if (crd != null)
                {//if valid
                 //redeem code
                    try
                    {
                        AuthorizationCodeProvider authorizationCodeProvider = new AuthorizationCodeProvider(cca, crd.Scopes);
                        await authorizationCodeProvider.GetTokenByAuthorizationCodeAsync(code);

                        HttpContext.Current.Session.Add("IsAdmin", true);
                    }
                    catch (Exception ee)
                    {
                    }
                    //redirect to original requestor
                    context.Response.StatusCode = 302;
                    context.Response.Headers.Set("Location", crd.RequestOriginatorUrl);
                }
                else
                {
                    context.Response.StatusCode = 302;
                    context.Response.Headers.Set("Location", "/Error?message=" + "code_redeem_failed");
                }
            }
            else
            {
                await this.Next.Invoke(context);
            }
        }
示例#3
0
        // Get an authenticated Microsoft Graph Service client.
        public static GraphServiceClient GetAuthenticatedClient()
        {
            if (!redirectUri.EndsWith("/"))
            {
                redirectUri = redirectUri + "/";
            }
            bool?  isAdmin   = HttpContext.Current.Session["IsAdmin"] as bool?;
            string allScopes = nonAdminScopes;

            if (isAdmin.GetValueOrDefault())
            {
                allScopes += " " + adminScopes;
            }
            string[] scopes = allScopes.Split(new char[] { ' ' });

            HttpContextBase           context = HttpContext.Current.GetOwinContext().Environment["System.Web.HttpContextBase"] as HttpContextBase;
            SessionTokenCacheProvider sessionTokenCacheProvider = new SessionTokenCacheProvider(context);

            IConfidentialClientApplication cca = AuthorizationCodeProvider.CreateClientApplication(appId, redirectUri, new ClientCredential(appSecret), sessionTokenCacheProvider);

            return(new GraphServiceClient(new AuthorizationCodeProvider(cca, scopes)));
        }
        public void ConfigureAuth(IAppBuilder app)
        {
            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

            app.UseCookieAuthentication(new CookieAuthenticationOptions());

            app.UseOAuth2CodeRedeemer(
                new OAuth2CodeRedeemerOptions
            {
                ClientId     = appId,
                ClientSecret = appSecret,
                RedirectUri  = redirectUri
            }
                );

            app.UseOpenIdConnectAuthentication(
                new OpenIdConnectAuthenticationOptions
            {
                // The `Authority` represents the v2.0 endpoint - https://login.microsoftonline.com/common/v2.0
                // The `Scope` describes the permissions that your app will need. See https://azure.microsoft.com/documentation/articles/active-directory-v2-scopes/
                ClientId                  = appId,
                Authority                 = String.Format(CultureInfo.InvariantCulture, aadInstance, "common", "/v2.0"),
                RedirectUri               = redirectUri,
                Scope                     = scopes,
                PostLogoutRedirectUri     = redirectUri,
                TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer = false,
                    // In a real application you would use IssuerValidator for additional checks,
                    // like making sure the user's organization has signed up for your app.
                    //     IssuerValidator = (issuer, token, tvp) =>
                    //     {
                    //         if (MyCustomTenantValidation(issuer))
                    //             return issuer;
                    //         else
                    //             throw new SecurityTokenInvalidIssuerException("Invalid issuer");
                    //     },
                },
                Notifications = new OpenIdConnectAuthenticationNotifications
                {
                    AuthorizationCodeReceived = async(context) =>
                    {
                        var code        = context.Code;
                        string[] scopes = nonAdminScopes.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

                        SessionTokenCacheProvider sessionTokenCacheProvider = new SessionTokenCacheProvider(context.OwinContext.Environment["System.Web.HttpContextBase"] as HttpContextBase);
                        IConfidentialClientApplication cca = AuthorizationCodeProvider.CreateClientApplication(appId, redirectUri, new ClientCredential(appSecret), sessionTokenCacheProvider);
                        AuthorizationCodeProvider authorizationCodeProvider = new AuthorizationCodeProvider(cca, scopes);
                        AuthenticationResult result = await authorizationCodeProvider.GetTokenByAuthorizationCodeAsync(code);

                        // Check whether the login is from the MSA tenant.
                        // The sample uses this attribute to disable UI buttons for unsupported operations when the user is logged in with an MSA account.
                        var currentTenantId = context.AuthenticationTicket.Identity.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;
                        if (currentTenantId == "9188040d-6c67-4c5b-b112-36a304b66dad")
                        {
                            HttpContext.Current.Session.Add("AccountType", "msa");
                        }
                        // Set IsAdmin session variable to false, since the user hasn't consented to admin scopes yet.
                        HttpContext.Current.Session.Add("IsAdmin", false);
                    },
                    AuthenticationFailed = (context) =>
                    {
                        context.HandleResponse();
                        context.Response.Redirect("/Error?message=" + context.Exception.Message);
                        return(Task.FromResult(0));
                    }
                }
            });
        }