public async Task<ActionResult> Authorize()
        {
            var authContext = new AuthenticationContext(Settings.AzureADAuthority);
            var authStateString = Request.QueryString["state"];
            var authState = JsonConvert.DeserializeObject<AuthState>(authStateString);
            try
            {
                // Get the token.
                var authResult = await authContext.AcquireTokenByAuthorizationCodeAsync(
                    Request.Params["code"],                                         // the auth 'code' parameter from the Azure redirect.
                    loginRedirectUri,                                               // same redirectUri as used before in Login method.
                    new ClientCredential(Settings.AzureADClientId, Settings.AzureADClientSecret), // use the client ID and secret to establish app identity.
                    Settings.GraphApiResource);                                     // provide the identifier of the resource we want to access

                await SaveAuthToken(authState, authResult);

                authState.authStatus = "success";

            }
            catch (Exception ex)
            {
                System.Diagnostics.Trace.WriteLine(ex.ToString());
                authState.authStatus = "failure";
            }

            return RedirectToAction(nameof(AuthorizeComplete), new { authState = JsonConvert.SerializeObject(authState) });
        }
        public async Task JsonWebTokenWithX509PublicCertSendX5CTestAsync()
        {
            var certificate     = new X509Certificate2("valid_cert.pfx", TestConstants.DefaultPassword);
            var clientAssertion = new ClientAssertionCertificate(TestConstants.DefaultClientId, certificate);
            var context         = new AuthenticationContext(TestConstants.TenantSpecificAuthority, new TokenCache());

            var validCertClaim = "\"x5c\":\"" + Convert.ToBase64String(certificate.GetRawCertData());

            //Check for x5c claim
            HttpMessageHandlerFactory.AddMockHandler(X5CMockHandler);
            AuthenticationResult result = await context.AcquireTokenAsync(TestConstants.DefaultResource, clientAssertion, true).ConfigureAwait(false);

            Assert.IsNotNull(result.AccessToken);

            HttpMessageHandlerFactory.AddMockHandler(X5CMockHandler);
            result = await context.AcquireTokenByAuthorizationCodeAsync(TestConstants.DefaultAuthorizationCode, TestConstants.DefaultRedirectUri, clientAssertion, TestConstants.DefaultResource, true).ConfigureAwait(false);

            Assert.IsNotNull(result.AccessToken);

            //Check for empty x5c claim
            HttpMessageHandlerFactory.AddMockHandler(EmptyX5CMockHandler);
            context.TokenCache.Clear();
            result = await context.AcquireTokenAsync(TestConstants.DefaultResource, clientAssertion, false).ConfigureAwait(false);

            Assert.IsNotNull(result.AccessToken);

            HttpMessageHandlerFactory.AddMockHandler(EmptyX5CMockHandler);
            result = await context.AcquireTokenByAuthorizationCodeAsync(TestConstants.DefaultAuthorizationCode, TestConstants.DefaultRedirectUri, clientAssertion, TestConstants.DefaultResource, false).ConfigureAwait(false);

            Assert.IsNotNull(result.AccessToken);
        }
Пример #3
0
        // Redeem code for token asynchronosly for performance, must not do synchronous call for Production
        private async Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedNotification context)
        {
            Startup.LastContext = context;
            code      = context.Code;
            returnUri = new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path));

            // Token Service appKey is required to authenticate with Azure AD for redeeming the authorization code
            // Note that the code is returned to LE-SfBApp, but the JavaScript client cannot make use of it
            ClientCredential credential = new ClientCredential(clientId, appKey);

            // userObjectID is the objectGUID of the O365 user in Azure AD
            string userObjectID = context.AuthenticationTicket.Identity.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;

            // intialize with common to retrieve MRRT, index Cache with both user GUID and resource url due to UCWA usage pattern
            // Startup.sessionCache = new NaiveSessionCache(userObjectID);
            // Startup.sessionCache = new NaiveSessionCache(userObjectID);
            // Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext authContext = new Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext(Startup.Authority, Startup.sessionCache);
            AuthContext authContext = new AuthContext(Authority,
                                                      new DistributedTokenCache(cacheconnStr, userObjectID));

            AuthenticationResult result = await authContext.AcquireTokenByAuthorizationCodeAsync(code, returnUri, credential, ucwaResourceUrl);

            // Azure AD schema change
            // string tenantID = context.AuthenticationTicket.Identity.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;
            // string signedInUserID = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value;
            // AuthenticationContext authContext = new AuthenticationContext(aadInstance + tenantID, new ADALTokenCache(signedInUserID));

            Startup.accessToken  = result.AccessToken;
            Startup.refreshToken = result.RefreshToken;
            Startup.idToken      = result.IdToken;
        }
Пример #4
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,

            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.AcquireTokenByAuthorizationCodeAsync(
                      code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential, resourceAzureGraphAPI).Result;

                return Task.FromResult(0);
              }
            }
              });
        }
 public async Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedNotification notification)
 {
     // Acquire a Token for the Graph API and cache it.  In the TodoListController, we'll use the cache to acquire a token to the Todo List API
     string userObjectId = notification.AuthenticationTicket.Principal.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
     ClientCredential clientCred = new ClientCredential(ClientId, AppKey);
     AuthenticationContext authContext = new AuthenticationContext(Authority, new NaiveSessionCache(userObjectId, notification.HttpContext.Session));
     AuthenticationResult authResult = await authContext.AcquireTokenByAuthorizationCodeAsync(
         notification.Code, new Uri(notification.RedirectUri), clientCred, Startup.GraphResourceId);
 }
 public async Task<HttpResponseMessage> CompleteAuth(string code)
 {
     AuthenticationContext AC = new AuthenticationContext("https://login.windows.net/common/oauth2/authorize/");
     ClientCredential cc = new ClientCredential(clientId, clientSecret);
     AuthenticationResult ar = await AC.AcquireTokenByAuthorizationCodeAsync(code, new Uri(redirectUrl), cc);
     PowerBIController.authorization = new AuthResult { Expires = ar.ExpiresOn.UtcDateTime, AccessToken = ar.AccessToken, RefreshToken = ar.RefreshToken };
     await WriteTokenToStorage(PowerBIController.authorization);
     return Request.CreateResponse(HttpStatusCode.OK, "Successfully Authenticated");
 }
        internal static void ConfigureAuth(IAppBuilder app)
        {
            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
            app.UseCookieAuthentication(new CookieAuthenticationOptions()
            {
                CookieManager = new SystemWebCookieManager()
            });

            app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions()
            {
                Authority = OfficeSettings.Authority,
                ClientId = OfficeSettings.ClientId,

                Notifications = new OpenIdConnectAuthenticationNotifications()
                {
                    AuthorizationCodeReceived = async (context) =>
                    {
                        string code = context.Code;
                        ClientCredential credential = new ClientCredential(OfficeSettings.ClientId,
                                                              OfficeSettings.ClientSecret);
                        string signInUserId = context.AuthenticationTicket
                                                      .Identity
                                                      .FindFirst(ClaimTypes.NameIdentifier)
                                                      .Value;

                        AuthenticationContext ctx = new AuthenticationContext(OfficeSettings.Authority,
                                                            new ADALTokenCache(signInUserId));

                        var result = await ctx.AcquireTokenByAuthorizationCodeAsync(code,
                                                                              new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)),
                                                                              credential,
                                                                              OfficeSettings.GraphResourceId);

                        return;
                    },
                    RedirectToIdentityProvider = (context) =>
                    {
                        string appBaseUrl = context.Request.Scheme + "://" + context.Request.Host + context.Request.PathBase;
                        context.ProtocolMessage.RedirectUri = appBaseUrl + "/";
                        context.ProtocolMessage.PostLogoutRedirectUri = appBaseUrl + "/";

                        return Task.FromResult(0);
                    },
                    AuthenticationFailed = (context) =>
                    {
                        if (context.Exception.Message.StartsWith("OICE_20004") || context.Exception.Message.Contains("IDX10311"))
                        {
                            context.SkipToNextMiddleware();
                            return Task.FromResult(0);
                        }
                        context.HandleResponse();
                        context.Response.Redirect("/Home/Error?message=" + context.Exception.Message);
                        return Task.FromResult(0);
                    }
                }
            });
        }
 private async Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedNotification notification)
 {
     string userObjectId = notification.AuthenticationTicket.Identity.FindFirst("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier").Value;
     string tenantID = notification.AuthenticationTicket.Identity.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;
     string authority = String.Format(CultureInfo.InvariantCulture, aadInstance, tenantID, string.Empty);
     ClientCredential cred = new ClientCredential(clientId, clientSecret);
    
     // Here you ask for a token using the web app's clientId as the scope, since the web app and service share the same clientId.
     var authContext = new Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext(authority, false, new NaiveSessionCache(userObjectId));
     var authResult = await authContext.AcquireTokenByAuthorizationCodeAsync(notification.Code, new Uri(redirectUri), cred, new string[] { clientId });
 }
