예제 #1
0
 public AuthHelper(string authority, string appId, string appSecret, SessionTokenCache tokenCache)
 {
     Authority  = authority;
     AppId      = appId;
     AppSecret  = appSecret;
     TokenCache = tokenCache;
 }
예제 #2
0
        private async Task AddAccessToken(System.Net.Http.HttpRequestMessage request)
        {
            // Load the app config from web.config
            string appId       = ConfigurationManager.AppSettings["ida:AppId"];
            string appSecret   = ConfigurationManager.AppSettings["ida:AppSecret"];
            string redirectUri = ConfigurationManager.AppSettings["ida:RedirectUri"];

            // Get the current user's ID
            string userId = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;

            // Get the user's token cache
            SessionTokenCache tokenCache = new SessionTokenCache(userId, HttpContext);

            ConfidentialClientApplication cca = new ConfidentialClientApplication(
                appId, redirectUri, new ClientCredential(appSecret), tokenCache);

            // Call AcquireTokenSilentAsync, which will return the cached
            // access token if it has not expired. If it has expired, it will
            // handle using the refresh token to get a new one.
            string[]             scopes = { "User.Read", "Mail.Send" };
            AuthenticationResult result = await cca.AcquireTokenSilentAsync(scopes);

            // Set the token on the request
            request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", result.Token);
        }
