コード例 #1
0
 private async Task ApplyHeaders(bool shouldRedirectToReturnUrl, string returnUrl = null)
 {
     Response.Headers[HeaderNames.CacheControl] = HeaderValueNoCache;
     Response.Headers[HeaderNames.Pragma]       = HeaderValueNoCache;
     Response.Headers[HeaderNames.Expires]      = HeaderValueMinusOne;
     if (shouldRedirectToReturnUrl && Response.StatusCode == 200)
     {
         var query       = Request.Query;
         var redirectUri = query[Options.ReturnUrlParameter];
         if ((!StringValues.IsNullOrEmpty(redirectUri) && IsHostRelative(redirectUri)) || !String.IsNullOrWhiteSpace(returnUrl))
         {
             var redirectContext = new CookieRedirectContext(Context, Options, returnUrl ?? redirectUri);
             await Options.Events.RedirectToReturnUrl(redirectContext);
         }
     }
 }
コード例 #2
0
        public Task OnCustomRedirectToLogin(CookieRedirectContext context)
        {
            var actionContext = context.HttpContext.RequestServices.GetRequiredService <IActionContextAccessor>();

            if (actionContext.ActionContext == null)
            {
                return(_old(context));
            }

            if (actionContext.ActionContext.ActionDescriptor.FilterDescriptors.Any(x => x.Filter is AjaxAttribute))
            {
                // this is an ajax request, return custom JSON telling user that they must be authenticated.
                var serializerSettings = context
                                         .HttpContext
                                         .RequestServices
                                         .GetRequiredService <IOptions <MvcJsonOptions> >()
                                         .Value
                                         .SerializerSettings;

                context.Response.ContentType = "application/json";

                using (var writer = new HttpResponseStreamWriter(context.Response.Body, Encoding.UTF8))
                {
                    using (var jsonWriter = new JsonTextWriter(writer))
                    {
                        jsonWriter.CloseOutput = false;
                        var jsonSerializer = JsonSerializer.Create(serializerSettings);
                        jsonSerializer.Serialize(jsonWriter, new
                        {
                            success = false,
                            error   = "You must be signed in."
                        });
                    }
                }

                return(Task.FromResult(0));
            }
            else
            {
                // this is a normal request to an endpoint that is secured.
                // do what ASP.NET used to do.
                return(_old(context));
            }
        }
        //private void ApplyHeaders(bool shouldRedirectToReturnUrl = false)
        private async Task ApplyHeaders(bool shouldRedirectToReturnUrl)
        {
            Response.Headers[HeaderNames.CacheControl] = HeaderValueNoCache;
            Response.Headers[HeaderNames.Pragma]       = HeaderValueNoCache;
            Response.Headers[HeaderNames.Expires]      = HeaderValueMinusOne;

            if (shouldRedirectToReturnUrl && Response.StatusCode == 200)
            {
                var query          = Request.Query;
                var tenantResolver = tenantResolverFactory.GetResolver();
                var redirectUri    = query[tenantResolver.ResolveReturnUrlParameter(Options.ReturnUrlParameter)];

                if (!string.IsNullOrEmpty(redirectUri) &&
                    IsHostRelative(redirectUri))
                {
                    var redirectContext = new CookieRedirectContext(Context, Options, redirectUri);
                    await Options.Events.RedirectToReturnUrl(redirectContext);
                }
            }
        }
コード例 #4
0
        protected override async Task <bool> HandleUnauthorizedAsync(ChallengeContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            var redirectUri = new AuthenticationProperties(context.Properties).RedirectUri;

            if (string.IsNullOrEmpty(redirectUri))
            {
                redirectUri = OriginalPathBase + Request.Path + Request.QueryString;
            }

            var loginUri        = Options.LoginPath + QueryString.Create(Options.ReturnUrlParameter, redirectUri);
            var redirectContext = new CookieRedirectContext(Context, Options, BuildRedirectUri(loginUri));
            await Options.Events.RedirectToLogin(redirectContext);

            return(true);
        }
        protected override async Task <bool> HandleUnauthorizedAsync(ChallengeContext context)
        {
            if (!Options.LoginPath.HasValue)
            {
                return(await base.HandleUnauthorizedAsync(context));
            }

            var redirectUri = new AuthenticationProperties(context.Properties).RedirectUri;

            //try
            //{
            if (string.IsNullOrEmpty(redirectUri))
            {
                redirectUri = OriginalPathBase + Request.Path + Request.QueryString;
            }

            //var loginUri = Options.LoginPath + QueryString.Create(Options.ReturnUrlParameter, redirectUri);
            var tenantResolver = tenantResolverFactory.GetResolver();
            var loginUri       = Options.LoginPath + QueryString.Create(tenantResolver.ResolveReturnUrlParameter(Options.ReturnUrlParameter), redirectUri);

            //var redirectContext = new CookieApplyRedirectContext(Context, Options, BuildRedirectUri(loginUri));
            //Options.Notifications.ApplyRedirect(redirectContext);

            var redirectContext = new CookieRedirectContext(Context, Options, BuildRedirectUri(loginUri));
            await Options.Events.RedirectToLogin(redirectContext);

            //}
            //catch (Exception exception)
            //{
            //    var exceptionContext = new CookieExceptionContext(Context, Options,
            //        CookieExceptionContext.ExceptionLocation.Unauthorized, exception, ticket: null);
            //    await Options.Events.Exception(exceptionContext);
            //    if (exceptionContext.Rethrow)
            //    {
            //        throw;
            //    }
            //}
            return(true);
        }
