public object Login([FromBody] LoginAuthModel model,
                            [FromServices] SigningConfigurations signingConfigurations, //Vem da configuração Startup
                            [FromServices] TokenConfigurations tokenConfigurations      //Vem da configuração Startup
                            )
        {
            var user = _mapper.Map <User>(model);


            try
            {
                using (var loginService = new LoginFactory(_serviceOptions).Build())
                {
                    var loggedUSer = loginService.EfetuarLogin(user);

                    var identity = new ClaimsIdentity(new GenericIdentity(user.Login, "Login"), new[]
                    {
                        new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString("N")),
                        new Claim(JwtRegisteredClaimNames.UniqueName, user.Login)
                    });

                    DateTime dataCriacao   = DateTime.Now;
                    DateTime dataExpiracao = dataCriacao +
                                             TimeSpan.FromSeconds(tokenConfigurations.Seconds);

                    var handler       = new JwtSecurityTokenHandler();
                    var securityToken = handler.CreateToken(new SecurityTokenDescriptor
                    {
                        Issuer             = tokenConfigurations.Issuer,
                        Audience           = tokenConfigurations.Audience,
                        SigningCredentials = signingConfigurations.SigningCredentials,
                        Subject            = identity,
                        NotBefore          = dataCriacao,
                        Expires            = dataExpiracao
                    });
                    var token = handler.WriteToken(securityToken);



                    return(new
                    {
                        authenticated = true,
                        idLoggedUser = loggedUSer.Id,
                        created = dataCriacao.ToString("yyyy-MM-dd HH:mm:ss"),
                        expiration = dataExpiracao.ToString("yyyy-MM-dd HH:mm:ss"),
                        accessToken = token,
                        message = "OK"
                    });
                }
            }
            catch (Exception ex)
            {
                return(new
                {
                    authenticated = false,
                    message = $"Falha ao autenticar:\n{ex.Message}"
                });
            }
        }
Beispiel #2
0
        public void ConfigureServices(IServiceCollection services, IConfiguration configuration, IHostEnvironment env, CalamusOptions calamusOptions, ITypeFinder typeFinder)
        {
            services.AddIdentityUser <int, LoginAuthModel>((user, principal) =>
            {
                if (!principal.Identity.IsAuthenticated)
                {
                    return;                                         // 未授权返回
                }
                string sub           = principal.FindFirstValue(JwtRegisteredClaimNames.Sub);
                LoginAuthModel model = System.Text.Json.JsonSerializer.Deserialize <LoginAuthModel>(sub);
                user.Name            = model.NickName;
                user.Account         = model.Account;
                user.Avatar          = model.Avatar;
                user.Id = Convert.ToInt32(principal.FindFirstValue("id"));
            });

            // Services
            var types      = typeFinder.FindClassesOfType <IDependency>(false);
            var interfaces = types.Where(t => t.IsInterface && t != typeof(IDependency)).ToList();
            var impements  = types.Where(t => !t.IsAbstract).ToList();
            var didatas    = interfaces
                             .Select(t =>
            {
                return(new
                {
                    serviceType = t,
                    implementationType = impements.FirstOrDefault(c => t.IsAssignableFrom(c))
                });
            }
                                     ).ToList();

            didatas.ForEach(t =>
            {
                if (t.implementationType != null)
                {
                    services.AddScoped(t.serviceType, t.implementationType);
                }
            });

            // AutoMapper
            services.AddAutoMapper(typeof(AutomapperProfiler).Assembly);

            // MiniProfiler
            if (env.IsDevelopment())
            {
                services.AddMiniProfiler(options =>
                {
                    options.SqlFormatter = new SqlServerFormatter()
                    {
                        IncludeParameterValues = true
                    };
                    options.RouteBasePath = "/profiler";
                }).AddEntityFramework();
            }

            services.AddMemoryCache();
            services.AddDistributedMemoryCache();
        }
Beispiel #3
0
        public async Task <AccessTokenAuthModel> Authenticate(LoginAuthModel model)
        {
            var client   = _proxyHttpClient.Get(ProxyHttpClient.AuthAPI);
            var response = await client.PostAsJsonAsync("auth/login", model);

            response.EnsureSuccessStatusCode();

            return(await response.Content.ReadAsAsync <AccessTokenAuthModel>());
        }
Beispiel #4
0
        public LoginAuthModel Login(AccountLoginRequestDTO request)
        {
            string pwd = Md5Helper.Encrypt(request.Password);
            var    q1  = from t1 in _snsdbContext.Accounts
                         where t1.Account1 == request.Account && t1.Pwd == pwd
                         select new LoginAuthModel
            {
                Id         = t1.Id,
                Account    = t1.Account1,
                NickName   = t1.NickName,
                Avatar     = t1.Avatar,
                Intro      = t1.Intro,
                CreateTime = t1.CreateTime
            };
            LoginAuthModel model = q1.FirstOrDefault();

            return(model);
        }