예제 #3
0
        public static async Task <string> GetAccessToken(HttpContextBase HttpContext)
        {
            string accessToken = null;

            // Load the app config from web.config
            string appId       = ConfigurationManager.AppSettings["ida:AppId"];
            string appPassword = ConfigurationManager.AppSettings["ida:AppPassword"];
            string redirectUri = ConfigurationManager.AppSettings["ida:RedirectUri"];

            string[] scopes = ConfigurationManager.AppSettings["ida:AppScopes"]
                              .Replace(' ', ',').Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

            // Get the current user's ID
            string userId = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;

            if (!string.IsNullOrEmpty(userId))
            {
                // Get the user's token cache
                SessionTokenCache tokenCache = new SessionTokenCache(userId, HttpContext);

                ConfidentialClientApplication cca = new ConfidentialClientApplication(
                    appId, redirectUri, new ClientCredential(appPassword), tokenCache.GetMsalCacheInstance(), null);

                // Call AcquireTokenSilentAsync, which will return the cached
                // access token if it has not expired. If it has expired, it will
                // handle using the refresh token to get a new one.
                AuthenticationResult result = await cca.AcquireTokenSilentAsync(scopes, cca.Users.First());

                accessToken = result.AccessToken;
            }

            return(accessToken);
        }
        private async Task SendIncidentEmail(Incident incidentData)
        {
            string userObjId = ClaimsPrincipal.Current.FindFirst(Settings.AAD_OBJECTID_CLAIMTYPE).Value;

            //The email is the UPN of the user from the claim
            string emailAddress = getUserEmailAddressFromClaims(ClaimsPrincipal.Current);

            SessionTokenCache tokenCache = new SessionTokenCache(userObjId, HttpContext);

            string     tenantId    = ClaimsPrincipal.Current.FindFirst(Settings.AAD_TENANTID_CLAIMTYPE).Value;
            string     authority   = string.Format(Settings.AAD_INSTANCE, tenantId, "");
            AuthHelper authHelper  = new AuthHelper(authority, Settings.AAD_APP_ID, Settings.AAD_APP_SECRET, tokenCache);
            string     accessToken = await authHelper.GetUserAccessToken(Url.Action("Create", "Incident", null, Request.Url.Scheme));

            EmailMessage msg = getEmailBodyContent(incidentData, emailAddress);

            using (var client = new HttpClient())
            {
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                // New code:
                StringContent msgContent = new StringContent(JsonConvert.SerializeObject(msg), System.Text.Encoding.UTF8, "application/json");
                msgContent.Headers.ContentType = new MediaTypeWithQualityHeaderValue("application/json");
                HttpResponseMessage response = await client.PostAsync(Settings.GRAPH_SENDMESSAGE_URL, msgContent);

                if (response.IsSuccessStatusCode)
                {
                    string resultString = await response.Content.ReadAsStringAsync();
                }
            }
        }
        public ActionResult Index()
        {
            if (Request.IsAuthenticated)
            {
                string userName = ClaimsPrincipal.Current.FindFirst("name").Value;
                string userId   = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
                if (string.IsNullOrEmpty(userName) || string.IsNullOrEmpty(userId))
                {
                    // Invalid principal, sign out
                    return(RedirectToAction("SignOut"));
                }

                // Since we cache tokens in the session, if the server restarts
                // but the browser still has a cached cookie, we may be
                // authenticated but not have a valid token cache. Check for this
                // and force signout.
                SessionTokenCache tokenCache = new SessionTokenCache(userId, HttpContext);
                if (!tokenCache.HasData())
                {
                    // Cache is empty, sign out
                    return(RedirectToAction("SignOut"));
                }

                ViewBag.UserName = userName;
            }
            return(View());
        }
        private async Task <Models.ContactValue> GetContacts()
        {
            Models.ContactValue contacts = null;
            try
            {
                string            userObjId  = System.Security.Claims.ClaimsPrincipal.Current.FindFirst(Settings.AAD_OBJECTID_CLAIMTYPE).Value;
                SessionTokenCache tokenCache = new SessionTokenCache(userObjId, HttpContext);

                string     tenantId    = System.Security.Claims.ClaimsPrincipal.Current.FindFirst(Settings.AAD_TENANTID_CLAIMTYPE).Value;
                string     authority   = string.Format(Settings.AAD_INSTANCE, tenantId, "");
                AuthHelper authHelper  = new AuthHelper(authority, Settings.AAD_APP_ID, Settings.AAD_APP_SECRET, tokenCache);
                string     accessToken = await authHelper.GetUserAccessToken(Url.Action("Create", "Incident", null, Request.Url.Scheme));

                using (var client = new HttpClient())
                {
                    client.DefaultRequestHeaders.Accept.Clear();
                    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                    HttpResponseMessage response = await client.GetAsync(Settings.GRAPH_CONTACTS_URL);

                    if (response.IsSuccessStatusCode)
                    {
                        string resultString = await response.Content.ReadAsStringAsync();

                        contacts = JsonConvert.DeserializeObject <Models.ContactValue>(resultString);                        // [8] für mw
                    }
                }
            }
            catch (Exception ex)
            {
                ViewBag.Error = "An error has occurred. Details: " + ex.Message;
            }
            return(contacts);
        }
        public async Task <string> GetUserAccessTokenAsync()
        {
            string             signedInUserID = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
            HttpContextWrapper httpContext    = new HttpContextWrapper(HttpContext.Current);
            TokenCache         userTokenCache = new SessionTokenCache(signedInUserID, httpContext).GetMsalCacheInstance();

            ConfidentialClientApplication cca = new ConfidentialClientApplication(
                appId,
                redirectUri,
                new ClientCredential(appSecret),
                userTokenCache,
                null);

            try
            {
                AuthenticationResult result = await cca.AcquireTokenSilentAsync(scopes.Split(new char[] { ' ' }), cca.Users.First());

                return(result.AccessToken);
            }

            catch (Exception)
            {
                HttpContext.Current.Request.GetOwinContext().Authentication.Challenge(
                    new AuthenticationProperties()
                {
                    RedirectUri = "/"
                },
                    OpenIdConnectAuthenticationDefaults.AuthenticationType);

                throw new Exception();
            }
        }