コード例 #6
0
        protected override async Task <bool> HandleUnauthorizedAsync(ChallengeContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            //create a return url that is the current requests full url
            var returnUrl = $"{Request.Scheme}://{Request.Host}{Request.Path}{Request.QueryString}";

            //if user not authenticated but the form post contains a SignInResponseMessage - so they've come back from the IdP after signing in - handle it to sign the user in to this app.
            var signInResponse = GetSignInResponseMessage();

            if (signInResponse != null)
            {
                Dictionary <string, string> props = new Dictionary <string, string>();

                //Add the persistent option to the props for the cookie handler here if it's set to true in the Options object. This is to have IsPersistent available as a higher level option instead of
                //having to pass to SignInAsync as an option.
                if (Options.IsPersistent)
                {
                    props.Add(".persistent", "");
                }

                WsFedSignInContext c = new WsFedSignInContext(Options.AuthenticationScheme, Context.User, props, signInResponse, returnUrl);
                await this.SignInAsync(c);

                return(true);
            }

            //User is not authenticated, so create SignInRequest message to send to IdP endpoint, and redirect there.
            SignInRequestMessage req = new SignInRequestMessage(new Uri(Options.IdPEndpoint), Options.Realm, returnUrl);
            var signInUrl            = req.RequestUrl;
            var redirectContext      = new CookieRedirectContext(Context, Options, signInUrl);
            await Options.Events.RedirectToLogin(redirectContext);

            return(true);
        }
コード例 #7
0
        public override Task RedirectToLogin(CookieRedirectContext context)
        {
            var shortHandUrl = context.Request.Path.ToString()
                               .Split(new[] { "/" }, StringSplitOptions.RemoveEmptyEntries)
                               .ToList()
                               .FirstOrDefault();

            if (shortHandUrl == null)
            {
                throw new Exception("Unable to determine host url");
            }
            var queryString  = QueryHelpers.ParseQuery(new Uri(context.RedirectUri).Query);
            var returnUrl    = queryString[context.Options.ReturnUrlParameter];
            var authRedirect = new UriBuilder(new Uri(context.Request.GetDisplayUrl()).GetLeftPart(UriPartial.Path))
            {
                Path = shortHandUrl + context.Options.LoginPath
            };
            var redirectUrl = QueryHelpers.AddQueryString(authRedirect.ToString(), context.Options.ReturnUrlParameter, returnUrl);

            context.Response.Redirect(redirectUrl);

            return(Task.FromResult <object>(null));
        }
