Beispiel #1
0
        public async Task <IActionResult> Login(LoginDTO loginDto)
        {
            var identity = loginHelper.GetClaimsIdentity(loginDto.ChipId, loginDto.Password);

            if (identity == null)
            {
                ViewBag.Error = "Wrooong!";
            }
            else
            {
                // issue an authentication cookie
                var properties = new AuthenticationProperties()
                {
                    IsPersistent = true,
                    ExpiresUtc   = DateTime.UtcNow.AddMonths(1)
                };
                await AuthenticationHttpContextExtensions.SignInAsync(HttpContext, new ClaimsPrincipal(identity), properties);

                // redirect to the home page
                return(RedirectToRoute(new
                {
                    controller = "Home",
                    action = "Index"
                }));
            }
            return(View());
        }
        protected override async Task <AuthenticateResult> HandleAuthenticateAsync()
        {
            var    action     = Request.Method;
            string controller = string.Empty;
            string api        = string.Empty;

            try
            {
                controller = Request.Path.Value.Contains("/api/") ? Request.Path.Value.Split('/')[2] : string.Empty;
                api        = Request.Path.Value.Contains("/api/") && Request.Path.Value.Split('/').Length > 3
                    ? Request.Path.Value.Split('/')[3]
                    : string.Empty;
            }
            catch (Exception)
            {
                Logging <AuthValidationHandler> .Warning("URL not valid: " + Request.Path.Value);

                return(AuthenticateResult.Fail("URL not valid: " + Request.Path.Value));
            }

            AuthenticationTicket ticket = await CreateTicketAsync(action, controller, api);

            if (ticket == null)
            {
                return(AuthenticateResult.Fail("Authentication failed because the access token was invalid."));
            }

            await AuthenticationHttpContextExtensions.SignInAsync(Request.HttpContext, ticket.AuthenticationScheme, ticket.Principal);

            return(AuthenticateResult.Success(ticket));
        }
Beispiel #3
0
        public async Task <IActionResult> GoogleCallback(string code)
        {
            var token = await _api.TokenExchange(code);

            var googleUser = await _api.GoogleUser(token);

            var user = await _db.Users.FirstOrDefaultAsync(u => u.Email == googleUser.Email);

            if (user == null)
            {
                return(RedirectToAction("Beta", "Home"));
            }

            var claims = new List <Claim>()
            {
                new Claim(ClaimTypes.Role, "user"),
                new Claim(ClaimTypes.Name, googleUser.Name),
                new Claim(ClaimTypes.Email, googleUser.Email),
                new Claim(ClaimTypes.Sid, user.Id.ToString())
            };
            var identity  = new ClaimsIdentity(claims, "GoogleAuthLogin");
            var principal = new ClaimsPrincipal(new[] { identity });
            await AuthenticationHttpContextExtensions.SignInAsync(HttpContext, AUTH_NAME, principal);

            return(RedirectToAction("Index", "Home"));
        }
Beispiel #4
0
        public async Task <IActionResult> SignIn([FromBody] LoginArgs loginArgs)
        {
            try
            {
                // credential validation ...

                var claims = new List <Claim>
                {
                    new Claim(ClaimTypes.Name, "Alex")
                };
                var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
                var authProperties = new AuthenticationProperties
                {
                    IsPersistent = true,
                    RedirectUri  = Request.Host.Value
                };

                await AuthenticationHttpContextExtensions.SignInAsync(
                    HttpContext,
                    CookieAuthenticationDefaults.AuthenticationScheme,
                    new ClaimsPrincipal(claimsIdentity),
                    authProperties);

                return(Ok());
            }
            catch (Exception ex)
            {
                return(BadRequest(new { Error = ex.Message }));
            }
        }
        /// <summary>
        /// 设置授权认证数
        /// </summary>
        /// <param name="value">实体序列化JsonConvert.SerializeObject(data)</param>
        /// <param name="valueType"></param>
        public async void SetsAuthenticationAsync(string value, AuthorizationStorageType valueType)
        {
            var claims = new List <Claim>()
            {
                new Claim(valueType.ToString(), value)
            };
            Task <AuthenticateResult> authenticateInfo = AuthenticationHttpContextExtensions.AuthenticateAsync(HttpContext, authenticationScheme);

            if (!authenticateInfo.IsFaulted && authenticateInfo.Result.Principal != null)
            {
                claims = authenticateInfo.Result.Principal.Claims.ToList();
                int idx = claims.FindIndex(c => { return(c.Type.Equals(valueType.ToString())); });
                if (idx >= 0)
                {
                    claims.RemoveAt(idx);
                }
                claims.Add(new Claim(valueType.ToString(), value));
            }
            ClaimsIdentity identity      = new ClaimsIdentity(claims);
            var            userPrincipal = new ClaimsPrincipal(identity);
            await AuthenticationHttpContextExtensions.SignInAsync(HttpContext, authenticationScheme, userPrincipal, new Microsoft.AspNetCore.Authentication.AuthenticationProperties
            {
                ExpiresUtc   = DateTime.UtcNow.AddHours(24),
                IsPersistent = false,
                AllowRefresh = true
            });
        }
        public async Task <IActionResult> Login(string name, string password, string email)
        {
            //validate that there is user data
            if (string.IsNullOrEmpty(name) || string.IsNullOrEmpty(password) || string.IsNullOrEmpty(email))
            {
                RedirectToAction(nameof(Index), nameof(HomeController));
            }

            //login the user: ClaimsIdentity, ClaimsPrincipal and SignInAsync()
            //Create identity clames for the user data
            var claims = new List <Claim>()
            {
                new Claim(ClaimTypes.Name, name),
                new Claim(ClaimTypes.Email, email)
            };
            var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);

            //create a claims principal for the user
            var principal = new ClaimsPrincipal(identity);

            //login the user
            await AuthenticationHttpContextExtensions.SignInAsync(HttpContext, CookieAuthenticationDefaults.AuthenticationScheme, principal);

            return(RedirectToAction("LogedInUsers", "Authentication"));
        }