예제 #8
0
        // Get an access token. First tries to get the token from the token cache.
        public async Task <string> GetUserAccessTokenAsync()
        {
            string          signedInUserID  = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
            HttpContextBase httpContextBase = HttpContext.Current.GetOwinContext().Environment["System.Web.HttpContextBase"] as HttpContextBase;

            SessionTokenCache tokenCache = new SessionTokenCache(signedInUserID, httpContextBase);
            //var cachedItems = tokenCache.ReadItems(); // see what's in the cache

            AuthenticationContext authContext      = new AuthenticationContext(SettingsHelper.Authority, tokenCache);
            ClientCredential      clientCredential = new ClientCredential(SettingsHelper.ClientId, SettingsHelper.ClientSecret);

            string         userObjectId = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
            UserIdentifier userId       = new UserIdentifier(userObjectId, UserIdentifierType.UniqueId);

            try
            {
                AuthenticationResult result = await authContext.AcquireTokenSilentAsync(SettingsHelper.GraphResourceId, clientCredential, userId);

                return(result.AccessToken);
            }
            // Unable to retrieve the access token silently.
            catch (AdalException ex)
            {
                HttpContext.Current.Request.GetOwinContext().Authentication.Challenge(
                    new AuthenticationProperties()
                {
                    RedirectUri = "/"
                },
                    OpenIdConnectAuthenticationDefaults.AuthenticationType);

                throw new Exception(Resource.Error_AuthChallengeNeeded + $" {ex.Message}");
            }
        }
        public async Task <ActionResult> Create(FormCollection collection)
        {
            try
            {
                string            userObjId  = System.Security.Claims.ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
                SessionTokenCache tokenCache = new SessionTokenCache(userObjId, HttpContext);

                string accessToken = await SampleAuthProvider.Instance.GetUserAccessTokenAsync();

                await ExcelApiHelper.CreateToDoItem(
                    accessToken,
                    collection["Title"],
                    collection["PriorityDD"],
                    collection["StatusDD"],
                    collection["PercentComplete"],
                    collection["StartDate"],
                    collection["EndDate"],
                    collection["Notes"]);

                return(RedirectToAction("Index"));
            }
            catch
            {
                return(View());
            }
        }
예제 #10
0
        public async Task <string> GetUserAccessTokenAsync()
        {
            string signedInUserID = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;

            tokenCache = new SessionTokenCache(
                signedInUserID,
                HttpContext.Current.GetOwinContext().Environment["System.Web.HttpContextBase"] as HttpContextBase);

            ConfidentialClientApplication cca = new ConfidentialClientApplication(
                appId,
                redirectUri,
                new ClientCredential(appSecret),
                tokenCache);

            try
            {
                AuthenticationResult result = await cca.AcquireTokenSilentAsync(scopes.Split(new char[] { ' ' }));

                return(result.Token);
            }

            // Unable to retrieve the access token silently.
            catch (MsalSilentTokenAcquisitionException)
            {
                HttpContext.Current.Request.GetOwinContext().Authentication.Challenge(
                    new AuthenticationProperties()
                {
                    RedirectUri = "/"
                },
                    OpenIdConnectAuthenticationDefaults.AuthenticationType);

                throw new Exception("Caller needs to authenticate.");
            }
        }
예제 #11
0
        public void ConfigureAuth(IAppBuilder app)
        {
            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

            app.UseCookieAuthentication(new CookieAuthenticationOptions());

            app.UseOpenIdConnectAuthentication(
                new OpenIdConnectAuthenticationOptions
            {
                // The `Authority` represents the Microsoft v2.0 authentication and authorization service.
                // The `Scope` describes the permissions that your app will need. See https://azure.microsoft.com/documentation/articles/active-directory-v2-scopes/
                ClientId = appId,
                //Authority = "https://login.microsoftonline.com/common/v2.0",
                Authority             = "https://login.microsoftonline.com/{0}",
                PostLogoutRedirectUri = redirectUri,
                RedirectUri           = redirectUri,
                Scope = "openid email profile offline_access " + graphScopes,
                TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer = false,
                    // In a real application you would use IssuerValidator for additional checks,
                    // like making sure the user's organization has signed up for your app.
                    //     IssuerValidator = (issuer, token, tvp) =>
                    //     {
                    //         if (MyCustomTenantValidation(issuer))
                    //             return issuer;
                    //         else
                    //             throw new SecurityTokenInvalidIssuerException("Invalid issuer");
                    //     },
                },
                Notifications = new OpenIdConnectAuthenticationNotifications
                {
                    AuthorizationCodeReceived = async(context) =>
                    {
                        var code = context.Code;
                        string signedInUserID = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value;

                        TokenCache userTokenCache = new SessionTokenCache(signedInUserID,
                                                                          context.OwinContext.Environment["System.Web.HttpContextBase"] as HttpContextBase).GetMsalCacheInstance();
                        ConfidentialClientApplication cca = new ConfidentialClientApplication(
                            appId,
                            redirectUri,
                            new ClientCredential(appSecret),
                            userTokenCache,
                            null);
                        string[] scopes = graphScopes.Split(new char[] { ' ' });

                        AuthenticationResult result = await cca.AcquireTokenByAuthorizationCodeAsync(code, scopes);
                    },
                    AuthenticationFailed = (context) =>
                    {
                        context.HandleResponse();
                        context.Response.Redirect("/Error?message=" + context.Exception.Message);
                        return(Task.FromResult(0));
                    }
                }
            });
        }
        static void AddToCache(string uri, string token)
        {
            var cache = new SessionTokenCache(
                SessionTokenCacheLocation,
                new ConsoleLogger(),
                CancellationToken.None);

            cache [new Uri(uri)] = token;
        }