Пример #9
0
        public void ConfigureAuth(IAppBuilder app)
        {
            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

            app.UseCookieAuthentication(new CookieAuthenticationOptions { });

            app.UseOpenIdConnectAuthentication(
                new OpenIdConnectAuthenticationOptions
                {
                    ClientId = clientId,
                    Authority = authority,
                    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()
                    {
                        SecurityTokenValidated = (context) =>
                        {
                            return Task.FromResult(0);
                        },
                        AuthorizationCodeReceived = (context) =>
                        {
                            var code = context.Code;

                            ClientCredential credential = new ClientCredential(clientId, appKey);
                            string tenantID = context.AuthenticationTicket.Identity.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;
                            string signedInUserID = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value;

                            // 2016-10-02 Commenting out because the ADALTokenCache threw an exception about empty DB connection string.
                            // AuthenticationContext authContext = new AuthenticationContext(aadInstance + tenantID, new ADALTokenCache(signedInUserID));
                            AuthenticationContext authContext = new AuthenticationContext(aadInstance + tenantID);
                            return
                                authContext.AcquireTokenByAuthorizationCodeAsync(
                                    code,
                                    new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)),
                                    credential,
                                    graphResourceID);

                            //return Task.FromResult(0);
                        },
                        AuthenticationFailed = (context) =>
                        {
                            telemetry.TrackException(context.Exception);
                            context.OwinContext.Response.Redirect("/Home/Error");
                            context.HandleResponse(); // Suppress the exception
                            return Task.FromResult(0);
                        }
                    }
                });
        }
Пример #10
0
        public async Task <HttpResponseMessage> PostAuthorize([FromBody] AuthorizeArgs a)
        {
            var cookie = SecureUrlToken.Decode <ResumptionCookie>(a.state);

            if (!string.IsNullOrEmpty(a.error))
            {
                await Conversation.ResumeAsync(cookie, new AuthenticationResultModel(cookie.GetMessage()) { Error = a.error, ErrorDescription = a.error_description });

                return(new HttpResponseMessage(HttpStatusCode.OK)
                {
                    Content = new StringContent("<html><head><script type='text/javascript'>window.close();</script></head><body>An error occurred during authentication.  You can close this browser window</body></html>", Encoding.UTF8, "text/html")
                });
            }

            // Get access token
            var authContext = new AuthenticationContext(ConfigurationManager.AppSettings["Authority"]);
            var authResult  = await authContext.AcquireTokenByAuthorizationCodeAsync(
                a.code,
                new Uri(this.Request.RequestUri.GetLeftPart(UriPartial.Path)),
                new ClientCredential(
                    ConfigurationManager.AppSettings["ClientId"],
                    ConfigurationManager.AppSettings["ClientSecret"]));

            var upn = authResult?.UserInfo?.DisplayableId;

            var result = new AuthenticationResultModel(cookie.GetMessage())
            {
                AccessToken = authResult.IdToken
            };

            if (upn == cookie.GetMessage().From.Id)
            {
                await Conversation.ResumeAsync(cookie, result);

                return(new HttpResponseMessage(HttpStatusCode.OK)
                {
                    Content = new StringContent("<html><head><script type='text/javascript'>window.close();</script></head><body>You can close this browser window</body></html>", Encoding.UTF8, "text/html")
                });
            }
            else
            {
                var rnd = new Random();
                result.SecurityKey = string.Join("", Enumerable.Range(0, 6).Select(i => rnd.Next(10).ToString()));
                await Conversation.ResumeAsync(cookie, result);

                return(new HttpResponseMessage(HttpStatusCode.OK)
                {
                    Content = new StringContent($"<html><head></head><body><!--We can't auto-auth you because {upn} != {cookie.GetMessage().From.Id}. -->Please copy and paste this key into the conversation with the bot: {result.SecurityKey}.</body></html>", Encoding.UTF8, "text/html")
                });
            }
        }
        // GET: /TOnboarding/ProcessCode
        public ActionResult ProcessCode(string code, string error, string error_description, string resource, string state)
        {
            // Is this a response to a request we generated? Let's see if the state is carrying an ID we previously saved
            // ---if we don't, return an error
            if (db.Tenants.FirstOrDefault(a => a.IssValue == state) == null)
            {
                // TODO: prettify
                return View("Error");
            }
            else
            {
                // ---if the response is indeed from a request we generated
                // ------get a token for the Graph, that will provide us with information abut the caller
                ClientCredential credential = new ClientCredential(ConfigurationManager.AppSettings["ida:ClientID"],
                                                                   ConfigurationManager.AppSettings["ida:Password"]);
                AuthenticationContext authContext = new AuthenticationContext("https://login.chinacloudapi.cn/common/");
                AuthenticationResult result = authContext.AcquireTokenByAuthorizationCodeAsync(
                    code, new Uri(Request.Url.GetLeftPart(UriPartial.Path)), credential).Result;

                var myTenant = db.Tenants.FirstOrDefault(a => a.IssValue == state);
                // if this was an admin consent, save the tenant
                if (myTenant.AdminConsented)
                {
                    // ------read the tenantID out of the Graph token and use it to create the issuer string
                    string issuer = String.Format("https://sts.chinacloudapi.cn/{0}/", result.TenantId);
                    myTenant.IssValue = issuer;
                }
                else
                //otherwise, remove the temporary entry and save just the user
                {
                    if (db.Users.FirstOrDefault(a => (a.UPN == result.UserInfo.DisplayableId) && (a.TenantID == result.TenantId)) == null)
                    {
                        db.Users.Add(new User { UPN = result.UserInfo.DisplayableId, TenantID = result.TenantId });
                    }
                    db.Tenants.Remove(myTenant);
                }

                // remove older, unclaimed entries
                DateTime tenMinsAgo = DateTime.Now.Subtract(new TimeSpan(0, 10, 0)); // workaround for Linq to entities
                var garbage = db.Tenants.Where(a => (!a.IssValue.StartsWith("https") && (a.Created < tenMinsAgo)));
                foreach (Tenant t in garbage)
                    db.Tenants.Remove(t);

                db.SaveChanges();
                // ------return a view claiming success, inviting the user to sign in
                return View();
            }
        }
        public async Task JsonWebTokenWithDeveloperImplementedClientAssertionTestAsync()
        {
            var certificate     = new X509Certificate2("valid_cert.pfx", TestConstants.DefaultPassword);
            var clientAssertion = new ClientAssertionTestImplementation();
            var context         = new AuthenticationContext(TestConstants.TenantSpecificAuthority, new TokenCache());

            HttpMessageHandlerFactory.AddMockHandler(EmptyX5CMockHandler);
            AuthenticationResult result = await context.AcquireTokenAsync(TestConstants.DefaultResource, clientAssertion, true).ConfigureAwait(false);

            Assert.IsNotNull(result.AccessToken);

            HttpMessageHandlerFactory.AddMockHandler(EmptyX5CMockHandler);
            result = await context.AcquireTokenByAuthorizationCodeAsync(TestConstants.DefaultAuthorizationCode, TestConstants.DefaultRedirectUri, clientAssertion, TestConstants.DefaultResource, true).ConfigureAwait(false);

            Assert.IsNotNull(result.AccessToken);
        }
Пример #13
0
        public async Task<ActionResult> Authorize()
        {
            // Create new authentication context
            var authContext = new AuthenticationContext(Settings.Authority);

            // The URL where Azure redirects to after successful login
            Uri loginRedirectUri = new Uri(Url.Action("Authorize", "Home", null, Request.Url.Scheme));

            // Get the access token
            var authResult = await authContext.AcquireTokenByAuthorizationCodeAsync(Request.Params["code"], loginRedirectUri, new ClientCredential(Settings.ClientId, Settings.ClientSecret), Settings.GraphUri);

            // Save the token in the session.
            Session["access_token"] = authResult.AccessToken;

            return RedirectToAction("Index");
        }