コード例 #8
0
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddAuthentication(options => options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme);
            services.AddDataProtection();
            services.Configure <CookieAuthenticationOptions>(options =>
            {
                options.AutomaticAuthenticate = true;
                options.AutomaticChallenge    = true;
                options.LoginPath             = new PathString("/login");
                options.LogoutPath            = new PathString("/logout");
                options.Events = new CookieAuthenticationEvents
                {
                    OnSigningOut = (context) =>
                    {
                        // Single Sign-Out
                        var casUrl      = new Uri(Configuration["Authentication:CAS:CasServerUrlBase"]);
                        var serviceUrl  = new Uri(context.Request.GetEncodedUrl()).GetComponents(UriComponents.SchemeAndServer, UriFormat.Unescaped);
                        var redirectUri = UriHelper.BuildAbsolute(casUrl.Scheme, new HostString(casUrl.Host, casUrl.Port), casUrl.LocalPath, "/logout", QueryString.Create("service", serviceUrl));

                        var logoutRedirectContext = new CookieRedirectContext(
                            context.HttpContext,
                            context.Options,
                            redirectUri,
                            context.Properties
                            );
                        context.Response.StatusCode = 204; //Prevent RedirectToReturnUrl
                        context.Options.Events.RedirectToLogout(logoutRedirectContext);
                        return(Task.FromResult(0));
                    }
                };
            });
            services.Configure <CasAuthenticationOptions>(options =>
            {
                options.CasServerUrlBase = Configuration["Authentication:CAS:CasServerUrlBase"];
                options.UseTicketStore   = true;
                options.Events           = new CasEvents
                {
                    OnCreatingTicket = (context) =>
                    {
                        // first_name, family_name, display_name, email, verified_email
                        var assertion = (context.Principal as ICasPrincipal)?.Assertion;
                        if (assertion == null || !assertion.Attributes.Any())
                        {
                            return(Task.FromResult(0));
                        }
                        var identity = context.Principal.Identity as ClaimsIdentity;
                        if (identity == null)
                        {
                            return(Task.FromResult(0));
                        }
                        var email = assertion.Attributes["email"]?.FirstOrDefault();
                        if (!string.IsNullOrEmpty(email))
                        {
                            identity.AddClaim(new Claim(ClaimTypes.Email, email));
                        }
                        var name = assertion.Attributes["display_name"]?.FirstOrDefault();
                        if (!string.IsNullOrEmpty(name))
                        {
                            identity.AddClaim(new Claim(ClaimTypes.Name, name));
                        }
                        return(Task.FromResult(0));
                    }
                };
            });
            services.Configure <OAuthOptions>(options =>
            {
                options.AuthenticationScheme    = "OAuth";
                options.DisplayName             = "OAuth";
                options.ClientId                = Configuration["Authentication:OAuth:ClientId"];
                options.ClientSecret            = Configuration["Authentication:OAuth:ClientSecret"];
                options.CallbackPath            = new PathString("/sign-oauth");
                options.AuthorizationEndpoint   = Configuration["Authentication:OAuth:AuthorizationEndpoint"];
                options.TokenEndpoint           = Configuration["Authentication:OAuth:TokenEndpoint"];
                options.SaveTokens              = true;
                options.UserInformationEndpoint = Configuration["Authentication:OAuth:UserInformationEndpoint"];
                options.Events = new OAuthEvents
                {
                    OnCreatingTicket = async context =>
                    {
                        var request = new HttpRequestMessage(HttpMethod.Get, context.Options.UserInformationEndpoint);
                        request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", context.AccessToken);
                        request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                        var response = await context.Backchannel.SendAsync(request, context.HttpContext.RequestAborted);
                        response.EnsureSuccessStatusCode();

                        var user       = JObject.Parse(await response.Content.ReadAsStringAsync());
                        var identifier = user.Value <string>("id");
                        if (!string.IsNullOrEmpty(identifier))
                        {
                            context.Identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, identifier));
                        }
                        var attributes = user.Value <JObject>("attributes");
                        if (attributes == null)
                        {
                            return;
                        }
                        var email = attributes.Value <string>("email");
                        if (!string.IsNullOrEmpty(email))
                        {
                            context.Identity.AddClaim(new Claim(ClaimTypes.Email, email));
                        }
                        var name = attributes.Value <string>("display_name");
                        if (!string.IsNullOrEmpty(name))
                        {
                            context.Identity.AddClaim(new Claim(ClaimTypes.Name, name));
                        }
                    }
                };
            });
        }
 public Task RedirectToAccessDenied(CookieRedirectContext context)
 {
     context.Response.Headers["Location"] = context.RedirectUri;
     context.Response.StatusCode          = 401;
     return(Task.CompletedTask);
 }
 public Task RedirectToReturnUrl(CookieRedirectContext context)
 {
     return(Task.CompletedTask);
 }
 public Task RedirectToLogout(CookieRedirectContext context)
 {
     return(Task.CompletedTask);
 }
コード例 #12
0
 public override Task RedirectToLogin(CookieRedirectContext context)
 {
     context.RedirectUri = < PUT LOGIC HERE TO REPLACE YOUR REDIRECT URI >
                           return(base.RedirectToLogin(context));
 }
コード例 #13
0
 public Task RedirectToReturnUrl(CookieRedirectContext context)
 {
     return(Task.FromResult(0));
 }
コード例 #14
0
 public Task RedirectToLogout(CookieRedirectContext context)
 {
     return(Task.FromResult(0));
 }
コード例 #15
0
 public Task RedirectToLogin(CookieRedirectContext context)
 {
     return(RedirectHttpOnly(context));
 }
コード例 #16
0
 public Task RedirectToAccessDenied(CookieRedirectContext context)
 {
     return(RedirectHttpOnly(context));
 }