예제 #13
0
        //
        // GET: ToDoList
        public async Task <ActionResult> Index()
        {
            string            userObjId  = System.Security.Claims.ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
            SessionTokenCache tokenCache = new SessionTokenCache(userObjId, HttpContext);

            string accessToken = await SampleAuthProvider.Instance.GetUserAccessTokenAsync();

            return(View(await ExcelApiHelper.GetDonations(accessToken)));
        }
예제 #14
0
        // Gets an access token and its expiration date. First tries to get the token from the token cache.
        public async Task <string> GetUserAccessTokenAsync()
        {
            // Initialize the cache.
            HttpContextBase context = HttpContext.Current.GetOwinContext().Environment["System.Web.HttpContextBase"] as HttpContextBase;

            tokenCache = new SessionTokenCache(
                ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value,
                context).GetMsalCacheInstance();
            //var cachedItems = tokenCache.ReadItems(appId); // see what's in the cache

            if (!redirectUri.EndsWith("/"))
            {
                redirectUri = redirectUri + "/";
            }
            string[] segments = context.Request.Path.Split(new char[] { '/' });
            ConfidentialClientApplication cca = new ConfidentialClientApplication(
                appId,
                redirectUri + segments[1],
                new ClientCredential(appSecret),
                tokenCache,
                null);
            bool?isAdmin = HttpContext.Current.Session["IsAdmin"] as bool?;

            string allScopes = nonAdminScopes;

            if (isAdmin.GetValueOrDefault())
            {
                allScopes += " " + adminScopes;
            }
            string[] scopes = allScopes.Split(new char[] { ' ' });
            try
            {
                AuthenticationResult result = await cca.AcquireTokenSilentAsync(scopes, cca.Users.First());

                return(result.AccessToken);
            }

            // Unable to retrieve the access token silently.
            catch (Exception)
            {
                HttpContext.Current.Request.GetOwinContext().Authentication.Challenge(
                    new AuthenticationProperties()
                {
                    RedirectUri = redirectUri + segments[1]
                },
                    OpenIdConnectAuthenticationDefaults.AuthenticationType);

                throw new ServiceException(
                          new Error
                {
                    Code    = GraphErrorCode.AuthenticationFailure.ToString(),
                    Message = Resource.Error_AuthChallengeNeeded,
                });
            }
        }