Пример #14
0
        /// <summary>
        /// Fired when the user authenticates
        /// </summary>
        /// <param name="notification"></param>
        /// <returns></returns>
        private async Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedNotification notification)
        {
            // Get the user's object id (used to name the token cache)
            string userObjId = notification.AuthenticationTicket.Identity.FindFirst(Settings.AAD_OBJECTID_CLAIMTYPE).Value;

            // Create a token cache
            HttpContextBase   httpContext = notification.OwinContext.Get <HttpContextBase>(typeof(HttpContextBase).FullName);
            SessionTokenCache tokenCache  = new SessionTokenCache(userObjId, httpContext);

            // Exchange the auth code for a token
            ADAL.ClientCredential clientCred = new ADAL.ClientCredential(Settings.AAD_APP_ID, Settings.AAD_APP_SECRET);

            // Create the auth context
            ADAL.AuthenticationContext authContext = new ADAL.AuthenticationContext(
                string.Format(CultureInfo.InvariantCulture, Settings.AAD_INSTANCE, "common", ""), false, tokenCache);

            ADAL.AuthenticationResult authResult = await authContext.AcquireTokenByAuthorizationCodeAsync(
                notification.Code, notification.Request.Uri, clientCred, Settings.GRAPH_API_URL);
        }
Пример #15
0
        public async Task<ActionResult> Authorize()
        {
            var authContext = new AuthenticationContext(Settings.AzureADAuthority);

            // Get the token.
            var authResult = await authContext.AcquireTokenByAuthorizationCodeAsync(
                Request.Params["code"],                                         // the auth 'code' parameter from the Azure redirect.
                loginRedirectUri,                                               // same redirectUri as used before in Login method.
                new ClientCredential(Settings.ClientId, Settings.ClientSecret), // use the client ID and secret to establish app identity.
                Settings.O365UnifiedAPIResource);

            // Save the token in the session.
            Session[SessionKeys.Login.AccessToken] = authResult.AccessToken;

            // Get info about the current logged in user.
            Session[SessionKeys.Login.UserInfo] = await GraphHelper.GetUserInfoAsync(authResult.AccessToken);

            return RedirectToAction(nameof(Index), "PersonalData");
        }
Пример #16
0
        public void AdalClaimsChallengeExceptionThrownWithAuthCodeWhenClaimsChallengeRequiredTestAsync()
        {
            var             context         = new AuthenticationContext(TestConstants.DefaultAuthorityCommonTenant, new TokenCache());
            ClientAssertion clientAssertion = new ClientAssertion(TestConstants.DefaultClientId, "some-assertion");

            HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler()
            {
                Method          = HttpMethod.Post,
                ResponseMessage = new HttpResponseMessage(HttpStatusCode.BadRequest)
                {
                    Content = new StringContent(responseContent)
                }
            });

            var result = AssertException.TaskThrows <AdalClaimChallengeException>(() =>
                                                                                  context.AcquireTokenByAuthorizationCodeAsync("some-code", TestConstants.DefaultRedirectUri, clientAssertion, TestConstants.DefaultResource));

            Assert.AreEqual(claims.Replace("\\", ""), result.Claims);
        }
Пример #17
0
        private async Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedNotification context)
        {
            try
            {
                var code = context.Code;

                // Create a Client Credential Using an Application Key
                ClientCredential credential = new ClientCredential(clientId_admin, clientSecret_admin);
                string           userObjId  = context.AuthenticationTicket.Identity.GetClaim(Settings.ObjectIdentifier);

                Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext authContext = new Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext(string.Format(aadInstanceLocal, tenant), new AdalCosmosTokenCache(userObjId, Utils.GetFQDN(context.Request)));
                AuthenticationResult result = await authContext.AcquireTokenByAuthorizationCodeAsync(
                    code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential, Settings.GraphResource);
            }
            catch (Exception ex)
            {
                Logging.WriteToAppLog("Error caching auth code", System.Diagnostics.EventLogEntryType.Error, ex);
                throw;
            }
        }
        private async Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedNotification notification)
        {
            // Get the user's object id (used to name the token cache)
            string userObjId = notification.AuthenticationTicket.Identity
                               .FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;

            // Create a token cache
            HttpContextBase   httpContext = notification.OwinContext.Get <HttpContextBase>(typeof(HttpContextBase).FullName);
            SessionTokenCache tokenCache  = new SessionTokenCache(userObjId, httpContext);

            // Exchange the auth code for a token
            ADAL.ClientCredential clientCred = new ADAL.ClientCredential(appId, appSecret);

            // Create the auth context
            ADAL.AuthenticationContext authContext = new ADAL.AuthenticationContext(
                authority, false, tokenCache);

            ADAL.AuthenticationResult authResult = await authContext.AcquireTokenByAuthorizationCodeAsync(
                notification.Code, notification.Request.Uri, clientCred, "https://graph.microsoft.com");
        }
        public void ConfigureAuth(IAppBuilder app)
        {
            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

            app.UseCookieAuthentication(new CookieAuthenticationOptions());

            app.UseOpenIdConnectAuthentication(
                new OpenIdConnectAuthenticationOptions
            {
                ClientId              = clientId,
                Authority             = authority,
                PostLogoutRedirectUri = postLogoutRedirectUri,

                TokenValidationParameters = new TokenValidationParameters
                {
                    NameClaimType = "name",
                    RoleClaimType = "roles"
                },

                Notifications = new OpenIdConnectAuthenticationNotifications
                {
                    AuthorizationCodeReceived = async(context) =>
                    {
                        var code         = context.Code;
                        var userObjectID = context.AuthenticationTicket.Identity.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;

                        var clientCredential = new ADAL.ClientCredential(clientId, clientSecret);
                        var authContext      = new ADAL.AuthenticationContext(authority, new NaiveSessionCache(userObjectID));
                        var authResult       = await authContext.AcquireTokenByAuthorizationCodeAsync(
                            code,
                            new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)),
                            clientCredential,
                            targetResource);
                    }
                }
            });
        }
 public async System.Threading.Tasks.Task<ActionResult> Authorize(string code)
 {
     try
     {
         string powerBISchema = "Unable to retrieve schema";
         using (var client = new HttpClient())
         {
             var schemaResult = await client.GetAsync("https://raw.githubusercontent.com/jeffhollan/MSHealthAPI/master/Power%20BI%20Dataset%20Schema.json");
             powerBISchema = await schemaResult.Content.ReadAsStringAsync();
             AuthenticationContext AC = new AuthenticationContext("https://login.windows.net/common/oauth2/authorize/");
             ClientCredential cc = new ClientCredential(ConfigurationManager.AppSettings["clientId"], ConfigurationManager.AppSettings["clientSecret"]);
             AuthenticationResult ar = await AC.AcquireTokenByAuthorizationCodeAsync(code, new Uri(ConfigurationManager.AppSettings["redirect"].ToLower()), cc);
             client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", ar.AccessToken);
             var createResult = await client.PostAsync("https://api.powerbi.com/v1.0/myorg/datasets?defaultRetentionPolicy=None", new StringContent(powerBISchema, Encoding.UTF8, "application/json"));
             var resultString = await createResult.Content.ReadAsStringAsync();
             ViewBag.datasetid = (string)JObject.Parse(resultString)["id"];
         }
         return View();
     }
     catch (Exception ex)
     {
         return View("Error");
     }
 }