Beispiel #7
0
        private async Task PerformSignIn(GenericPrincipal user, string webToken)
        {
            Dictionary <string, string> items = new Dictionary <string, string>
            {
                { "AuthScheme", CookieAuthenticationDefaults.AuthenticationScheme },
            };

            AuthenticationProperties props = new AuthenticationProperties(items)
            {
                // web authentication ticket life time, after expire new log in required
                ExpiresUtc   = DateTime.UtcNow.AddHours(8),
                IsPersistent = false,
                AllowRefresh = false,
            };

            List <AuthenticationToken> authenticationTokens = new List <AuthenticationToken>
            {
                new AuthenticationToken {
                    Name = "access_token", Value = webToken
                },
            };

            AuthenticationTokenExtensions.StoreTokens(props, authenticationTokens);

            await AuthenticationHttpContextExtensions.SignInAsync(_httpContext,
                                                                  CookieAuthenticationDefaults.AuthenticationScheme, user, props);
        }
Beispiel #8
0
        public async Task <ActionResult> ACS(IFormCollection collection)
        {
            string       samlResponse = "";
            string       redirect     = "";
            AuthResponse resp         = new AuthResponse();

            try
            {
                samlResponse = Encoding.UTF8.GetString(Convert.FromBase64String(collection["SAMLResponse"]));
                redirect     = Encoding.UTF8.GetString(Convert.FromBase64String(collection["RelayState"]));

                resp.Deserialize(samlResponse);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error reading SAML Response {0}", samlResponse);
            }
            if (resp.RequestStatus == SamlRequestStatus.Success)
            {
                //CookieOptions options = new CookieOptions();
                //options.Expires = resp.SessionIdExpireDate;
                //Response.Cookies.Delete("SPID_COOKIE");
                //Response.Cookies.Append("SPID_COOKIE", JsonConvert.SerializeObject(resp), options);

                var scheme = "SPIDCookie"; //CookieAuthenticationDefaults.AuthenticationScheme

                var claims = resp.GetClaims();

                var identityClaims = new List <Claim>();

                foreach (var item in claims)
                {
                    identityClaims.Add(new Claim(item.Key, item.Value, ClaimValueTypes.String, resp.Issuer));
                }
                identityClaims.Add(new Claim(ClaimTypes.Name, claims["Name"], ClaimValueTypes.String, resp.Issuer));
                identityClaims.Add(new Claim(ClaimTypes.Surname, claims["FamilyName"], ClaimValueTypes.String, resp.Issuer));
                identityClaims.Add(new Claim(ClaimTypes.Email, claims["Email"], ClaimValueTypes.String, resp.Issuer));

                var identity = new ClaimsIdentity(identityClaims, scheme);

                var principal = new ClaimsPrincipal(identity);

                HttpContext.User = principal;

                await AuthenticationHttpContextExtensions.SignInAsync(HttpContext, scheme, principal,
                                                                      new AuthenticationProperties
                {
                    ExpiresUtc   = DateTime.UtcNow.AddMinutes(20),
                    IsPersistent = true,
                    AllowRefresh = false
                });
            }

            if (string.IsNullOrEmpty(redirect))
            {
                redirect = "/";
            }

            return(Redirect(redirect));
        }
Beispiel #9
0
        public async Task <IActionResult> Login(LoginViewModel model)
        {
            if (!Request.Form.Keys.Any(x => x == "external"))
            {
                // 通常ログイン
                if (ModelState.IsValid)
                {
                    if (!string.IsNullOrEmpty(model.UserName))
                    {
                        // 認証情報を作成する。
                        List <Claim> claims = new List <Claim>();
                        claims.Add(new Claim(ClaimTypes.Name, model.UserName));

                        // 認証情報を保存する。
                        ClaimsIdentity  userIdentity  = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
                        ClaimsPrincipal userPrincipal = new ClaimsPrincipal(userIdentity);

                        // サイン アップする。
                        await AuthenticationHttpContextExtensions.SignInAsync(
                            this.HttpContext, CookieAuthenticationDefaults.AuthenticationScheme, userPrincipal);

                        // 認証情報を保存する。
                        MyUserInfo ui = new MyUserInfo(model.UserName, (new GetClientIpAddress()).GetAddress());
                        UserInfoHandle.SetUserInformation(ui);

                        //基盤に任せるのでリダイレクトしない。
                        return(View(model));
                    }
                    else
                    {
                        // ユーザー認証 失敗
                        this.ModelState.AddModelError(string.Empty, "指定されたユーザー名またはパスワードが正しくありません。");
                    }
                }
                else
                {
                    // LoginViewModelの検証に失敗
                }

                // Session消去
                //this.FxSessionAbandon();

                // ポストバック的な
                return(this.View(model));
            }
            else
            {
                // 外部ログイン
                return(Redirect(string.Format(
                                    "https://localhost:44300/MultiPurposeAuthSite/authorize"
                                    + "?client_id=" + OAuth2AndOIDCParams.ClientID
                                    + "&response_type=code"
                                    + "&scope=profile%20email%20phone%20address%20openid"
                                    + "&state={0}"
                                    + "&nonce={1}"
                                    + "&prompt=none",
                                    this.State, this.Nonce)));
            }
        }