예제 #15
0
        public void ConfigureAuth(IAppBuilder app)
        {
            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

            app.UseCookieAuthentication(new CookieAuthenticationOptions());

            app.UseOpenIdConnectAuthentication(
                new OpenIdConnectAuthenticationOptions
            {
                ClientId                  = appId,
                Authority                 = authority + "/v2.0",
                Scope                     = "openid offline_access profile " + scopes,
                RedirectUri               = postLogoutRedirectUri,
                PostLogoutRedirectUri     = postLogoutRedirectUri,
                TokenValidationParameters = new TokenValidationParameters
                {
                    // For demo purposes only, see below
                    ValidateIssuer = false

                                     // In a real multitenant app, you would add logic to determine whether the
                                     // issuer was from an authorized tenant
                                     //ValidateIssuer = true,
                                     //IssuerValidator = (issuer, token, tvp) =>
                                     //{
                                     //  if (MyCustomTenantValidation(issuer))
                                     //  {
                                     //    return issuer;
                                     //  }
                                     //  else
                                     //  {
                                     //    throw new SecurityTokenInvalidIssuerException("Invalid issuer");
                                     //  }
                                     //}
                },
                Notifications = new OpenIdConnectAuthenticationNotifications
                {
                    AuthorizationCodeReceived = async(notification) =>
                    {
                        // Get the user's object id (used to name the token cache)
                        ClaimsPrincipal principal = new ClaimsPrincipal(notification.AuthenticationTicket.Identity);
                        string userObjId          = AuthHelper.GetUserId(principal);

                        // 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
                        AuthHelper authHelper = new AuthHelper(authority, appId, appSecret, tokenCache);

                        var response = await authHelper.GetTokensFromAuthority("authorization_code", notification.Code,
                                                                               notification.Request.Uri.ToString());
                    }
                }
            });
        }
        private async Task <string> GetAccessToken()
        {
            string            userObjId  = AuthHelper.GetUserId(System.Security.Claims.ClaimsPrincipal.Current);
            SessionTokenCache tokenCache = new SessionTokenCache(userObjId, HttpContext);

            string     tenantId   = System.Security.Claims.ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;
            string     authority  = "common";
            AuthHelper authHelper = new AuthHelper(authority, ConfigurationManager.AppSettings["ida:AppId"], ConfigurationManager.AppSettings["ida:AppSecret"], tokenCache);

            return(await authHelper.GetUserAccessToken(Url.Action("Index", "Home", null, Request.Url.Scheme)));
        }
        //
        // GET: ToDoList
        public async Task <ActionResult> Index()
        {
            string            userObjId  = System.Security.Claims.ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
            SessionTokenCache tokenCache = new SessionTokenCache(userObjId, HttpContext);

            string     tenantId    = System.Security.Claims.ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;
            string     authority   = string.Format(ConfigurationManager.AppSettings["ida:AADInstance"], tenantId, "");
            AuthHelper authHelper  = new AuthHelper(authority, ConfigurationManager.AppSettings["ida:AppId"], ConfigurationManager.AppSettings["ida:AppSecret"], tokenCache);
            string     accessToken = await authHelper.GetUserAccessToken(Url.Action("Index", "Home", null, Request.Url.Scheme));

            return(View(await ExcelApiHelper.GetDonations(accessToken)));
        }
예제 #18
0
        /// <summary>
        /// Gets an access token and its expiration date. First tries to get the token from the token cache.
        /// </summary>
        /// <param name="userId">optional parameter to get the access token using a user Id</param>
        /// <returns></returns>
        public async Task <string> GetUserAccessTokenAsync(string userId)
        {
            // user Id will be passed when trying to authenticate a notification
            var currentUserId = !string.IsNullOrEmpty(userId) ? userId : ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;

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

            TokenCache = new SessionTokenCache(
                currentUserId).GetMsalCacheInstance();

            if (!_redirectUri.EndsWith("/"))
            {
                _redirectUri = _redirectUri + "/";
            }
            string[] segments = context?.Request.Path.Split('/');
            ConfidentialClientApplication cca = new ConfidentialClientApplication(_appId, _redirectUri + segments?[1], new ClientCredential(_appSecret), TokenCache, null);
            bool?isAdmin = HttpContext.Current.Session["IsAdmin"] as bool?;

            string allScopes = _nonAdminScopes;

            if (isAdmin.GetValueOrDefault())
            {
                allScopes += " " + _adminScopes;
            }

            string[] scopes = allScopes.Split(' ');
            try
            {
                var accounts = await cca.GetAccountsAsync();

                AuthenticationResult result = await cca.AcquireTokenSilentAsync(scopes, accounts.First());

                return(result.AccessToken);
            }

            // Unable to retrieve the access token silently.
            catch (Exception)
            {
                HttpContext.Current.Request.GetOwinContext().Authentication.Challenge(
                    new AuthenticationProperties {
                    RedirectUri = _redirectUri + segments?[1]
                },
                    OpenIdConnectAuthenticationDefaults.AuthenticationType);

                throw new ServiceException(
                          new Error
                {
                    Code    = GraphErrorCode.AuthenticationFailure.ToString(),
                    Message = "Caller needs to authenticate.",
                });
            }
        }