Пример #21
0
        public void Configuration(IAppBuilder app)
        {
            // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=316888
            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

            app.UseCookieAuthentication(new CookieAuthenticationOptions());

            app.UseOpenIdConnectAuthentication(
                new OpenIdConnectAuthenticationOptions
            {
                ClientId      = SettingsHelper.ClientId,
                Authority     = SettingsHelper.Authority,
                Notifications = new OpenIdConnectAuthenticationNotifications
                {
                    AuthorizationCodeReceived = async(context) =>
                    {
                        var code = context.Code;
                        string signedInUserID       = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value;
                        HttpContextBase httpContext = context.OwinContext.Environment["System.Web.HttpContextBase"] as HttpContextBase;
                        TokenCache tokenCache       = new SessionTokenCache(signedInUserID, httpContext);

                        Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext authContext = new Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext(SettingsHelper.Authority, tokenCache);
                        ClientCredential credential = new ClientCredential(SettingsHelper.ClientId, SettingsHelper.ClientSecret);
                        Uri redirectUri             = new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path));
                        AuthenticationResult result = await authContext.AcquireTokenByAuthorizationCodeAsync(code, redirectUri, credential, SettingsHelper.GraphResourceId);
                        // var token = result.AccessToken;
                    },
                    AuthenticationFailed = (context) =>
                    {
                        context.HandleResponse();
                        context.Response.Redirect("/Error?message=" + context.Exception.Message);
                        return(Task.FromResult(0));
                    }
                }
            });
        }
        public void ConfigureAuth(IAppBuilder app)
        {
            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

            app.UseCookieAuthentication(new CookieAuthenticationOptions());

            app.UseOpenIdConnectAuthentication(
                new OpenIdConnectAuthenticationOptions {

                    ClientId = AADAppSettings.ClientId,
                    Authority = AADAppSettings.Authority,

                    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 = async context => {

                            var serviceCredential = new ClientCredential(AADAppSettings.ClientId, AADAppSettings.AppKey);

                            string tenantID = context.AuthenticationTicket.Identity.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;
                            string nameIdentifier = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value;

                            AuthenticationContext authContext = new AuthenticationContext(
                                string.Format("{0}/{1}", AADAppSettings.AuthorizationUri, tenantID), 
                                new SimpleDatabaseTokenCache(nameIdentifier)
                            );

                            // 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 = await authContext.AcquireTokenByAuthorizationCodeAsync(
                                context.Code, 
                                new Uri(context.Request.Uri.GetLeftPart(UriPartial.Path)), 
                                serviceCredential,
                                AADAppSettings.SharePointResourceId
                            );

                            Debug.WriteLine("Auth result: {0}", result);
                        },

                        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 + "/Home/SPA";
                            context.ProtocolMessage.PostLogoutRedirectUri = appBaseUrl;

                            return Task.FromResult(0);
                        },

                        AuthenticationFailed = (context) => {
                            // Suppress the exception
                            context.HandleResponse(); 

                            return Task.FromResult(0);
                        }
                    }

                });
        }
Пример #23
0
        public async Task<ActionResult> Index(string code)
        {
            List<MyEvent> eventList = new List<MyEvent>();

            AuthenticationContext authContext = new AuthenticationContext(
               ConfigurationManager.AppSettings["ida:AuthorizationUri"] + "/common",
               true);

            ClientCredential creds = new ClientCredential(
                ConfigurationManager.AppSettings["ida:ClientID"],
                ConfigurationManager.AppSettings["ida:Password"]);

            DiscoveryClient disco = GetFromCache("DiscoveryClient") as DiscoveryClient;
            CapabilityDiscoveryResult eventsDisco =GetFromCache("EventsDiscovery") as CapabilityDiscoveryResult;

            //Redirect to login page if we do not have an 
            //authorization code for the Discovery service
            if (disco == null && code == null)
            {
                Uri redirectUri = authContext.GetAuthorizationRequestURL(
                    discoResource,
                    creds.ClientId,
                    new Uri(Request.Url.AbsoluteUri.Split('?')[0]),
                    UserIdentifier.AnyUser,
                    string.Empty);

                return Redirect(redirectUri.ToString());
            }

            //Create a DiscoveryClient using the authorization code
            if (disco == null && code != null)
            {

                disco = new DiscoveryClient(new Uri(discoEndpoint), async () =>
                {

                    var authResult = await authContext.AcquireTokenByAuthorizationCodeAsync(
                        code,
                        new Uri(Request.Url.AbsoluteUri.Split('?')[0]),
                        creds);

                    return authResult.AccessToken;
                });

            }

            if (disco != null && code != null & eventsDisco == null)
            {

                //Discover required capabilities
                eventsDisco = await disco.DiscoverCapabilityAsync("Calendar");
                SaveInCache("EventsDiscovery", eventsDisco);

                code = null;

                //Get authorization code for the calendar
                Uri redirectUri = authContext.GetAuthorizationRequestURL(
                    eventsDisco.ServiceResourceId,
                    creds.ClientId,
                    new Uri(Request.Url.AbsoluteUri.Split('?')[0]),
                    UserIdentifier.AnyUser,
                    string.Empty);

                return Redirect(redirectUri.ToString());
            }

            //Get the calendar events
            if (disco != null && code != null & eventsDisco != null)
            {
                OutlookServicesClient outlookClient = new OutlookServicesClient(eventsDisco.ServiceEndpointUri, async () =>
                {

                    var authResult = await authContext.AcquireTokenByAuthorizationCodeAsync(
                        code,
                        new Uri(Request.Url.AbsoluteUri.Split('?')[0]),
                        creds);

                    return authResult.AccessToken;
                });

                //Get the events for the next 8 hours
                var eventResults = await (from i in outlookClient.Me.Events
                                          where i.End >= DateTimeOffset.UtcNow && i.End <= DateTimeOffset.UtcNow.AddHours(8)
                                          select i).Take(5).ExecuteAsync();
                var events = eventResults.CurrentPage.OrderBy(e => e.Start);

                foreach (var e in events)
                {
                    eventList.Add(new MyEvent
                    {
                        Id = e.Id,
                        Body = e.Body == null ? string.Empty : e.Body.Content,
                        End = e.End,
                        Location = e.Location == null ? string.Empty : e.Location.DisplayName,
                        Start = e.Start,
                        Subject = e.Subject == null ? string.Empty : e.Subject

                    });
                }

                //cache the events
                SaveInCache("Events", eventList);
            }

            return View();

        }
Пример #24
0
        // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app)
        {
            // the web access to the site will use cookie authentication
            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

            app.UseCookieAuthentication(new CookieAuthenticationOptions());

            // we will use OpenIdConnect to authenticate with Azure AD
            app.UseOpenIdConnectAuthentication(
                new OpenIdConnectAuthenticationOptions
            {
                ClientId              = ConfigurationManager.AppSettings["ida:ClientID"],
                Authority             = authority,
                PostLogoutRedirectUri = ConfigurationManager.AppSettings["ida:PostLogoutRedirectUri"],
                RedirectUri           = ConfigurationManager.AppSettings["ida:PostLogoutRedirectUri"],
                Notifications         = new OpenIdConnectAuthenticationNotifications
                {
                    AuthenticationFailed = context =>
                    {
                        context.HandleResponse();
                        context.Response.Redirect("/Error/AuthFailure?message=" + Uri.EscapeUriString(context.Exception.Message));
                        return(Task.FromResult(0));
                    },
                    AuthorizationCodeReceived = async context =>
                    {
                        // We need this to create a token that is stored in the token cache for the current user
                        ClientCredential credential = new ClientCredential(ConfigurationManager.AppSettings["ida:ClientID"], ConfigurationManager.AppSettings["ida:AppKey"]);
                        string uniqueUserId         = context.AuthenticationTicket.Identity.FindFirst(objectIdentifierClaimType).Value;
                        Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext authContext = new Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext(authority, new TokenCacheService(uniqueUserId));

                        // we don't do anything with the access token, but we do this so that the access token is added to the cache so we can use it later if needed
                        AuthenticationResult result = await authContext.AcquireTokenByAuthorizationCodeAsync(
                            context.Code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential, graphUrl);
                    }
                }
            });

            // WebApi controllers will use bearer token authentication instead of cookie authentication
            app.Map("/api", inner =>
            {
                var config = new HttpConfiguration();

                // suppress the default auth type so that cookies will not work for WebApi
                config.SuppressDefaultHostAuthentication();
                config.Filters.Add(new HostAuthenticationFilter("OAuth2Bearer"));
                inner.UseWindowsAzureActiveDirectoryBearerAuthentication(
                    new WindowsAzureActiveDirectoryBearerAuthenticationOptions
                {
                    Tenant = ConfigurationManager.AppSettings["ida:Tenant"],
                    TokenValidationParameters = new TokenValidationParameters
                    {
                        ValidateAudience   = false,
                        AuthenticationType = "OAuth2Bearer"
                    },
                    AuthenticationType = "OAuth2Bearer"
                });

                config.MapHttpAttributeRoutes();

                config.Routes.MapHttpRoute(
                    name: "DefaultApi",
                    routeTemplate: "{controller}/{id}",
                    defaults: new { id = RouteParameter.Optional }
                    );

                inner.UseWebApi(config);
            });
        }