Beispiel #5
0
        async Task SignIn(LoginAuthModel account)
        {
            // 写入cookie
            DateTime       now            = DateTime.Now;
            ClaimsIdentity claimsIdentity = new ClaimsIdentity(new Claim[]
            {
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                new Claim(JwtRegisteredClaimNames.Nbf, now.ToTimestamp().ToString()),
                new Claim(JwtRegisteredClaimNames.Iat, now.ToTimestamp().ToString()),
                new Claim(JwtRegisteredClaimNames.Exp, now.AddDays(30).ToTimestamp().ToString()),
                new Claim("id", account.Id.ToString()),
                new Claim(JwtRegisteredClaimNames.Sub, System.Text.Json.JsonSerializer.Serialize(account))
            }, CookieAuthenticationDefaults.AuthenticationScheme);

            ClaimsPrincipal claimsPrincipal = new ClaimsPrincipal(claimsIdentity);
            await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, claimsPrincipal, new AuthenticationProperties
            {
                IsPersistent = true,
                AllowRefresh = true,
                ExpiresUtc   = DateTime.Now.AddDays(30) // 有效期30天
            });
        }
Beispiel #6
0
        /// <summary>
        /// 登录授权
        /// </summary>
        /// <param name="username">用户名</param>
        /// <param name="password">密码</param>
        /// <param name="captcha">验证码</param>
        /// <param name="remember">是否记住密码</param>
        /// <returns></returns>
        public static string LoginAuth(string username, string password, string captcha, bool remember = false)
        {
            LoginAuthModel mo = new LoginAuthModel();

            try
            {
                if (System.Web.HttpContext.Current.Session["captcha"] == null || System.Web.HttpContext.Current.Session["captcha"].ToString().ToLower() != captcha.ToLower())
                {
                    mo.code = 102;
                    mo.msg  = "验证码过期或错误";
                }
                else
                {
                    string            sql   = "select * from view_sys_user where u_name=@u_name and u_pwd=@u_pwd";
                    SQLiteParameter[] parma =
                    {
                        new SQLiteParameter("@u_name", DbType.String, 40),
                        new SQLiteParameter("@u_pwd",  DbType.String, 40)
                    };
                    parma[0].Value = username;
                    parma[1].Value = DB.CalcTo.MD5(password);

                    DataTable dt = DB.HelperSQLite.Query(sql, parma).Tables[0];
                    if (dt.Rows.Count == 0)
                    {
                        mo.code = 103;
                        mo.msg  = "账号或密码错误";
                    }
                    else
                    {
                        DataRow dr = dt.Rows[0];

                        if (dr["u_state"].ToString() != "1")
                        {
                            mo.code = 104;
                            mo.msg  = "账号已被禁用";
                        }
                        else
                        {
                            HttpCookie hc1 = new HttpCookie("__U_id");
                            HttpCookie hc2 = new HttpCookie("__U_name");
                            HttpCookie hc3 = new HttpCookie("__U_nickname");
                            HttpCookie hc4 = new HttpCookie("__U_roleid");
                            HttpCookie hc5 = new HttpCookie("__U_photo");

                            hc1.Value = DB.CalcTo.EnHash(dr["id"].ToString());
                            hc2.Value = DB.CalcTo.EnHash(dr["u_name"].ToString());
                            hc3.Value = DB.CalcTo.EnHash(dr["u_nickname"].ToString());
                            hc4.Value = DB.CalcTo.EnHash(dr["u_roleid"].ToString());
                            hc5.Value = DB.CalcTo.EnHash(dr["u_photo"].ToString());

                            if (remember)
                            {
                                hc1.Expires = hc2.Expires = hc3.Expires = hc4.Expires = hc5.Expires = DateTime.Now.AddDays(5);
                            }

                            System.Web.HttpContext.Current.Response.Cookies.Add(hc1);
                            System.Web.HttpContext.Current.Response.Cookies.Add(hc2);
                            System.Web.HttpContext.Current.Response.Cookies.Add(hc3);
                            System.Web.HttpContext.Current.Response.Cookies.Add(hc4);
                            System.Web.HttpContext.Current.Response.Cookies.Add(hc5);

                            mo.code = 100;
                            mo.msg  = "登录成功";
                            mo.url  = "/";

                            //角色权限菜单、按钮缓存
                            DB.CatchTo.Set("role" + dr["u_roleid"].ToString(), dr);

                            //登录票据
                            System.Web.Security.FormsAuthentication.SetAuthCookie(dr["id"].ToString(), remember);
                        }
                    }
                }
            }
            catch (Exception)
            {
                mo.code = 101;
                mo.msg  = "处理登录授权异常";
            }

            return(mo.ToJson());
        }