protected override System.Threading.Tasks.Task<HttpResponseMessage> SendAsync(
            HttpRequestMessage request,
            CancellationToken cancellationToken)
        {
            AuthenticationHeaderValue authValue = request.Headers.Authorization;
            if (authValue != null && !String.IsNullOrWhiteSpace(authValue.Parameter))
            {
                Credentials parsedCredentials = ParseAuthorizationHeader(authValue.Parameter);
                if (parsedCredentials != null)
                {
                    var id = new BjaIdentity(parsedCredentials.Username, null);//TODO: look up more info on user
                    var user = new CustomPrincipal(id);
                    System.Web.HttpContext.Current.User = user;
                    Thread.CurrentPrincipal = user;
                }
            }

            return base.SendAsync(request, cancellationToken)
               .ContinueWith(task =>
               {
                   var response = task.Result;
                   if (response.StatusCode == HttpStatusCode.Unauthorized
                       && !response.Headers.Contains(BasicAuthResponseHeader))
                   {
                       response.Headers.Add(BasicAuthResponseHeader
                           , BasicAuthResponseHeaderValue);
                   }
                   return response;
               });
        }
Beispiel #2
0
        void MvcApplication_PostAuthenticateRequest(object sender, EventArgs e)
        {
            var authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
            if (authCookie != null && !string.IsNullOrEmpty(authCookie.Value))
            {
                var authTicket = FormsAuthentication.Decrypt(authCookie.Value);
                if (authTicket == null || authTicket.Expired)
                    return;

                var id = new BjaIdentity(authTicket.Name, authTicket.UserData);
                var user = new CustomPrincipal(id);
                Context.User = user;
                Thread.CurrentPrincipal = user;

                HttpCookie cookie = HttpContext.Current.Request.Cookies.Get(CookieName);
                if (cookie == null)
                {
                    cookie = new HttpCookie(CookieName);
                    cookie.Value = "yes";
                    cookie.Expires = DateTime.Now.AddDays(1d);
                    Response.Cookies.Add(cookie);
                }
                else if (!id.IsAuthenticated)
                {
                    Response.Cookies.Remove(CookieName);
                    FormsAuthentication.SignOut();
                }
            }
        }