Пример #25
0
        public void Configure(IApplicationBuilder app, ILoggerFactory loggerfactory)
        {
            loggerfactory.AddConsole(Microsoft.Extensions.Logging.LogLevel.Information);

            // Simple error page
            app.Use(async (context, next) =>
            {
                try
                {
                    await next();
                }
                catch (Exception ex)
                {
                    if (!context.Response.HasStarted)
                    {
                        context.Response.Clear();
                        context.Response.StatusCode = 500;
                        await context.Response.WriteAsync(ex.ToString());
                    }
                    else
                    {
                        throw;
                    }
                }
            });

            app.UseCookieAuthentication(new CookieAuthenticationOptions());

            var clientId = Configuration["oidc:clientid"];
            var clientSecret = Configuration["oidc:clientsecret"];
            var authority = Configuration["oidc:authority"];
            var resource = "https://graph.windows.net";
            app.UseOpenIdConnectAuthentication(new OpenIdConnectOptions
            {
                ClientId = clientId,
                ClientSecret = clientSecret, // for code flow
                Authority = authority,
                ResponseType = OpenIdConnectResponseType.CodeIdToken,
                // GetClaimsFromUserInfoEndpoint = true,
                Events = new OpenIdConnectEvents()
                {
                    OnAuthorizationCodeReceived = async context =>
                    {
                        var request = context.HttpContext.Request;
                        var currentUri = UriHelper.BuildAbsolute(request.Scheme, request.Host, request.PathBase, request.Path);
                        var credential = new ClientCredential(clientId, clientSecret);
                        var authContext = new AuthenticationContext(authority, AuthPropertiesTokenCache.ForCodeRedemption(context.Properties));

                        var result = await authContext.AcquireTokenByAuthorizationCodeAsync(
                            context.ProtocolMessage.Code, new Uri(currentUri), credential, resource);

                        context.HandleCodeRedemption();
                    }
                }
            });

            app.Run(async context =>
            {
                if (context.Request.Path.Equals("/signout"))
                {
                    await context.Authentication.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
                    context.Response.ContentType = "text/html";
                    await context.Response.WriteAsync($"<html><body>Signing out {context.User.Identity.Name}<br>{Environment.NewLine}");
                    await context.Response.WriteAsync("<a href=\"/\">Sign In</a>");
                    await context.Response.WriteAsync($"</body></html>");
                    return;
                }

                if (!context.User.Identities.Any(identity => identity.IsAuthenticated))
                {
                    await context.Authentication.ChallengeAsync(OpenIdConnectDefaults.AuthenticationScheme, new AuthenticationProperties { RedirectUri = "/" });
                    return;
                }

                context.Response.ContentType = "text/html";
                await context.Response.WriteAsync($"<html><body>Hello Authenticated User {context.User.Identity.Name}<br>{Environment.NewLine}");
                await context.Response.WriteAsync("Claims:<br>" + Environment.NewLine);
                foreach (var claim in context.User.Claims)
                {
                    await context.Response.WriteAsync($"{claim.Type}: {claim.Value}<br>{Environment.NewLine}");
                }

                await context.Response.WriteAsync("Tokens:<br>" + Environment.NewLine);
                try
                {
                    // Use ADAL to get the right token
                    var authContext = new AuthenticationContext(authority, AuthPropertiesTokenCache.ForApiCalls(context, CookieAuthenticationDefaults.AuthenticationScheme));
                    var credential = new ClientCredential(clientId, clientSecret);
                    string userObjectID = context.User.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
                    var result = await authContext.AcquireTokenSilentAsync(resource, credential, new UserIdentifier(userObjectID, UserIdentifierType.UniqueId));

                    await context.Response.WriteAsync($"access_token: {result.AccessToken}<br>{Environment.NewLine}");
                }
                catch (Exception ex)
                {
                    await context.Response.WriteAsync($"AquireToken error: {ex.Message}<br>{Environment.NewLine}");
                }

                await context.Response.WriteAsync("<a href=\"/signout\">Sign Out</a>");
                await context.Response.WriteAsync($"</body></html>");
            });
        }
        public static async Task <string> GetToken(RuntimeOptions runtimeOptions)
        {
            // Get OAuth token using client credentials
            string tenantName = runtimeOptions.tenantName;
            string authString = runtimeOptions.authUrl + "/" + tenantName;

            authenticationContext = new Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext(authString, false);

            string token;

            try
            {
                AuthenticationResult authenticationResult = null;
                if (runtimeOptions.isDelegateTokenRequest)
                {
                    if (runtimeOptions.isNativeApplication)
                    {
                        if (runtimeOptions.adminConsent)
                        {
                            authenticationResult = await authenticationContext.AcquireTokenAsync(runtimeOptions.resource,
                                                                                                 runtimeOptions.clientId,
                                                                                                 new Uri(runtimeOptions.redirectUrl),
                                                                                                 new PlatformParameters(PromptBehavior.Always),
                                                                                                 UserIdentifier.AnyUser,
                                                                                                 "prompt=admin_consent");
                        }
                        else
                        {
                            authenticationResult = await authenticationContext.AcquireTokenAsync(runtimeOptions.resource, runtimeOptions.clientId, new Uri(runtimeOptions.redirectUrl), new PlatformParameters(PromptBehavior.Always));
                        }
                    }
                    else
                    {
                        GetCodeForm getCodeForm = new GetCodeForm(runtimeOptions.clientId, runtimeOptions.redirectUrl, runtimeOptions.resource, runtimeOptions.isV2Endpoint, runtimeOptions.adminConsent);
                        if (getCodeForm.ShowDialog() == DialogResult.OK)
                        {
                            string code = getCodeForm._acquiredCode;
                            if (runtimeOptions.cert == null)
                            {
                                ClientCredential clientCred = new ClientCredential(runtimeOptions.clientId, runtimeOptions.key);
                                authenticationResult = await authenticationContext.AcquireTokenByAuthorizationCodeAsync(code, new Uri(runtimeOptions.redirectUrl), clientCred);
                            }
                            else
                            {
                                ClientAssertionCertificate clientCert = new ClientAssertionCertificate(runtimeOptions.clientId, runtimeOptions.cert);
                                authenticationResult = await authenticationContext.AcquireTokenByAuthorizationCodeAsync(code, new Uri(runtimeOptions.redirectUrl), clientCert);
                            }
                        }
                    }
                }
                else
                {
                    if (runtimeOptions.cert == null)
                    {
                        ClientCredential clientCred = new ClientCredential(runtimeOptions.clientId, runtimeOptions.key);
                        authenticationResult = await authenticationContext.AcquireTokenAsync(runtimeOptions.resource, clientCred);
                    }
                    else
                    {
                        ClientAssertionCertificate clientCert = new ClientAssertionCertificate(runtimeOptions.clientId, runtimeOptions.cert);
                        authenticationResult = await authenticationContext.AcquireTokenAsync(runtimeOptions.resource, clientCert);
                    }
                }
                token = authenticationResult.AccessToken;
                return(token);
            }
            catch (AuthenticationException ex)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("Acquiring a token failed with the following error: {0}", ex.Message);
                if (ex.InnerException != null)
                {
                    //  You should implement retry and back-off logic according to
                    //  http://msdn.microsoft.com/en-us/library/dn168916.aspx . This topic also
                    //  explains the HTTP error status code in the InnerException message.
                    Console.WriteLine("Error detail: {0}", ex.InnerException.Message);
                }
                return(string.Empty);
            }
            catch (Exception ex)
            {
                return(ex.ToString());
            }
        }