Beispiel #10
0
        public async Task <IActionResult> Login(LoginDto data)
        {
            var claims   = new[] { new Claim(ClaimTypes.Name, data.Username), new Claim(ClaimTypes.Role, "role") };
            var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
            await AuthenticationHttpContextExtensions.SignInAsync(HttpContext, CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(identity));

            return(Redirect("~/Home/Profile"));
        }
Beispiel #11
0
        /// <summary>
        /// Handle onPost Login AJAX based dengan return value JsonResult
        /// </summary>
        /// <param name="request_parameter"></param>
        /// <param name="returnURL"></param>
        /// <returns></returns>
        public JsonResult OnPost(string request_parameter, string returnURL = null)
        {
            dynamic login_object = JsonConvert.DeserializeObject(request_parameter);
            string  user_name    = login_object["username"];
            string  password     = login_object["password"];
            //Console.WriteLine("user_name>> " + user_name);
            //Console.WriteLine("password >> " + password);
            AppResponseMessage arm = new AppResponseMessage();

            if (!string.IsNullOrWhiteSpace(user_name) && !string.IsNullOrWhiteSpace(password))
            {
                //jika masukan username & password valid
                if (IsValidLogin(user_name, password))
                {
                    //jika username & password dikenali
                    string user_id          = _context.m_user.Where(f => f.user_name == user_name).FirstOrDefault().m_user_id + "";
                    string Role             = _context.m_user.Include(f => f.m_user_group).Where(f => f.user_name == user_name).FirstOrDefault().m_user_group.user_group_name;
                    string user_category_id = _context.m_user.Where(f => f.user_name == user_name).FirstOrDefault().m_user_group_id + "";

                    bool status_aktif = _context.m_user.Where(f => f.user_name == user_name).FirstOrDefault().user_active;
                    if (status_aktif != true)
                    {
                        //jika user tidak aktif
                        arm.fail();
                        arm.message = "user tidak aktif";
                    }
                    else
                    {
                        //jika user valid & aktif
                        var claims = new[] {
                            new Claim(ClaimTypes.Name, user_name),
                            new Claim(ClaimTypes.Role, Role),

                            new Claim("user_id", user_id),
                            new Claim("user_category_id", user_category_id),
                            new Claim("user_name", user_name),
                        };
                        ClaimsIdentity  identity  = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
                        ClaimsPrincipal principal = new ClaimsPrincipal(identity);

                        AuthenticationHttpContextExtensions.SignInAsync(HttpContext, CookieAuthenticationDefaults.AuthenticationScheme, principal);
                        arm.success();
                        arm.message = "login berhasil";
                    }
                }
                else
                {
                    arm.fail();
                    arm.message = "login gagal";
                }
            }
            else
            {
                arm.fail();
                arm.message = "login gagal";
            }
            return(new JsonResult(arm));
        }
Beispiel #12
0
        public async Task Authenticate(HttpContext httpContext)
        {
            var claims = new List <Claim>
            {
                new Claim(ClaimTypes.Name, Username)
            };

            ClaimsIdentity id = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);

            await AuthenticationHttpContextExtensions.SignInAsync(httpContext, new ClaimsPrincipal(id));
        }
Beispiel #13
0
        public JsonResult OnPost()
        {
            login_db           _context = new login_db(AppGlobal.get_db_option()); //simplifying context initializer by override
            AppResponseMessage arm      = new AppResponseMessage();                //inisialisasi ARM sebagai standarisasi respon balik

            try {
                using (var transaction = _context.Database.BeginTransaction()) {
                    if (Request.Query["f"] == "login_handler")
                    {
                        string email    = Request.Form["email"];
                        string password = Request.Form["password"];
                        var    m_user   = _context.m_user.FirstOrDefault(e => e.email == email && e.password == password);
                        if (m_user == null)
                        {
                            arm.fail();
                            arm.message = "Data Not Exist!!";
                        }
                        else
                        {
                            t_login_history login_history = new t_login_history {
                                m_user_id  = m_user.m_user_id,
                                login_time = DateTime.Now
                            };

                            _context.t_login_history.Add(login_history);
                            _context.SaveChanges();

                            //jika user valid & aktif
                            var claims = new[] {
                                new Claim(ClaimTypes.Email, email),

                                new Claim("m_user_id", m_user.m_user_id.ToString()),
                                new Claim("full_name", m_user.full_name),
                                new Claim("history_id", login_history.t_login_history_id.ToString()),
                            };
                            ClaimsIdentity  identity  = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
                            ClaimsPrincipal principal = new ClaimsPrincipal(identity);

                            AuthenticationHttpContextExtensions.SignInAsync(HttpContext, CookieAuthenticationDefaults.AuthenticationScheme, principal);

                            arm.success();
                            arm.message = "Success";
                        }
                    }
                    transaction.Commit();
                    _context.SaveChanges();
                }
            } catch (Exception ex) {
                arm.fail();
                arm.message = ex.Message;
            }
            return(new JsonResult(arm)); //return ARM dg method JsonResult untuk auto serialize ke format JSON
        }
