コード例 #1
0
        public static byte[] EncodeCookie(AADOAuth2AccessToken token)
        {
            var bytes = token.ToBytes();

            for (int i = 0; i < DefaultCookieTransforms.Length; ++i)
            {
                bytes = DefaultCookieTransforms[i].Encode(bytes);
            }
            return(bytes);
        }
コード例 #2
0
 public static AADOAuth2AccessToken DecodeCookie(byte[] bytes)
 {
     try
     {
         for (int i = DefaultCookieTransforms.Length - 1; i >= 0; --i)
         {
             bytes = DefaultCookieTransforms[i].Decode(bytes);
         }
         return(AADOAuth2AccessToken.FromBytes(bytes));
     }
     catch (Exception)
     {
         // bad cookie
         return(null);
     }
 }
コード例 #3
0
        public static void WriteOAuthTokenCookie(HttpApplication application, AADOAuth2AccessToken oauthToken)
        {
            var request  = application.Context.Request;
            var response = application.Context.Response;

            var bytes      = EncodeCookie(oauthToken);
            var cookie     = Convert.ToBase64String(bytes);
            var chunkCount = cookie.Length / CookieChunkSize + (cookie.Length % CookieChunkSize == 0 ? 0 : 1);

            for (int i = 0; i < chunkCount; ++i)
            {
                var setCookie = new StringBuilder();
                setCookie.Append(OAuthTokenCookie);
                if (i > 0)
                {
                    setCookie.Append(i.ToString(CultureInfo.InvariantCulture));
                }

                setCookie.Append('=');

                int startIndex = i * CookieChunkSize;
                setCookie.Append(cookie.Substring(startIndex, Math.Min(CookieChunkSize, cookie.Length - startIndex)));
                setCookie.Append("; path=/; secure; HttpOnly");
                response.Headers.Add("Set-Cookie", setCookie.ToString());
            }

            var cookies = request.Cookies;
            var index   = chunkCount;

            while (true)
            {
                var cookieName = OAuthTokenCookie;
                if (index > 0)
                {
                    cookieName += index.ToString(CultureInfo.InvariantCulture);
                }

                if (cookies[cookieName] == null)
                {
                    break;
                }

                // remove old cookie
                response.Headers.Add("Set-Cookie", String.Format(DeleteCookieFormat, cookieName));
                ++index;
            }
        }
コード例 #4
0
        public void AuthenticateRequest(object sender, EventArgs e)
        {
            ClaimsPrincipal principal   = null;
            var             application = (HttpApplication)sender;
            var             request     = application.Request;
            var             response    = application.Response;

            // only perform authentication if localhost
            //if (!request.Url.IsLoopback)
            //{
            //var displayName = HttpContext.Current.Request.Headers["X-MS-CLIENT-DISPLAY-NAME"];
            //var principalName = HttpContext.Current.Request.Headers["X-MS-CLIENT-PRINCIPAL-NAME"];
            //if (!string.IsNullOrWhiteSpace(principalName) ||
            //    !string.IsNullOrWhiteSpace(displayName))
            //{
            //    principal = new GenericPrincipal(new GenericIdentity(principalName ?? displayName), new[] { "User" });
            //}
            //else
            //{
            //    principal = new ClaimsPrincipal(new ClaimsIdentity("SCM"));
            //}
            //HttpContext.Current.User = principal;
            //Thread.CurrentPrincipal = principal;
            //return;
            //}

            response.Headers["Strict-Transport-Security"] = "max-age=0";

            if (request.Url.Scheme != "https")
            {
                response.Redirect(String.Format("https://{0}{1}", request.Url.Authority, request.Url.PathAndQuery), endResponse: true);
                return;
            }

            if (request.Url.PathAndQuery.StartsWith("/logout", StringComparison.OrdinalIgnoreCase))
            {
                RemoveSessionCookie(application);

                var logoutUrl = GetLogoutUrl(application);
                response.Redirect(logoutUrl, endResponse: true);
                return;
            }

            string tenantId;

            if (SwitchTenant(application, out tenantId))
            {
                RemoveSessionCookie(application);

                var loginUrl = GetLoginUrl(application, tenantId, "/token");
                response.Redirect(loginUrl, endResponse: true);
                return;
            }

            var id_token = request.Form["id_token"];
            var code     = request.Form["code"];
            var state    = request.Form["state"];

            if (!String.IsNullOrEmpty(id_token) && !String.IsNullOrEmpty(code))
            {
                principal = AuthenticateIdToken(application, id_token);
                var tenantIdClaim = principal.Claims.FirstOrDefault(c => c.Type == TenantIdClaimType);
                if (tenantIdClaim == null)
                {
                    throw new InvalidOperationException("Missing tenantid claim");
                }

                var base_uri     = request.Url.GetLeftPart(UriPartial.Authority);
                var redirect_uri = base_uri + "/manage";
                var token        = AADOAuth2AccessToken.GetAccessTokenByCode(tenantIdClaim.Value, code, redirect_uri);
                WriteOAuthTokenCookie(application, token);
                response.Redirect(base_uri + state, endResponse: true);
                return;
            }
            else
            {
                var token = ReadOAuthTokenCookie(application);
                if (token != null)
                {
                    if (!token.IsValid())
                    {
                        token = AADOAuth2AccessToken.GetAccessTokenByRefreshToken(token.TenantId, token.refresh_token, ManagementResource);
                        WriteOAuthTokenCookie(application, token);
                    }

                    principal = new ClaimsPrincipal(new ClaimsIdentity("AAD"));
                    request.ServerVariables["HTTP_X_MS_OAUTH_TOKEN"] = token.access_token;
                }
            }

            if (principal == null)
            {
                var loginUrl = GetLoginUrl(application);
                response.Redirect(loginUrl, endResponse: true);
                return;
            }

            HttpContext.Current.User = principal;
            Thread.CurrentPrincipal  = principal;
        }
コード例 #5
0
        public static AADOAuth2AccessToken ReadOAuthTokenCookie(HttpApplication application)
        {
            var request = application.Context.Request;

            // read oauthtoken cookie
            var cookies = request.Cookies;
            var strb    = new StringBuilder();
            int index   = 0;

            while (true)
            {
                var cookieName = OAuthTokenCookie;
                if (index > 0)
                {
                    cookieName += index.ToString(CultureInfo.InvariantCulture);
                }

                var cookie = cookies[cookieName];
                if (cookie == null)
                {
                    break;
                }

                strb.Append(cookie.Value);
                ++index;
            }

            if (strb.Length == 0)
            {
                return(null);
            }

            var bytes      = Convert.FromBase64String(strb.ToString());
            var oauthToken = DecodeCookie(bytes);

            if (oauthToken == null || !oauthToken.IsValid())
            {
                try
                {
                    if (oauthToken != null)
                    {
                        oauthToken = AADOAuth2AccessToken.GetAccessTokenByRefreshToken(oauthToken.TenantId, oauthToken.refresh_token, oauthToken.resource);
                    }
                }
                catch (Exception)
                {
                    oauthToken = null;
                }

                if (oauthToken == null)
                {
                    RemoveSessionCookie(application);

                    return(null);
                }

                WriteOAuthTokenCookie(application, oauthToken);
            }

            return(oauthToken);
        }