Пример #27
0
        public void ConfigureAuth(IAppBuilder app)
        {
            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

            app.UseCookieAuthentication(new CookieAuthenticationOptions {
            });

            app.UseOpenIdConnectAuthentication(
                new OpenIdConnectAuthenticationOptions
            {
                ClientId                  = SettingsHelper.ClientId,
                Authority                 = SettingsHelper.Authority,
                ClientSecret              = SettingsHelper.AppKey,
                ResponseType              = "code id_token",
                Resource                  = "https://graph.microsoft.com",
                PostLogoutRedirectUri     = "/",
                TokenValidationParameters = new System.IdentityModel.Tokens.TokenValidationParameters
                {
                    ValidateIssuer = false
                },
                Notifications = new OpenIdConnectAuthenticationNotifications()
                {
                    SecurityTokenValidated = (context) =>
                    {
                        return(Task.FromResult(0));
                    },
                    AuthenticationFailed = (context) =>
                    {
                        string message = Uri.EscapeDataString(context.Exception.Message);
                        context.OwinContext.Response.Redirect("/Home/Error?msg=" + message);
                        context.HandleResponse();
                        return(Task.FromResult(0));
                    },
                    AuthorizationCodeReceived = async(context) =>
                    {
                        var code = context.Code;
                        ClientCredential credential = new ClientCredential(SettingsHelper.ClientId, SettingsHelper.AppKey);

                        string tenantID     = context.AuthenticationTicket.Identity.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;
                        string signInUserId = context.AuthenticationTicket.Identity.FindFirst(AuthHelper.ObjectIdentifierClaim).Value;

                        var authContext = new Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext(SettingsHelper.Authority,
                                                                                                                    new AzureTableTokenCache(signInUserId));

                        AuthenticationResult result = await authContext.AcquireTokenByAuthorizationCodeAsync(code,
                                                                                                             new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)),
                                                                                                             credential,
                                                                                                             SettingsHelper.AADGraphResourceId);
                    },
                    RedirectToIdentityProvider = (context) =>
                    {
                        string appBaseUrl = context.Request.Scheme + "://" + context.Request.Host + context.Request.PathBase;
                        context.ProtocolMessage.RedirectUri           = appBaseUrl + "/";
                        context.ProtocolMessage.PostLogoutRedirectUri = appBaseUrl;

                        FileHandlerActivationParameters fileHandlerActivation;
                        if (FileHandlerController.IsFileHandlerActivationRequest(new HttpRequestWrapper(HttpContext.Current.Request), out fileHandlerActivation))
                        {
                            context.ProtocolMessage.LoginHint  = fileHandlerActivation.UserId;
                            context.ProtocolMessage.DomainHint = "organizations";
                            CookieStorage.Save(HttpContext.Current.Request.Form, HttpContext.Current.Response);
                        }

                        var challengeProperties = context.OwinContext?.Authentication?.AuthenticationResponseChallenge?.Properties;
                        if (null != challengeProperties && challengeProperties.Dictionary.ContainsKey("prompt"))
                        {
                            context.ProtocolMessage.Prompt = challengeProperties.Dictionary["prompt"];
                        }

                        return(Task.FromResult(0));
                    }
                }
            });
        }
        public void ConfigureAuth(IAppBuilder app)
        {
            Certificate = LoadCertificate();

            if (Certificate == null)
            {
                throw new Exception("Certificate == null");
            }

            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

            app.UseCookieAuthentication(new CookieAuthenticationOptions());

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

                    TokenValidationParameters = new System.IdentityModel.Tokens.TokenValidationParameters
                    {
                        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 = async (context) =>
                        {
                            //  This code gets the AccessToken for the AAD graph. This will be needed for some scenarios. However, it might 
                            //  be that we should ask for the services resource id at this stage. The AuthenticationResult includes a RefreshToken.
                            
                            var code = context.Code;

                            var signedInUserId = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value;
                            string tenantId = context.AuthenticationTicket.Identity.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;

                            string authority = string.Format(aadInstance, tenantId);

                            AuthenticationContext authContext = new AuthenticationContext(authority, new NaiveSessionCache(signedInUserId));
                            ClientAssertionCertificate clientAssertionCertificate = new ClientAssertionCertificate(clientId, Certificate);
                            AuthenticationResult result = await authContext.AcquireTokenByAuthorizationCodeAsync(code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), clientAssertionCertificate, graphResourceId);
                        },
                        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;
                            return Task.FromResult(0);
                        },
                        SecurityTokenReceived = (context) =>
                        {
                            return Task.FromResult(0);
                        },
                        AuthenticationFailed = (context) =>
                        {
                            //context.OwinContext.Response.Redirect("/Home/Error");
                            //context.HandleResponse(); // Suppress the exception
                            return Task.FromResult(0);
                        }
                    }
                });
        }
        // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301883
        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);

            // Enable the application to use a cookie to store information for the signed in user
            // and to use a cookie to temporarily store information about a user logging in with a third party login provider
            // Configure the sign in cookie
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                //AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                //LoginPath = new PathString("/Account/Login"),
                //Provider = new CookieAuthenticationProvider
                //{
                //    OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
                //        validateInterval: TimeSpan.FromMinutes(30),
                //        regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
                //}
                SlidingExpiration = true,
                ExpireTimeSpan    = TimeSpan.FromMinutes(480)
            });

            app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
            {
                ClientId              = ConfigurationManager.AppSettings["Ida:ClientId"],
                Authority             = ConfigurationManager.AppSettings["Ida:AadInstance"] + ConfigurationManager.AppSettings["Ida:Tenant"],
                RedirectUri           = ConfigurationManager.AppSettings["Ida:RedirectUri"],
                PostLogoutRedirectUri = ConfigurationManager.AppSettings["Ida:RedirectUri"],
                Scope        = OpenIdConnectScope.OpenIdProfile,
                ResponseType = OpenIdConnectResponseType.IdToken,
                TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
                {
                    SaveSigninToken = true,
                    ValidateIssuer  = false
                },
                Notifications = new OpenIdConnectAuthenticationNotifications
                {
                    AuthorizationCodeReceived = async context =>
                    {
                        var code = context.Code;
                        ClientCredential credential = new ClientCredential(ConfigHelper.ClientId, ConfigHelper.AppKey);
                        var authContext             = new Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext(ConfigHelper.Authority, new ADALTokenCache(Util.GetSignedInUsersObjectIdFromClaims()));

                        // This method exchanges the auth code for an access token and refresh token
                        // Note that this also stores both tokens in the token cache that is configured
                        // in the AuthenticationContext, where they will be automatically retrieved or
                        // refreshed by calling AcquireTokenSilentAsync()
                        AuthenticationResult result = authContext.AcquireTokenByAuthorizationCodeAsync(
                            code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential, ConfigHelper.GraphResourceId).Result;

                        //return System.Threading.Tasks.Task.FromResult(0);
                    },
                    //SecurityTokenValidated = async context =>
                    //{
                    //    var token = new JwtSecurityToken(context.ProtocolMessage.IdToken);
                    //    var claims = new ClaimsIdentity(token.Claims);
                    //    claims.AddClaim(new Claim(ClaimTypes.NameIdentifier, claims.FindFirst("name")?.Value));
                    //    claims.AddClaim(new Claim(Globals.ObjectIdClaimType, claims.FindFirst("oid")?.Value));
                    //    claims.AddClaim(new Claim(ClaimTypes.Email, (claims.FindFirst("upn") ?? claims.FindFirst("email"))?.Value));
                    //    claims.AddClaim(new Claim("access_token", context.ProtocolMessage.IdToken));
                    //    //claims.BootstrapContext = new BootstrapContext(context.ProtocolMessage.IdToken);
                    //    //var claims = context.Request.User.Identity as ClaimsIdentity;
                    //    var groups = await UserInfoHelper.GetAllGroups(claims);
                    //},
                    AuthenticationFailed = (context) =>
                    {
                        if (context.Exception.Message.StartsWith("OICE_20004") || context.Exception.Message.Contains("IDX10311"))
                        {
                            context.SkipToNextMiddleware();
                            return(System.Threading.Tasks.Task.FromResult(0));
                        }
                        return(System.Threading.Tasks.Task.FromResult(0));
                    }
                }
            });

            app.Use(typeof(UserGroupCachingMiddleware));

            // Use a cookie to temporarily store information about a user logging in with a third party login provider
            //app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            //// Enables the application to temporarily store user information when they are verifying the second factor in the two-factor authentication process.
            //app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));

            //// Enables the application to remember the second login verification factor such as phone or email.
            //// Once you check this option, your second step of verification during the login process will be remembered on the device where you logged in from.
            //// This is similar to the RememberMe option when you log in.
            //app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);

            // Uncomment the following lines to enable logging in with third party login providers
            //app.UseMicrosoftAccountAuthentication(
            //    clientId: "",
            //    clientSecret: "");

            //app.UseTwitterAuthentication(
            //   consumerKey: "",
            //   consumerSecret: "");

            //app.UseFacebookAuthentication(
            //   appId: "",
            //   appSecret: "");

            //    app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
            //    {
            //      ClientId = "000000000000.apps.googleusercontent.com",
            //      ClientSecret = "00000000000"
            //    });
        }