Beispiel #14
0
        public async Task <IActionResult> EmulateUserAsync(string username)
        {
            List <String>   roles          = new List <string>();
            UserPermission  userPermission = findUserPermissions(username);
            ClaimsPrincipal principal      = new ClaimsPrincipal();

            if (userPermission != null)
            {
                if (userPermission.IsResearcher)
                {
                    roles.Add("User");
                }
                ;
                if (userPermission.IsAdmin)
                {
                    roles.Add("Admin");
                }
            }
            ;


            // Hard coded roles.
            // string[] roles = new[]{ "User", "Admin" };

            // `AddClaim` is not available directly from `context.Principal.Identity`.
            // We can add a new empty identity with the roles we want to the principal.
            var identity = new ClaimsIdentity("Custom");

            foreach (var role in roles)
            {
                identity.AddClaim(new Claim(ClaimTypes.Role, role));
            }

            identity.AddClaim(new Claim(JwtRegisteredClaimNames.UniqueName, username));

            principal.AddIdentity(identity);



            await AuthenticationHttpContextExtensions.SignInAsync(this.HttpContext, "Cookies", principal);



            // CookieOptions option = new CookieOptions();


            //  option.Expires = DateTime.Now.AddMinutes(1000);


            //Response.Cookies.Append(".AspNetCore.CasLogin", principal.ToString(), option);

            return(RedirectToAction("Index"));
        }
Beispiel #15
0
        public async Task <IActionResult> Login(LoginViewModel viewModel, string returnUrl)
        {
            if (!ModelState.IsValid)
            {
                return(View());
            }

            User user = await _userRepository.GetByUserNameAsync(viewModel.Username);

            if (user == null)
            {
                ModelState.AddModelError(nameof(ErrorCode.UsernameNotFound), Resources.UserNameNotFound);
                return(View());
            }

            if (user.Password != _securityService.ComputeHash(viewModel.Password))
            {
                ModelState.AddModelError(nameof(ErrorCode.InvalidPassword), Resources.WrongPassword);
                return(View());
            }

            IEnumerable <Role> userRoles = await _userRepository.GetUserRolesAsync(user.Id.GetValueOrDefault());

            List <Claim> claims = new List <Claim>()
            {
                new Claim(ClaimTypes.Name, user.UserName),
                new Claim(ClaimTypes.NameIdentifier, user.UserName),
                new Claim(ApplicationClaimTypes.UserId, user.Id.ToString()),
            };

            foreach (Role role in userRoles)
            {
                claims.Add(new Claim(ClaimTypes.Role, role.Name));
            }

            ClaimsIdentity  identity  = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
            ClaimsPrincipal principal = new ClaimsPrincipal(identity);

            await AuthenticationHttpContextExtensions.SignInAsync(HttpContext, CookieAuthenticationDefaults.AuthenticationScheme, principal, new AuthenticationProperties()
            {
                IsPersistent = false, ExpiresUtc = DateTime.Now.AddMinutes(30).ToUniversalTime()
            });

            if (Url.IsLocalUrl(returnUrl))
            {
                return(Redirect(returnUrl));
            }

            return(Redirect("/"));
        }
Beispiel #16
0
        private async Task RefreshTokensAync()
        {
            var authorizatinServerInformation =
                await DiscoveryClient.GetAsync("http://localhost:26421");

            var client = new TokenClient(authorizatinServerInformation.TokenEndpoint,
                                         "socialnetwork_code", "secret");

            var refreshToken = await AuthenticationHttpContextExtensions.GetTokenAsync(this.HttpContext, "refresh_token");

            var tokenResponse = await client.RequestRefreshTokenAsync(refreshToken);

            var identityToken = await AuthenticationHttpContextExtensions.GetTokenAsync(this.HttpContext, "id_token");

            var expiresAt = DateTime.UtcNow + TimeSpan.FromSeconds(tokenResponse.ExpiresIn);

            var tokens = new[] {
                new AuthenticationToken
                {
                    Name  = OpenIdConnectParameterNames.IdToken,
                    Value = tokenResponse.IdentityToken
                },
                new AuthenticationToken
                {
                    Name  = OpenIdConnectParameterNames.AccessToken,
                    Value = tokenResponse.AccessToken
                },
                new AuthenticationToken
                {
                    Name  = OpenIdConnectParameterNames.RefreshToken,
                    Value = tokenResponse.RefreshToken
                },
                new AuthenticationToken
                {
                    Name  = "expires_at",
                    Value = expiresAt.ToString("o", CultureInfo.InvariantCulture)
                }
            };

            //var authenticationInformation =HttpContext.Authentication.GetAuthenticateInfoAsync(CookieAuthenticationDefaults.AuthenticationScheme);
            var authenticationInformation = await AuthenticationHttpContextExtensions.AuthenticateAsync(this.HttpContext, CookieAuthenticationDefaults.AuthenticationScheme);

            authenticationInformation.Properties.StoreTokens(tokens);

            await AuthenticationHttpContextExtensions.SignInAsync(this.HttpContext,
                                                                  CookieAuthenticationDefaults.AuthenticationScheme,
                                                                  authenticationInformation.Principal,
                                                                  authenticationInformation.Properties);
        }
