Exemplo n.º 1
0
        public async Task <SendPasswordResetEmailResult> SendPasswordResetEmail(SendPasswordResetEmailCommand config, AppUser user)
        {
            var link = UrlHelperExtensions.Action(
                _urlHelper,                                              /*Url Helper*/
                "PasswordResetConfirmation",                             /*Action*/
                "Authenticate",                                          /*Controller*/
                new { userId = user.Id },                                /*Object Value*/
                _httpContextAccessor.HttpContext.Request.Scheme,         /*Scheme*/
                _httpContextAccessor.HttpContext.Request.Host.ToString() /*Host*/
                );

            var client      = new SendGridClient(config.ApiKey);
            var from        = new EmailAddress(config.SenderEmail, config.SenderName);
            var to          = new EmailAddress(config.ReceiverEmail, config.ReceiverName);
            var htmlContent = $"<p>You recently requested to reset your password for your MRT FareMatrix Account. Click the link provided below to confirm password reset.<br></p>" +
                              $"<a href='{HtmlEncoder.Default.Encode(link)}'>Reset Password</a>" +
                              $"<p>If you did not request this password reset, please ignore this message.</p>" +
                              $"<p>- MRT Farematrix Team.</p>";

            var msg = MailHelper.CreateSingleEmail(
                from,
                to,
                config.Subject,
                config.TextContent,
                htmlContent);

            msg.SetClickTracking(false, false);
            var response = await client.SendEmailAsync(msg);

            return(new SendPasswordResetEmailResult
            {
                Response = response
            });
        }
        public static MvcForm BeginAjaxForm(this IHtmlHelper htmlHelper, string actionName, string controllerName, RouteValueDictionary routeValues, FormMethod method, AjaxFormOptions options, IDictionary <string, object> htmlAttributes)
        {
            var    actionContext = new ActionContext(htmlHelper.ViewContext.HttpContext, htmlHelper.ViewContext.HttpContext.GetRouteData(), new ActionDescriptor());
            string formAction    = UrlHelperExtensions.Action(new UrlHelper(actionContext), actionName, controllerName, routeValues ?? new RouteValueDictionary());

            return(FormHelper(htmlHelper, formAction, method, options, htmlAttributes));
        }
Exemplo n.º 3
0
        public async Task <IActionResult> Logout(LogoutInputModel model)
        {
            // build a model so the logged out page knows what to display
            var vm = await _account.BuildLoggedOutViewModelAsync(model.LogoutId);

            var user = HttpContext.User;

            if (user?.Identity.IsAuthenticated == true)
            {
                // delete local authentication cookie
                await HttpContext.SignOutAsync();

                // raise the logout event
                await _events.RaiseAsync(new UserLogoutSuccessEvent(user.GetSubjectId(), user.GetDisplayName()));
            }

            // check if we need to trigger sign-out at an upstream identity provider
            if (vm.TriggerExternalSignout)
            {
                // build a return URL so the upstream provider will redirect back
                // to us after the user has logged out. this allows us to then
                // complete our single sign-out processing.
                string url = UrlHelperExtensions.Action(Url, "Logout", new { logoutId = vm.LogoutId });

                // this triggers a redirect to the external provider for sign-out
                return(SignOut(new AuthenticationProperties {
                    RedirectUri = url
                }, vm.ExternalAuthenticationScheme));
            }

            return(View("LoggedOut", vm));
        }
Exemplo n.º 4
0
        public async Task <IActionResult> Forgot([FromBody] AccountDTO dto)
        {
            if (!IsPopulated(dto?.email))
            {
                return(BadRequest());
            }

            var user = await _userManager.FindByEmailAsync(dto.Username);

            if (user == null)
            {
                return(BadRequest("@UnknownUser"));
            }

            var code = await _userManager.GeneratePasswordResetTokenAsync(user);

            var callbackUrl = UrlHelperExtensions.Action(Url, "Index", "Home", new { reset = dto.Username, code = code }, HttpContext.Request.Scheme);

            _logger.LogInformation(5, $"User {dto.Username} requested a password reset link.");
            var subject = dto.messages != null && dto.messages.Length > 0 && !string.IsNullOrWhiteSpace(dto.messages[0]) ? dto.messages[0] : "Tracktor - password reset";
            var body    = dto.messages != null && dto.messages.Length > 1 && !string.IsNullOrWhiteSpace(dto.messages[1]) ? dto.messages[1] : "Please click the link below to reset your password.";
            await _emailSender.SendEmailAsync(dto.Username, subject, body, callbackUrl);

            return(Ok());
        }