Пример #30
0
        public static async Task <AuthenticationResult> GetToken(OAuthContext oAuthContext)
        {
            // Get OAuth token using client credentials
            string tenantName = oAuthContext.tenantName;

            if (_authenticationContext == null)
            {
                _authenticationContext = new Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext(oAuthContext.authUrl + "/" + tenantName, _tokenCache);
            }

            AuthenticationResult authenticationResult = null;

            if (oAuthContext.ObtainUserConsent)
            {
                // We need to get user consent

                FormGetUserPermission formGetPermission = new FormGetUserPermission(oAuthContext);
                if (formGetPermission.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    string code = formGetPermission.Code;
                    // When we get our token, it will be cached in the TokenCache, so next time the silent calls will work
                    if (oAuthContext.cert == null)
                    {
                        ClientCredential clientCred = new ClientCredential(oAuthContext.clientId, oAuthContext.secretKey);
                        authenticationResult = await _authenticationContext.AcquireTokenByAuthorizationCodeAsync(code, new Uri(oAuthContext.redirectUrl), clientCred);
                    }
                    else
                    {
                        ClientAssertionCertificate clientCert = new ClientAssertionCertificate(oAuthContext.clientId, oAuthContext.cert);
                        authenticationResult = await _authenticationContext.AcquireTokenByAuthorizationCodeAsync(code, new Uri(oAuthContext.redirectUrl), clientCert);
                    }
                }
                return(authenticationResult);
            }

            if (oAuthContext.isNativeApplication)
            {
                if (oAuthContext.adminConsent)
                {
                    authenticationResult = await _authenticationContext.AcquireTokenAsync(oAuthContext.resource,
                                                                                          oAuthContext.clientId,
                                                                                          new Uri(oAuthContext.redirectUrl),
                                                                                          new PlatformParameters(PromptBehavior.Always),
                                                                                          UserIdentifier.AnyUser,
                                                                                          "prompt=admin_consent");
                }
                else
                {
                    authenticationResult = await _authenticationContext.AcquireTokenAsync(oAuthContext.resource, oAuthContext.clientId, new Uri(oAuthContext.redirectUrl), new PlatformParameters(PromptBehavior.Always));
                }
            }
            else
            {
                if (!String.IsNullOrEmpty(oAuthContext.userId))
                {
                    // We have the UserId for the mailbox we want to access, so we'll try to get a token silently (we should have a cached token)
                    try
                    {
                        if (oAuthContext.cert == null)
                        {
                            ClientCredential clientCred = new ClientCredential(oAuthContext.clientId, oAuthContext.secretKey);
                            authenticationResult = await _authenticationContext.AcquireTokenSilentAsync(oAuthContext.resource, clientCred, new UserIdentifier(oAuthContext.userId, UserIdentifierType.UniqueId));
                        }
                        else
                        {
                            ClientAssertionCertificate clientCert = new ClientAssertionCertificate(oAuthContext.clientId, oAuthContext.cert);
                            authenticationResult = await _authenticationContext.AcquireTokenSilentAsync(oAuthContext.resource, clientCert, new UserIdentifier(oAuthContext.userId, UserIdentifierType.UniqueId));
                        }
                        return(authenticationResult);
                    }
                    catch (Exception ex)
                    {
                        _lastError = ex;
                    }
                }
            }
            return(authenticationResult);
        }
        public void ConfigureAuth(IAppBuilder app)
        {
            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

            app.UseCookieAuthentication(new CookieAuthenticationOptions {
            });

            app.UseOpenIdConnectAuthentication(
                new OpenIdConnectAuthenticationOptions
            {
                ClientId              = SettingsHelper.ClientId,
                Authority             = SettingsHelper.Authority,
                ClientSecret          = SettingsHelper.AppKey,
                ResponseType          = "code id_token",
                Resource              = "https://graph.microsoft.com",
                PostLogoutRedirectUri = "/",

                TokenValidationParameters = new 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()
                {
                    SecurityTokenValidated = (context) =>
                    {
                        // If your authentication logic is based on users then add your logic here
                        return(Task.FromResult(0));
                    },
                    AuthenticationFailed = (context) =>
                    {
                        // Pass in the context back to the app
                        string message = Uri.EscapeDataString(context.Exception.Message);
                        context.OwinContext.Response.Redirect("/Home/Error?msg=" + message);
                        context.HandleResponse();     // Suppress the exception
                        return(Task.FromResult(0));
                    },
                    AuthorizationCodeReceived = async(context) =>
                    {
                        var code = context.Code;
                        ClientCredential credential = new ClientCredential(SettingsHelper.ClientId, SettingsHelper.AppKey);

                        string tenantID     = context.AuthenticationTicket.Identity.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;
                        string signInUserId = context.AuthenticationTicket.Identity.FindFirst(AuthHelper.ObjectIdentifierClaim).Value;

                        var authContext = new Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext(SettingsHelper.Authority,
                                                                                                                    new AzureTableTokenCache(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 = await authContext.AcquireTokenByAuthorizationCodeAsync(code,
                                                                                                             new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)),
                                                                                                             credential,
                                                                                                             SettingsHelper.AADGraphResourceId);
                    },
                    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;

                        FileHandlerActivationParameters fileHandlerActivation;
                        if (GraphHelper.IsFileHandlerActivationRequest(new HttpRequestWrapper(HttpContext.Current.Request), out fileHandlerActivation))
                        {
                            // Add LoginHint and DomainHint if the request includes a form handler post
                            context.ProtocolMessage.LoginHint  = fileHandlerActivation.UserId;
                            context.ProtocolMessage.DomainHint = "organizations";

                            // Save the form in the cookie to prevent it from getting lost in the login redirect
                            CookieStorage.Save(HttpContext.Current.Request.Form, HttpContext.Current.Response);
                        }

                        // Allow us to change the prompt in consent mode if the challenge properties specify a prompt type
                        var challengeProperties = context.OwinContext?.Authentication?.AuthenticationResponseChallenge?.Properties;
                        if (null != challengeProperties && challengeProperties.Dictionary.ContainsKey("prompt"))
                        {
                            context.ProtocolMessage.Prompt = challengeProperties.Dictionary["prompt"];
                        }

                        return(Task.FromResult(0));
                    }
                }
            });
        }
Пример #32
0
        /// <summary>
        /// Use the DiscoveryClient to get the Contacts and Files endpoints
        /// </summary>
        /// <param name="code">The authorization code to use when getting an access token</param>
        /// <returns></returns>
        public async Task<ActionResult> Index(string code)
        {
            AuthenticationContext authContext = new AuthenticationContext(
               ConfigurationManager.AppSettings["ida:AuthorizationUri"] + "/common",
               true);

            ClientCredential creds = new ClientCredential(
                ConfigurationManager.AppSettings["ida:ClientID"],
                ConfigurationManager.AppSettings["ida:Password"]);

            DiscoveryClient disco = Helpers.GetFromCache("DiscoveryClient") as DiscoveryClient;

            //Redirect to login page if we do not have an 
            //authorization code for the Discovery service
            if (disco == null && code == null)
            {
                Uri redirectUri = authContext.GetAuthorizationRequestURL(
                    discoResource,
                    creds.ClientId,
                    new Uri(Request.Url.AbsoluteUri.Split('?')[0]),
                    UserIdentifier.AnyUser,
                    string.Empty);

                return Redirect(redirectUri.ToString());
            }

            //Create a DiscoveryClient using the authorization code
            if (disco == null && code != null)
            {

                disco = new DiscoveryClient(new Uri(discoEndpoint), async () =>
                {

                    var authResult = await authContext.AcquireTokenByAuthorizationCodeAsync(
                        code,
                        new Uri(Request.Url.AbsoluteUri.Split('?')[0]),
                        creds);

                    return authResult.AccessToken;
                });

            }

            //Discover required capabilities
            CapabilityDiscoveryResult contactsDisco = await disco.DiscoverCapabilityAsync("Contacts");
            CapabilityDiscoveryResult filesDisco = await disco.DiscoverCapabilityAsync("MyFiles");

            Helpers.SaveInCache("ContactsDiscoveryResult", contactsDisco);
            Helpers.SaveInCache("FilesDiscoveryResult", filesDisco);

            List<MyDiscovery> discoveries = new List<MyDiscovery>(){
                new MyDiscovery(){
                    Capability = "Contacts",
                    EndpointUri = contactsDisco.ServiceEndpointUri.OriginalString,
                    ResourceId = contactsDisco.ServiceResourceId,
                    Version = contactsDisco.ServiceApiVersion
                },
                new MyDiscovery(){
                    Capability = "My Files",
                    EndpointUri = filesDisco.ServiceEndpointUri.OriginalString,
                    ResourceId = filesDisco.ServiceResourceId,
                    Version = filesDisco.ServiceApiVersion
                }
            };

            return View(discoveries);

        }