예제 #19
0
        private async Task <string> GetToken()
        {
            string            userObjId  = AuthHelper.GetUserId(System.Security.Claims.ClaimsPrincipal.Current);
            SessionTokenCache tokenCache = new SessionTokenCache(userObjId, HttpContext);

            var        authority   = ConfigurationManager.AppSettings["ida:AADInstance"] + "common";
            var        appId       = ConfigurationManager.AppSettings["ida:AppId"];
            var        appSecret   = ConfigurationManager.AppSettings["ida:AppSecret"];
            AuthHelper authHelper  = new AuthHelper(authority, appId, appSecret, tokenCache);
            var        redirectUri = ConfigurationManager.AppSettings["ida:PostLogoutRedirectUri"];

            return(await authHelper.GetUserAccessToken(redirectUri));
        }
예제 #20
0
        public async Task <FileResult> GetChart()
        {
            string            userObjId  = System.Security.Claims.ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
            SessionTokenCache tokenCache = new SessionTokenCache(userObjId, HttpContext);

            string     tenantId    = System.Security.Claims.ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;
            string     authority   = "common";
            AuthHelper authHelper  = new AuthHelper(authority, ConfigurationManager.AppSettings["ida:AppId"], ConfigurationManager.AppSettings["ida:AppSecret"], tokenCache);
            string     accessToken = await authHelper.GetUserAccessToken(Url.Action("Index", "Home", null, Request.Url.Scheme));


            return(await RESTAPIHelper.getChartImage(accessToken));
        }
        public void SignOut()
        {
            if (Request.IsAuthenticated)
            {
                string userObjectId = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;

                SessionTokenCache tokenCache = new SessionTokenCache(userObjectId, HttpContext);
                HttpContext.GetOwinContext().Authentication.SignOut(OpenIdConnectAuthenticationDefaults.AuthenticationType, CookieAuthenticationDefaults.AuthenticationType);
            }

            HttpContext.GetOwinContext().Authentication.SignOut(CookieAuthenticationDefaults.AuthenticationType);
            Response.Redirect("/");
        }
        public async Task <string> GetTokenForApplication()
        {
            string            signedInUserID = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
            string            tenantID       = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;
            string            userObjectID   = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
            string            authority      = aadInstance + tenantID;
            SessionTokenCache tokenCache     = new SessionTokenCache(userObjectID, HttpContext);

            AuthHelper authHelper  = new AuthHelper(authority, clientId, appKey, tokenCache);
            string     accessToken = await authHelper.GetUserAccessToken(Url.Action("Index", "Home", null, Request.Url.Scheme));

            return(accessToken);
        }
예제 #23
0
        /// <summary>
        /// Handle authorization codes by creating a token cache then requesting and storing an access token
        /// for the user.
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        private async Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedNotification context)
        {
            string     userId         = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value;
            TokenCache userTokenCache = new SessionTokenCache(
                userId, context.OwinContext.Environment["System.Web.HttpContextBase"] as HttpContextBase).GetMsalCacheInstance();
            // A ConfidentialClientApplication is a server-side client application that can securely store a client secret,
            // which is not accessible by the user.
            ConfidentialClientApplication cca = new ConfidentialClientApplication(
                clientId, redirectUri, new ClientCredential(clientSecret), userTokenCache, null);

            string[] scopes = this.scopes.Split(new char[] { ' ' });

            AuthenticationResult result = await cca.AcquireTokenByAuthorizationCodeAsync(context.Code, scopes);
        }
        public void ConfigureAuth(IAppBuilder app)
        {
            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

            app.UseCookieAuthentication(new CookieAuthenticationOptions());

            app.UseOpenIdConnectAuthentication(
                new OpenIdConnectAuthenticationOptions
            {
                ClientId              = appId,
                Authority             = "https://login.microsoftonline.com/common/v2.0",
                PostLogoutRedirectUri = redirectUri,
                RedirectUri           = redirectUri,
                Scope = "openid email profile offline_access " + graphScopes,
                TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer = false,
                },
                Notifications = new OpenIdConnectAuthenticationNotifications
                {
                    AuthorizationCodeReceived = async(context) =>
                    {
                        var code = context.Code;
                        string signedInUserID = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value;

                        TokenCache userTokenCache = new SessionTokenCache(
                            signedInUserID,
                            context.OwinContext.Environment["System.Web.HttpContextBase"] as HttpContextBase
                            ).GetMsalCacheInstance();
                        ConfidentialClientApplication cca = new ConfidentialClientApplication(
                            appId,
                            redirectUri,
                            new ClientCredential(appSecret),
                            userTokenCache,
                            null);

                        string[] scopes             = graphScopes.Split(new char[] { ' ' });
                        AuthenticationResult result = await cca.AcquireTokenByAuthorizationCodeAsync(code, scopes);
                    },
                    AuthenticationFailed = (context) =>
                    {
                        context.HandleResponse();
                        context.Response.Redirect("/Error?message=" + context.Exception.Message);
                        return(Task.FromResult(0));
                    }
                }
            }
                );
        }