Exemplo n.º 5
0
        public override Task RedirectToLogin(RedirectContext <CookieAuthenticationOptions> context)
        {
            var routeData   = context.Request.HttpContext.GetRouteData();
            var routeValues = routeData.Values;
            var uri         = new Uri(context.RedirectUri);
            var returnUrl   = HttpUtility.ParseQueryString(uri.Query)[context.Options.ReturnUrlParameter];
            var parameters  = $"id={Guid.NewGuid().ToString()}";
            //routeValues.Add(context.Options.ReturnUrlParameter, $"{returnUrl}{parameters}");
            var urlHelper = helper.GetUrlHelper(accessor.ActionContext);

            context.RedirectUri = UrlHelperExtensions.Action(urlHelper, "SignIn", "ApiAuthentication", routeValues);
            return(base.RedirectToLogin(context));
        }
Exemplo n.º 6
0
        public async Task <IActionResult> ExternalLogin(string provider, string returnUrl)
        {
            var props = new AuthenticationProperties
            {
                RedirectUri = UrlHelperExtensions.Action(Url, "ExternalLoginCallback"),
                Items       =
                {
                    { "returnUrl", returnUrl }
                }
            };

            // windows authentication needs special handling
            // since they don't support the redirect uri,
            // so this URL is re-triggered when we call challenge
            if (AccountOptions.WindowsAuthenticationSchemeName == provider)
            {
                // see if windows auth has already been requested and succeeded
                var result = await HttpContext.AuthenticateAsync(AccountOptions.WindowsAuthenticationSchemeName);

                if (result?.Principal is WindowsPrincipal wp)
                {
                    props.Items.Add("scheme", AccountOptions.WindowsAuthenticationSchemeName);

                    var id = new ClaimsIdentity(provider);
                    id.AddClaim(new Claim(JwtClaimTypes.Subject, wp.Identity.Name));
                    id.AddClaim(new Claim(JwtClaimTypes.Name, wp.Identity.Name));

                    // add the groups as claims -- be careful if the number of groups is too large
                    if (AccountOptions.IncludeWindowsGroups)
                    {
                        var wi     = wp.Identity as WindowsIdentity;
                        var groups = wi.Groups.Translate(typeof(NTAccount));
                        var roles  = groups.Select(x => new Claim(JwtClaimTypes.Role, x.Value));
                        id.AddClaims(roles);
                    }

                    await HttpContext.SignInAsync(
                        IdentityServerConstants.ExternalCookieAuthenticationScheme,
                        new ClaimsPrincipal(id),
                        props);

                    return(Redirect(props.RedirectUri));
                }
                // challenge/trigger windows auth
                return(Challenge(AccountOptions.WindowsAuthenticationSchemeName));
            }
            // start challenge and roundtrip the return URL
            props.Items.Add("scheme", provider);
            return(Challenge(props, provider));
        }
        private async Task <IActionResult> ProcessWindowsLoginAsync(string returnUrl)
        {
            // see if windows auth has already been requested and succeeded
            var result = await HttpContext.AuthenticateAsync(AccountOptions.WindowsAuthenticationSchemeName);

            if (result?.Principal is WindowsPrincipal wp)
            {
                // we will issue the external cookie and then redirect the
                // user back to the external callback, in essence, tresting windows
                // auth the same as any other external authentication mechanism
                var props = new AuthenticationProperties()
                {
                    RedirectUri = UrlHelperExtensions.Action(Url, "ExternalLoginCallback"),
                    Items       =
                    {
                        { "returnUrl", returnUrl                                      },
                        { "scheme",    AccountOptions.WindowsAuthenticationSchemeName },
                    }
                };

                var id = new ClaimsIdentity(AccountOptions.WindowsAuthenticationSchemeName);
                id.AddClaim(new Claim(JwtClaimTypes.Subject, wp.Identity.Name));
                id.AddClaim(new Claim(JwtClaimTypes.Name, wp.Identity.Name));

                // add the groups as claims -- be careful if the number of groups is too large
                if (AccountOptions.IncludeWindowsGroups)
                {
                    var wi     = wp.Identity as WindowsIdentity;
                    var groups = wi.Groups.Translate(typeof(NTAccount));
                    var roles  = groups.Select(x => new Claim(JwtClaimTypes.Role, x.Value));
                    id.AddClaims(roles);
                }

                await HttpContext.SignInAsync(
                    IdentityServer4.IdentityServerConstants.ExternalCookieAuthenticationScheme,
                    new ClaimsPrincipal(id),
                    props);

                return(Redirect(props.RedirectUri));
            }
            else
            {
                // trigger windows auth
                // since windows auth don't support the redirect uri,
                // this URL is re-triggered when we call challenge
                return(Challenge(AccountOptions.WindowsAuthenticationSchemeName));
            }
        }