Пример #33
0
        /// <summary>
        /// Display a form for creating a new Project
        /// </summary>
        /// <param name="submitModel">The new project data submitted from the form</param>
        /// <param name="code">The authorization code to use when getting an access token</param>
        /// <returns></returns>
        public async Task<ActionResult> Projects(ViewModel submitModel, string code)
        {
            //If the New Project form needs to be displayed
            if (submitModel.Project == null && code == null)
            {
                ViewModel formModel = new ViewModel();
                formModel.Contacts = Helpers.GetFromCache("ContactList") as List<MyContact>;
                formModel.Files = Helpers.GetFromCache("FileList") as List<MyFile>;
                return View(formModel);
            }
            // A new project was submitted
            else
            {
                if (submitModel.Project != null)
                {
                    Helpers.SaveInCache("SubmitModel", submitModel);
                }

                AuthenticationContext authContext = new AuthenticationContext(
                   ConfigurationManager.AppSettings["ida:AuthorizationUri"] + "/common",
                   true);

                ClientCredential creds = new ClientCredential(
                    ConfigurationManager.AppSettings["ida:ClientID"],
                    ConfigurationManager.AppSettings["ida:Password"]);

                //Get an authorization code, if necessary
                if (code == null)
                {
                    Uri redirectUri = authContext.GetAuthorizationRequestURL(
                        spSite,
                        creds.ClientId,
                        new Uri(Request.Url.AbsoluteUri.Split('?')[0]),
                        UserIdentifier.AnyUser,
                        string.Empty);

                    return Redirect(redirectUri.ToString());
                }
                else
                {
                    //Get the access token
                    var authResult = await authContext.AcquireTokenByAuthorizationCodeAsync(
                        code,
                        new Uri(Request.Url.AbsoluteUri.Split('?')[0]),
                        creds);

                    string accessToken = authResult.AccessToken;

                    //Build SharePoint RESTful API endpoint for the list items
                    StringBuilder requestUri = new StringBuilder()
                      .Append(spSite)
                      .Append("/_api/web/lists/getbyTitle('Research Projects')/items");

                    //Create an XML message with the new project data
                    //This message will be POSTED to the SharePoint API endpoint
                    XNamespace atom = "http://www.w3.org/2005/Atom";
                    XNamespace d = "http://schemas.microsoft.com/ado/2007/08/dataservices";
                    XNamespace m = "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata";

                    submitModel = Helpers.GetFromCache("SubmitModel") as ViewModel;
                    string description = (Helpers.GetFromCache("FileList") as List<MyFile>).Where(f => f.Url == submitModel.Project.DocumentLink).First().Name;
                    string url = submitModel.Project.DocumentLink;
                    string title = submitModel.Project.Title;
                    string owner = submitModel.Project.Owner;

                    XElement message = new XElement(atom + "entry",
                        new XAttribute(XNamespace.Xmlns + "d", d),
                        new XAttribute(XNamespace.Xmlns + "m", m),
                        new XElement(atom + "category", new XAttribute("term", "SP.Data.Research_x0020_ProjectsListItem"), new XAttribute("scheme", "http://schemas.microsoft.com/ado/2007/08/dataservices/scheme")),
                        new XElement(atom + "content", new XAttribute("type", "application/xml"),
                            new XElement(m + "properties",
                                new XElement(d + "Statement", new XAttribute(m + "type", "SP.FieldUrlValue"),
                                    new XElement(d + "Description", description),
                                    new XElement(d + "Url", url)),
                                new XElement(d + "Title", title),
                                new XElement(d + "Owner", owner))));

                    StringContent requestData = new StringContent(message.ToString());

                    //POST the data to the endpoint
                    HttpClient client = new HttpClient();
                    HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, requestUri.ToString());
                    request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml"));
                    request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
                    requestData.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/atom+xml");
                    request.Content = requestData;
                    HttpResponseMessage response = await client.SendAsync(request);

                    //Show the Finished screen
                    return RedirectToAction("Finished");
                }
            }


        }
Пример #34
0
        /// <summary>
        /// Use the SharePointClient to get OneDrive for Business Files
        /// </summary>
        /// <param name="code">The authorization code to use when getting an access token</param>
        /// <returns></returns>
        public async Task<ActionResult> Files(string code)
        {
            AuthenticationContext authContext = new AuthenticationContext(
               ConfigurationManager.AppSettings["ida:AuthorizationUri"] + "/common",
               true);

            ClientCredential creds = new ClientCredential(
                ConfigurationManager.AppSettings["ida:ClientID"],
                ConfigurationManager.AppSettings["ida:Password"]);

            //Get the discovery information that was saved earlier
            CapabilityDiscoveryResult cdr = Helpers.GetFromCache("FilesDiscoveryResult") as CapabilityDiscoveryResult;

            //Get a client, if this page was already visited
            SharePointClient sharepointClient = Helpers.GetFromCache("SharePointClient") as SharePointClient;

            //Get an authorization code, if needed
            if (sharepointClient == null && cdr != null && code == null)
            {
                Uri redirectUri = authContext.GetAuthorizationRequestURL(
                    cdr.ServiceResourceId,
                    creds.ClientId,
                    new Uri(Request.Url.AbsoluteUri.Split('?')[0]),
                    UserIdentifier.AnyUser,
                    string.Empty);

                return Redirect(redirectUri.ToString());
            }

            //Create the SharePointClient
            if (sharepointClient == null && cdr != null && code != null)
            {

                sharepointClient = new SharePointClient(cdr.ServiceEndpointUri, async () =>
                {

                    var authResult = await authContext.AcquireTokenByAuthorizationCodeAsync(
                        code,
                        new Uri(Request.Url.AbsoluteUri.Split('?')[0]),
                        creds);

                    return authResult.AccessToken;
                });

                Helpers.SaveInCache("SharePointClient", sharepointClient);
            }

            //Get the files
            var filesResults = await sharepointClient.Files.ExecuteAsync();

            var fileList = new List<MyFile>();

            foreach (var file in filesResults.CurrentPage.Where(f => f.Name != "Shared with Everyone").OrderBy(e => e.Name))
            {
                fileList.Add(new MyFile
                {
                    Id = file.Id,
                    Name = file.Name,
                    Url = file.WebUrl
                });
            }

            //Save the files
            Helpers.SaveInCache("FileList", fileList);

            //Show the files
            return View(fileList);

        }
Пример #35
0
        /// <summary>
        /// Use the OutlookServicesClient to get Exchange contacts
        /// </summary>
        /// <param name="code">The authorization code to use when getting an access token</param>
        /// <returns></returns>
        public async Task<ActionResult> Contacts(string code)
        {
            AuthenticationContext authContext = new AuthenticationContext(
               ConfigurationManager.AppSettings["ida:AuthorizationUri"] + "/common",
               true);

            ClientCredential creds = new ClientCredential(
                ConfigurationManager.AppSettings["ida:ClientID"],
                ConfigurationManager.AppSettings["ida:Password"]);

            //Get the discovery information that was saved earlier
            CapabilityDiscoveryResult cdr = Helpers.GetFromCache("ContactsDiscoveryResult") as CapabilityDiscoveryResult;

            //Get a client, if this page was already visited
            OutlookServicesClient outlookClient = Helpers.GetFromCache("OutlookClient") as OutlookServicesClient;

            //Get an authorization code if needed
            if (outlookClient == null && cdr != null && code == null)
            {
                Uri redirectUri = authContext.GetAuthorizationRequestURL(
                    cdr.ServiceResourceId,
                    creds.ClientId,
                    new Uri(Request.Url.AbsoluteUri.Split('?')[0]),
                    UserIdentifier.AnyUser,
                    string.Empty);

                return Redirect(redirectUri.ToString());
            }

            //Create the OutlookServicesClient
            if (outlookClient == null && cdr != null && code != null)
            {

                outlookClient = new OutlookServicesClient(cdr.ServiceEndpointUri, async () =>
                {

                    var authResult = await authContext.AcquireTokenByAuthorizationCodeAsync(
                        code,
                        new Uri(Request.Url.AbsoluteUri.Split('?')[0]),
                        creds);

                    return authResult.AccessToken;
                });

                Helpers.SaveInCache("OutlookClient", outlookClient);
            }

            //Get the contacts
            var contactsResults = await outlookClient.Me.Contacts.ExecuteAsync();
            List<MyContact> contactList = new List<MyContact>();

            foreach (var contact in contactsResults.CurrentPage.OrderBy(c => c.Surname))
            {
                contactList.Add(new MyContact
                {
                    Id = contact.Id,
                    GivenName = contact.GivenName,
                    Surname = contact.Surname,
                    DisplayName = contact.Surname + ", " + contact.GivenName,
                    CompanyName = contact.CompanyName,
                    EmailAddress1 = contact.EmailAddresses.FirstOrDefault().Address,
                    BusinessPhone1 = contact.BusinessPhones.FirstOrDefault(),
                    HomePhone1 = contact.HomePhones.FirstOrDefault()
                });
            }

            //Save the contacts
            Helpers.SaveInCache("ContactList", contactList);

            //Show the contacts
            return View(contactList);

        }