Beispiel #17
0
        public async Task <IActionResult> Login(AdminLoginViewModel model)
        {
            if (this.ModelState.IsValid)
            {
                try
                {
                    Result <PanelUserDTO> result = await _panelUserService.GetUserAsync(model.Email, model.Password);

                    if (!result.IsSuccess)
                    {
                        model.FormMessage = "E-Posta ya da Şifre bilgisi yanlış, lütfen bilgilerinizi kontrol edin.";
                        return(this.View((object)model));
                    }
                    PanelUserDTO data   = result.Data;
                    List <Claim> claims = new List <Claim>
                    {
                        new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier", data.Id.ToString()),
                        new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name", data.Name),
                        new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress", data.Email),
                        new Claim("CompanyId", data.CompanyId.ToString()),
                        new Claim("PlaceId", data.PlaceId.ToString()),
                        new Claim("CompanyName", data.Company.Name),
                        new Claim("http://schemas.microsoft.com/ws/2008/06/identity/claims/role", data.Role.ToString())
                    };
                    ClaimsPrincipal claimsPrincipal = new ClaimsPrincipal(new ClaimsIdentity(claims, "ClaimIdentity"));
                    var             task            = AuthenticationHttpContextExtensions.SignInAsync(this.HttpContext, "AdminAreaCookies", claimsPrincipal);
                    task.Wait();
                    if (task.IsCompletedSuccessfully)
                    {
                        var temp = this.User.Claims;
                    }
                    else
                    {
                    }
                    return(this.RedirectToAction("Index", "Manage"));
                }
                catch (Exception ex)
                {
                    LoggerExtensions.LogError(_logger, ex, "Panel Login Error", Array.Empty <object>());
                    model.FormMessage = "İşleminiz gerçekleştirilemedi.";
                    return(this.View((object)model));
                }
            }
            return(this.View((object)model));
        }
Beispiel #18
0
        private async Task <AuthStatusResult> AuthenticateUser(AuthModel model)
        {
            var user = await _db.Users.SingleOrDefaultAsync(x => x.Phone == model.UserString || x.Email == model.UserString);

            //If user write email/phone that doesnt exist in db
            if (user == null)
            {
                _authResult.IncorrectData = true;
                _authResult.isSuccessful  = false;

                return(_authResult);
            }

            var enteredPassword = _cryProvider.GetPasswordHash(model.Password, user.LocalHash);

            //If password is incorrect
            if (!user.PasswordHash.SequenceEqual(enteredPassword))
            {
                _authResult.IncorrectPassword = true;
                _authResult.isSuccessful      = false;

                return(_authResult);
            }

            //all credentials are true
            List <Claim> userClaims = await VerifyUserAsync(user);

            if (userClaims == null)
            {
                _authResult.IncorrectData = true;
                _authResult.isSuccessful  = false;

                return(_authResult);
            }

            var u_id            = new ClaimsIdentity(userClaims, "ApplicationCookie");
            var claimsPrincipal = new ClaimsPrincipal(u_id);

            await AuthenticationHttpContextExtensions.SignInAsync(_contextAcessor.HttpContext, claimsPrincipal);

            _logger.LogInformation($"User email: {user.Email} has been authenticated");

            return(_authResult);
        }
Beispiel #19
0
        public async Task <IActionResult> SignIn(LoginViewModel model)
        {
            if (this.ModelState.IsValid)
            {
                try
                {
                    Result <UserDTO> result = await _userService.GetUserAsync(model.Email, model.Password);

                    if (!result.IsSuccess)
                    {
                        model.FormMessage = result.FormMessage;
                        return(this.View((object)model));
                    }
                    UserDTO      data   = result.Data;
                    List <Claim> claims = new List <Claim>
                    {
                        new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier", data.Id.ToString()),
                        new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name", data.Name),
                        new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress", data.Email),
                        new Claim("http://schemas.microsoft.com/ws/2008/06/identity/claims/role", "Member")
                    };
                    ClaimsPrincipal          claimsPrincipal = new ClaimsPrincipal(new ClaimsIdentity(claims, "ClaimIdentity"));
                    AuthenticationProperties val             = new AuthenticationProperties();
                    val.IsPersistent = (true);
                    val.ExpiresUtc   = ((DateTimeOffset?)(model.IsRemember ? DateTimeOffset.UtcNow.AddDays(7.0) : DateTimeOffset.UtcNow.AddHours(2.0)));
                    AuthenticationProperties val2 = val;
                    await AuthenticationHttpContextExtensions.SignInAsync(this.HttpContext, "Cookies", claimsPrincipal, val2);

                    if (this.Url.IsLocalUrl(model.ReturnUrl))
                    {
                        return(this.Redirect(model.ReturnUrl));
                    }
                    return(this.RedirectToAction("Index", "Home"));
                }
                catch (Exception ex)
                {
                    LoggerExtensions.LogError(_logger, ex, "SignIn Post Error", Array.Empty <object>());
                    model.FormMessage = "İşleminiz gerçekleştirilemedi.";
                    return(this.View((object)model));
                }
            }
            return(this.View((object)model));
        }
Beispiel #20
0
        private async Task CreateCookie(string username)
        {
            var claims = new List <Claim>
            {
                new Claim(ClaimTypes.NameIdentifier, GetUserIDByUserName(username).ToString())
            };

            var claimsIdentity = new ClaimsIdentity(
                claims, CookieAuthenticationDefaults.AuthenticationScheme);

            var authProperties = new AuthenticationProperties
            {
            };

            await AuthenticationHttpContextExtensions.SignInAsync(
                _httpContextAccessor.HttpContext, CookieAuthenticationDefaults.AuthenticationScheme,
                new ClaimsPrincipal(claimsIdentity),
                authProperties);
        }