예제 #25
0
        public void SignOut()
        {
            if (Request.IsAuthenticated)
            {
                // Get the user's token cache and clear it
                string userObjId = AuthHelper.GetUserId(ClaimsPrincipal.Current);

                SessionTokenCache tokenCache = new SessionTokenCache(userObjId, HttpContext);
                tokenCache.Clear();
            }
            // Send an OpenID Connect sign-out request.
            HttpContext.GetOwinContext().Authentication.SignOut(
                CookieAuthenticationDefaults.AuthenticationType);
            Response.Redirect("/");
        }
예제 #26
0
        public async Task <ActionResult> Graph()
        {
            string userObjId = AuthHelper.GetUserId(ClaimsPrincipal.Current);

            SessionTokenCache tokenCache = new SessionTokenCache(userObjId, HttpContext);

            string authority = string.Format(ConfigurationManager.AppSettings["ida:AADInstance"], "common/", "");

            AuthHelper authHelper = new AuthHelper(authority, ConfigurationManager.AppSettings["ida:AppId"],
                                                   ConfigurationManager.AppSettings["ida:AppSecret"], tokenCache);

            ViewBag.AccessToken = await authHelper.GetUserAccessToken(Url.Action("Index", "Home", null, Request.Url.Scheme));

            return(View());
        }
예제 #27
0
 public void SignOut()
 {
     if (Request.IsAuthenticated)
     {
         string userId = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
         if (!string.IsNullOrEmpty(userId))
         {
             // Get the user's token cache and clear it
             SessionTokenCache tokenCache = new SessionTokenCache(userId, HttpContext);
             tokenCache.Clear();
         }
     }
     HttpContext.GetOwinContext().Authentication.SignOut(CookieAuthenticationDefaults.AuthenticationType);
     Response.Redirect("/");
 }
예제 #28
0
        // Here we clear the token cache and end the session with the web app.
        public void SignOut()
        {
            if (Request.IsAuthenticated)
            {
                // Get the user's token cache and clear it.
                string userObjectId = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;

                SessionTokenCache tokenCache = new SessionTokenCache(userObjectId, HttpContext);
                tokenCache.Clear(userObjectId);
            }

            // Send an OpenID Connect sign-out request.
            HttpContext.GetOwinContext().Authentication.SignOut(
                CookieAuthenticationDefaults.AuthenticationType);
            Response.Redirect("/");
        }
예제 #29
0
        public void SignOut()
        {
            if (Request.IsAuthenticated)
            {
                // Get the user's token cache and clear it
                string userObjId = System.Security.Claims.ClaimsPrincipal.Current
                                   .FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;

                SessionTokenCache tokenCache = new SessionTokenCache(userObjId, HttpContext);
                tokenCache.Clear();
            }
            // Send an OpenID Connect sign-out request.
            HttpContext.GetOwinContext().Authentication.SignOut(
                CookieAuthenticationDefaults.AuthenticationType);
            Response.Redirect("/");
        }
        public async Task <ActionResult> Index()
        {
            // Get an access token for the request.
            string            userObjId  = AuthHelper.GetUserId(System.Security.Claims.ClaimsPrincipal.Current);
            SessionTokenCache tokenCache = new SessionTokenCache(userObjId, HttpContext);
            string            authority  = string.Format(ConfigurationManager.AppSettings["ida:AADInstance"], "common", "/v2.0");

            AuthHelper authHelper  = new AuthHelper(authority, ConfigurationManager.AppSettings["ida:AppId"], ConfigurationManager.AppSettings["ida:AppSecret"], tokenCache);
            string     accessToken = await authHelper.GetUserAccessToken("/Notebook/Index");

            // Make the request.
            var repository  = new NotebookRepository(accessToken);
            var myNotebooks = await repository.GetNotebooks();

            return(View(myNotebooks));
        }