Exemplo n.º 8
0
        public IActionResult SignIn(string provider, string returnUrl = null)
        {
            //IL_0001: Unknown result type (might be due to invalid IL or missing references)
            //IL_0006: Unknown result type (might be due to invalid IL or missing references)
            //IL_0031: Expected O, but got Unknown
            AuthenticationProperties val = new AuthenticationProperties();

            val.RedirectUri = (UrlHelperExtensions.Action(this.Url, "ExternalLoginCallback", (object)new
            {
                returnUrl
            }));
            return(this.Challenge(val, new string[1]
            {
                provider
            }));
        }
Exemplo n.º 9
0
        public IActionResult SignIn(string returnUrl, [FromQuery(Name = "fr")] bool isFeedbackRedirect)
        {
            string text = this.Url.IsLocalUrl(returnUrl) ? returnUrl : UrlHelperExtensions.Action(this.Url, "Index", "Home");

            if (base.CurrentUser != null)
            {
                return(this.Redirect(text));
            }
            LoginViewModel loginViewModel = new LoginViewModel
            {
                ReturnUrl          = text,
                IsFeedbackRedirect = isFeedbackRedirect
            };

            return(this.View((object)loginViewModel));
        }
Exemplo n.º 10
0
        public CreateEmailVerificationTokenResult CreateEmailVerificationToken(AppUser user)
        {
            //Generate Token
            var token = _userManager.GenerateEmailConfirmationTokenAsync(user).Result;
            //Encode token
            var code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(token));
            //Build link
            var link = UrlHelperExtensions.Action(
                _urlHelper,                                              /*Url Helper*/
                "VerifyEmail",                                           /*Action*/
                "Authenticate",                                          /*Controller*/
                new { userId = user.Id, code },                          /*Object Value*/
                _httpContextAccessor.HttpContext.Request.Scheme,         /*Scheme*/
                _httpContextAccessor.HttpContext.Request.Host.ToString() /*Host*/
                );

            return(new CreateEmailVerificationTokenResult
            {
                Link = link
            });
        }
 public async Task <IActionResult> ExternalLogin(string provider, string returnUrl)
 {
     if (AccountOptions.WindowsAuthenticationSchemeName == provider)
     {
         // windows authentication needs special handling
         return(await ProcessWindowsLoginAsync(returnUrl));
     }
     else
     {
         // start challenge and roundtrip the return URL and
         var props = new AuthenticationProperties()
         {
             RedirectUri = UrlHelperExtensions.Action(Url, "ExternalLoginCallback"),
             Items       =
             {
                 { "returnUrl", returnUrl },
                 { "scheme",    provider  },
             }
         };
         return(Challenge(props, provider));
     }
 }
Exemplo n.º 12
0
 public static string AbsoluteAction(this IUrlHelper url, string actionName, string controllerName, object routeValues = null)
 {
     return(UrlHelperExtensions.Action(url, actionName, controllerName, routeValues, url.get_ActionContext().get_HttpContext().get_Request().get_Scheme()));
 }
Exemplo n.º 13
0
        public static string Action(string actionName, string controllerName, string routeName, RouteValueDictionary routeValueDictionary)
        {
            string cacheKey = string.Format("ActionUrl::c:{0}-a:{1}-r:{2}", controllerName, actionName, routeName);

            RouteValueDictionary routeParameters = new RouteValueDictionary();

            string[] values = null;
            if (routeValueDictionary != null)
            {
                values = new string[routeValueDictionary.Count];
                int index = 0;
                foreach (KeyValuePair <string, object> pair in routeValueDictionary)
                {
                    cacheKey += "-" + pair.Key + ":{" + index + "}";

                    if (pair.Value == null)
                    {
                        values[index] = string.Empty;
                    }
                    else
                    {
                        values[index] = pair.Value.ToString();
                    }

                    routeParameters[pair.Key] = "{" + index + "}";

                    index++;
                }
            }

            ICacheService cacheService = DIContainer.Resolve <ICacheService>();
            string        url          = cacheService.Get <string>(cacheKey);

            if (url == null)
            {
                try
                {
                    var httpContext   = HttpContextCore.Current;
                    var actionContext = new ActionContext(httpContext, httpContext.GetRouteData(), new ActionDescriptor());
                    url = UrlHelperExtensions.Action(new UrlHelper(actionContext), actionName, controllerName, routeParameters);
                }
                catch (Exception e)
                {
                    url = string.Empty;
                }

                if (string.IsNullOrEmpty(url))
                {
                    return(string.Empty);
                }
                url = url.Replace("%7b", "{").Replace("%7d", "}").Replace("%7B", "{").Replace("%7D", "}");//.ToLower();
                cacheService.Add(cacheKey, url, CachingExpirationType.Stable);
            }

            if (values != null)
            {
                return(string.Format(url, values));
            }
            else
            {
                return(url);
            }
        }