Beispiel #21
0
        public async Task <IActionResult> Login(LoginUserDto user)
        {
            // to get all users do: context.Users
            // var d = context.Users.Find(1);
            // for debugging purposes: show list of users
            // var d = Context.Users.ToList();

            // fetch user from database
            var fetchedUser = Context.Users.Where(x => x.Email == user.Email).FirstOrDefault();

            // check whether user exists
            var userExists = fetchedUser != null;

            if (userExists)
            {
                var claims = new List <Claim>()
                {
                    new Claim(ClaimTypes.Name, fetchedUser.Username),
                    new Claim(ClaimTypes.Email, fetchedUser.Email),
                    new Claim(ClaimTypes.Role, "User")
                };

                var userPrincipal = new ClaimsPrincipal(new ClaimsIdentity(claims, "SuperSecureLogin"));
                await AuthenticationHttpContextExtensions.SignInAsync(HttpContext,
                                                                      CookieAuthenticationDefaults.AuthenticationScheme,
                                                                      userPrincipal,
                                                                      new AuthenticationProperties
                {
                    ExpiresUtc   = DateTime.UtcNow.AddMinutes(30),
                    IsPersistent = false,
                    AllowRefresh = false
                });

                return(RedirectToAction("Index", "Home"));
            }
            else
            {
                ViewBag.ErrMsg = "UserName or Password is invalid! Please try again.";

                return(View());
            }
        }
Beispiel #22
0
        public async Task <IActionResult> Login(LoginViewModel model, string returnUrl = null)
        {
            ViewData["ReturnUrl"] = returnUrl;
            if (ModelState.IsValid)
            {
                UserSessionApiHelper sessionApiHelper = new UserSessionApiHelper();

                var sessionResponse = await sessionApiHelper.Login(model.Email, model.Password);

                if (sessionResponse != null)
                {
                    var claims = new List <Claim>
                    {
                        new Claim(ClaimTypes.Name, sessionResponse.UserDetails.Name),
                        new Claim(ClaimTypes.Role, sessionResponse.UserDetails.UserTypeId.ToString()),
                        new Claim(ClaimTypes.NameIdentifier, sessionResponse.UserDetails.Username),
                        new Claim(ClaimTypes.Email, sessionResponse.UserDetails.Email),

                        new Claim("HasRestaurantConfigured", sessionResponse.UserDetails.HasRestaurantConfigured.HasValue ? sessionResponse.UserDetails.HasRestaurantConfigured.Value.ToString() : string.Empty),
                        new Claim("SessionKey", sessionResponse.SessionKey),
                    };
                    var props = new AuthenticationProperties
                    {
                        IsPersistent = false,
                        ExpiresUtc   = DateTime.UtcNow.AddMinutes(30)
                    };

                    var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
                    await AuthenticationHttpContextExtensions.SignInAsync(HttpContext, new ClaimsPrincipal(identity), props);

                    return(RedirectToLocal(returnUrl));
                }
                else
                {
                    ModelState.AddModelError(string.Empty, "Invalid login attempt.");
                    return(View(model));
                }
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
        public async Task <IActionResult> RegisterUser(RegisterUserViewModel model)
        {
            if (ModelState.IsValid)
            {
                // create user + claims
                var userToCreate = new Entities.User();
                userToCreate.Password = model.Password;
                userToCreate.Username = model.Username;
                userToCreate.IsActive = true;
                userToCreate.Claims.Add(new Entities.UserClaim("country", model.Country));
                userToCreate.Claims.Add(new Entities.UserClaim("address", model.Address));
                userToCreate.Claims.Add(new Entities.UserClaim("given_name", model.Firstname));
                userToCreate.Claims.Add(new Entities.UserClaim("family_name", model.Lastname));
                userToCreate.Claims.Add(new Entities.UserClaim("email", model.Email));
                userToCreate.Claims.Add(new Entities.UserClaim("subscriptionlevel", "FreeUser"));

                // add it through the repository
                marvinUserRepository.AddUser(userToCreate);

                if (!marvinUserRepository.Save())
                {
                    throw new Exception($"Creating a user failed.");
                }

                // log the user in
                //await HttpContext.Authentication.SignInAsync(userToCreate.SubjectId, userToCreate.Username);
                await AuthenticationHttpContextExtensions.SignInAsync(HttpContext, User);

                // continue with the flow
                if (interactionService.IsValidReturnUrl(model.ReturnUrl) || Url.IsLocalUrl(model.ReturnUrl))
                {
                    return(Redirect(model.ReturnUrl));
                }

                return(Redirect("~/"));
            }

            // ModelState invalid, return the view with the passed-in model
            // so changes can be made
            return(View(model));
        }
Beispiel #24
0
        public async Task <IActionResult> Login(AuthenticateUserCommand command)
        {
            if (!ModelState.IsValid)
            {
                return(View(command));
            }

            var response = await this.Mediator.Send(command);

            if (response.IsFailure)
            {
                ModelState.AddModelErrors(response.Errors);
                command.Password        = string.Empty;
                command.ConfirmPassword = string.Empty;

                return(View(command));
            }
            var user   = response.Result;
            var role   = user.RoleName;
            var claims = new List <Claim>()
            {
                new Claim(ClaimTypes.Sid, user.Id),
                new Claim(ClaimTypes.Role, (role != null ? role : "Guest")),
                new Claim(ClaimTypes.Name, user.UserName)
            };

            await AuthenticationHttpContextExtensions.SignInAsync(HttpContext, IdentityConstants.ApplicationScheme, new ClaimsPrincipal(
                                                                      new ClaimsIdentity(claims, IdentityConstants.ApplicationScheme)),
                                                                  new AuthenticationProperties {
                IsPersistent = command.RememberMe
            });

            if (!string.IsNullOrEmpty(command.ReturnUrl))
            {
                return(Redirect(command.ReturnUrl));
            }

            return(RedirectToAction("Index", "Home"));
        }
Beispiel #25
0
        public async Task <IActionResult> LoginWithRole(string name, string role)
        {
            //validate name not empty and role is Basic or Admin
            if (string.IsNullOrEmpty(name) && (role != "Basic" || role != "Admin"))
            {
                RedirectToAction(nameof(Index));
            }

            //Add role to User with no duplicates
            if (!User.IsInRole(role))
            {
                //Add role claim to the existing user
                var claims = new List <Claim> {
                    new Claim(ClaimTypes.Role, role)
                };
                var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
                var user     = HttpContext.User;
                user.AddIdentity(identity);
                var principal = user;

                //SignIn
                await AuthenticationHttpContextExtensions.SignInAsync(HttpContext, CookieAuthenticationDefaults.AuthenticationScheme, principal);
            }

            var redirect = string.Empty;

            if (role == "Admin")
            {
                redirect = "AuthenticateAndAuthorizeWithRole";
            }
            else
            {
                redirect = "AuthenticateAndAuthorize";
            }

            return(RedirectToAction(redirect));
        }
        public async Task <IActionResult> CookiesLogin(string returnUrl = null)
        {
            const string Issuer = "https://gov.uk";

            var claims = new List <Claim> {
                new Claim(ClaimTypes.Name, "Billy", ClaimValueTypes.String, Issuer),
                new Claim(ClaimTypes.Surname, "Bunter", ClaimValueTypes.String, Issuer),
                new Claim(ClaimTypes.Country, "UK", ClaimValueTypes.String, Issuer),
                new Claim("Hero", "Danger Mouse", ClaimValueTypes.String)
            };

            var userIdentity  = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
            var userPrincipal = new ClaimsPrincipal(userIdentity);

            await AuthenticationHttpContextExtensions.SignInAsync(HttpContext, userPrincipal,
                                                                  new AuthenticationProperties
            {
                ExpiresUtc   = DateTime.UtcNow.AddMinutes(20),
                IsPersistent = false,
                AllowRefresh = false
            });

            return(View());
        }
Beispiel #27
0
        public async Task SignInAsync(RentUser user)
        {
            var isAdmin = await _unitOfWork.Users.IsAdministrator(user);

            var claims = new List <Claim>
            {
                new Claim(ClaimTypes.Sid, user.UserId.ToString()),
                new Claim(ClaimTypes.Name, user.FirstName + ' ' + user.LastName),
                new Claim(ClaimTypes.GivenName, user.FirstName),
                new Claim(ClaimTypes.Surname, user.LastName),
                new Claim("OfficeID", user.OfficeId.ToString())
            };

            if (isAdmin)
            {
                claims.Add(new Claim("Admin", "true"));
            }

            var identity  = new ClaimsIdentity(claims, "local", "name", "role");
            var principal = new ClaimsPrincipal(identity);
            await AuthenticationHttpContextExtensions.SignInAsync(_httpContextAccessor.HttpContext, principal);

            // await _httpContextAccessor.HttpContext.Authentication.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal);
        }
Beispiel #28
0
        public async Task <IActionResult> ExternalLoginCallback(string returnUrl = null, string remoteError = null)
        {
            AuthenticateResult result = await AuthenticationHttpContextExtensions.AuthenticateAsync(this.HttpContext, "Cookies");

            LoginViewModel signInModel = new LoginViewModel
            {
                ReturnUrl   = returnUrl,
                FormMessage = "İşleminiz gerçekleştirilirken sorun oluştu."
            };
            AuthenticateResult obj = result;

            if (obj == null || !obj.Succeeded)
            {
                return(this.View("SignIn", (object)signInModel));
            }
            ClaimsPrincipal principal = result.Principal;

            if (principal == null)
            {
                return(this.View("SignIn", (object)signInModel));
            }
            List <Claim> source = principal.Claims.ToList();
            Claim        claim  = source.FirstOrDefault((Claim x) => x.Type == "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier");

            if (claim == null)
            {
                signInModel.FormMessage = "Kullanıcı bilgilerinize erişelemedi. Yetkilim uygulamasına erişim verdiğinize emin olup tekrar deneyin.";
                return(this.View("SignIn", (object)signInModel));
            }
            string externalProvider = claim.Issuer;
            Claim  emailClaim       = null;

            if (externalProvider == "Facebook")
            {
                emailClaim = source.FirstOrDefault((Claim x) => x.Type == "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress");
                if (emailClaim == null)
                {
                    signInModel.FormMessage = "E-Posta bilgilerinize erişelemedi. Yetkilim uygulamasının e-posta adresinize erişimine izin verdiğinize emin olup tekrar deneyin.";
                    return(this.View("SignIn", (object)signInModel));
                }
            }
            Claim  nameClaim      = source.FirstOrDefault((Claim x) => x.Type == "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name");
            string externalUserId = claim.Value;

            try
            {
                Result <UserDTO> result2 = await _userService.GetExternalUserAsync(externalProvider, externalUserId);

                int ıd;
                if (!result2.IsSuccess)
                {
                    if (!(result2.ResultCode == "NOT_REGISTERED"))
                    {
                        signInModel.FormMessage = result2.FormMessage;
                        return(this.View("SignIn", (object)signInModel));
                    }
                    UserDTO model = new UserDTO
                    {
                        Name  = nameClaim?.Value,
                        Email = emailClaim?.Value
                    };
                    Result <UserDTO> result3 = await _userService.AddExternalUserAsync(externalProvider, externalUserId, model);

                    if (!result3.IsSuccess)
                    {
                        signInModel.FormMessage = result3.FormMessage;
                        return(this.View("SignIn", (object)signInModel));
                    }
                    ıd = result3.Data.Id;
                }
                else
                {
                    ıd = result2.Data.Id;
                }
                List <Claim> claims = new List <Claim>
                {
                    new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier", ıd.ToString()),
                    nameClaim,
                    new Claim("http://schemas.microsoft.com/ws/2008/06/identity/claims/role", "Member")
                };
                ClaimsPrincipal claimsPrincipal = new ClaimsPrincipal(result.Ticket.Principal.Identity);
                claimsPrincipal.AddIdentity(new ClaimsIdentity(claims, "ClaimIdentity"));
                AuthenticationProperties val = new AuthenticationProperties();
                val.IsPersistent = (true);
                await AuthenticationHttpContextExtensions.SignInAsync(this.HttpContext, "Cookies", claimsPrincipal, val);
            }
            catch (Exception ex)
            {
                LoggerExtensions.LogError(_logger, ex, "Facebook Post Error", Array.Empty <object>());
                return(this.View("SignIn", (object)signInModel));
            }
            return(this.LocalRedirect(returnUrl ?? "/"));
        }
Beispiel #29
0
        public async Task <IActionResult> Login(LoginViewModel viewModel, string returnUrl)
        {
            ViewData["ReturnUrl"] = returnUrl;
            if (ModelState.IsValid)
            {
                var user = await _service.GetUserAsync(viewModel.Account, viewModel.Password, _context);

                if (user != null)
                {
                    if (user.Password.Trim() != MD5Utility.Sign(viewModel.Password, user.Salt))
                    {
                        ViewBag.ErrorInfo = "用户名或密码错误";
                        return(View());
                    }

                    _logger.LogInformation("用户:{0}于{1}登录系统", viewModel.Account, DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss"));

                    string role = GetRole(user);

                    //根据用户角色创建claim声明
                    List <Claim> claim = new List <Claim>
                    {
                        new Claim(ClaimTypes.Role, role)
                    };

                    var userIdentity = new ClaimsIdentity(role);
                    userIdentity.AddClaims(claim);

                    var userPrincipal = new ClaimsPrincipal(userIdentity);

                    await AuthenticationHttpContextExtensions.SignInAsync(HttpContext, userPrincipal, new AuthenticationProperties
                    {
                        ExpiresUtc   = DateTime.UtcNow.AddMinutes(20),
                        IsPersistent = false,
                        AllowRefresh = false
                    });

                    //设置当前用户信息
                    await _service.SetCurrentUser(user.IdentityUserOID, _httpContextAccessor, _context);

                    if (!string.IsNullOrEmpty(returnUrl))
                    {
                        return(RedirectToLocal(returnUrl));
                    }

                    return(RedirectToRoute(new
                    {
                        area = user.HomePage,
                        controller = "Home",
                        action = "Index"
                    }));
                }
                else
                {
                    ViewBag.ErrorInfo = "当前用户不存在";
                    return(View());
                }
            }

            //返回模型验证错误信息
            ViewBag.ErrorInfo = this.ModelState.Keys.SelectMany(key => this.ModelState[key].Errors).FirstOrDefault().ErrorMessage;
            return(View(viewModel));
        }
Beispiel #30
0
        public async Task <ActionResult> OAuth2AuthorizationCodeGrantClient(string code, string state)
        {
            try
            {
                string response = "";

                if (state == this.State) // CSRF(XSRF)対策のstateの検証は重要
                {
                    response = await OAuth2AndOIDCClient.GetAccessTokenByCodeAsync(
                        new Uri("https://localhost:44300/MultiPurposeAuthSite/token"),
                        OAuth2AndOIDCParams.ClientID, OAuth2AndOIDCParams.ClientSecret,
                        HttpUtility.HtmlEncode("http://localhost:58496/Home/OAuth2AuthorizationCodeGrantClient"), code);

                    // 汎用認証サイトはOIDCをサポートしたのでid_tokenを取得し、検証可能。
                    //Base64UrlTextEncoder base64UrlEncoder = new Base64UrlTextEncoder();
                    Dictionary <string, string> dic = JsonConvert.DeserializeObject <Dictionary <string, string> >(response);

                    // id_tokenの検証コード
                    if (dic.ContainsKey("id_token"))
                    {
                        string  sub   = "";
                        string  nonce = "";
                        JObject jobj  = null;

                        if (IdToken.Verify(dic["id_token"], dic["access_token"],
                                           code, state, out sub, out nonce, out jobj) && nonce == this.Nonce)
                        {
                            // ログインに成功

                            // /userinfoエンドポイントにアクセスする場合
                            response = await OAuth2AndOIDCClient.GetUserInfoAsync(
                                new Uri("https://localhost:44300/MultiPurposeAuthSite/userinfo"), dic["access_token"]);

                            // 認証情報を作成する。
                            List <Claim> claims = new List <Claim>();
                            claims.Add(new Claim(ClaimTypes.Name, sub));

                            // 認証情報を保存する。
                            ClaimsIdentity  userIdentity  = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
                            ClaimsPrincipal userPrincipal = new ClaimsPrincipal(userIdentity);

                            // サイン アップする。
                            await AuthenticationHttpContextExtensions.SignInAsync(
                                this.HttpContext, CookieAuthenticationDefaults.AuthenticationScheme, userPrincipal);

                            // 認証情報を保存する。
                            MyUserInfo ui = new MyUserInfo(sub, (new GetClientIpAddress()).GetAddress());
                            UserInfoHandle.SetUserInformation(ui);

                            return(this.Redirect(Url.Action("Index", "Home")));
                        }
                    }
                    else
                    {
                    }
                }
                else
                {
                }

                // ログインに失敗
                return(RedirectToAction("Login"));
            }
            finally
            {
                this.ClearExLoginsParams();
            }
        }