private static Session CreateSession(string email, string handle, string displayName, string bio)
        {
            var authTokenContainerModel = new JWTContainerModel(SessionSecretKey, SecurityAlgorithms.HmacSha256Signature, 1440, new Claim[]
            {
                new Claim(ClaimTypes.Email, email),
                new Claim("TokenType", JWTTokenTypes.Auth)
            });

            var refreshTokenContainerModel = new JWTContainerModel(SessionSecretKey, SecurityAlgorithms.HmacSha256Signature, 44640, new Claim[]
            {
                new Claim(ClaimTypes.Email, email),
                new Claim("TokenType", JWTTokenTypes.Refresh)
            });

            var jwtService = new JWTService(SessionSecretKey);

            var authTokenExpireTime    = new DateTimeOffset(DateTime.UtcNow.AddMinutes(Convert.ToInt32(authTokenContainerModel.ExpireMinutes))).ToUnixTimeSeconds();
            var refreshTokenExpireTime = new DateTimeOffset(DateTime.UtcNow.AddMinutes(Convert.ToInt32(refreshTokenContainerModel.ExpireMinutes))).ToUnixTimeSeconds();

            var authToken    = new SessionToken(authTokenExpireTime, jwtService.GenerateToken(authTokenContainerModel));
            var refreshToken = new SessionToken(refreshTokenExpireTime, jwtService.GenerateToken(refreshTokenContainerModel));

            return(new Session(email, handle, displayName, bio, authToken, refreshToken));
        }
コード例 #2
0
ファイル: GuildController.cs プロジェクト: Dymus/gms
        public ActionResult <Event> Post([FromBody] Event e)
        {
            IAuthService authService = new JWTService(clientSettings.Value.SecretKey);
            string       token       = HttpContext.Request.Headers["Authorization"];

            try
            {
                if (!authService.IsTokenValid(token))
                {
                    return(BadRequest("Unauthorized Access"));
                }
                else
                {
                    if (eventProcessor.InsertEvent(e.Name, e.EventType, e.Location, e.Date, e.Description, e.MaxNumberOfCharacters, e.GuildID))
                    {
                        return(e);
                    }
                    return(BadRequest("Invalid data"));
                }
            } catch
            {
                return(BadRequest("Unauthorized Access"));
            }
        }
コード例 #3
0
ファイル: JWTAppServicec.cs プロジェクト: LeadnCode/M.Host
        public async Task <GetTokenResultDto> GetToken(string adminName, string adminPwd)
        {
            string jwtStr = string.Empty;

            // 判断是否为空
            if (string.IsNullOrEmpty(adminName) || string.IsNullOrEmpty(adminPwd))
            {
                // 账号或密码不能为空
                throw new Exception("Account or password cannot be empty.");
            }

            var result = await HttpRequestService.HttpGetAsync(AppConfigurtaionService.Configuration["ProjectInfo:ApiUrl"]
                                                               + string.Format("/api/Admin/IsExistFromToken?adminName={0}&adminPwd={1}", adminName, adminPwd));

            //StringBuilder resultStringBuilder = new StringBuilder();

            // 去除转义字符
            //foreach (char c in result.ToString())
            //{
            //    if (c != '\\') resultStringBuilder.Append(c);
            //}
            // 返回字符串转换为JSON对象
            var admin = JsonConvert.DeserializeObject <Model.Entity.Admin>(result);

            TokenJWT tokenModel = new TokenJWT();

            tokenModel.Id        = admin.Id;
            tokenModel.AdminName = admin.AdminName;

            jwtStr = JWTService.IssueJWT(tokenModel);

            return(new GetTokenResultDto()
            {
                JWT = "Bearer " + jwtStr,
            });
        }
コード例 #4
0
        public async Task Invoke(HttpContext context, JWTService jWTService)
        {
            string authHeader = context.Request.Headers[Key.AuthHeaderKey];

            if (authHeader != null)
            {
                authHeader = authHeader.Replace(Key.JWTPrefixKey, "").Trim();
                UserCache user = jWTService.GetUserCache(authHeader);
                if (user == null)
                {
                    context.Response.StatusCode = 401;
                    return;
                }
                ClaimsIdentity aa     = new ClaimsIdentity();
                var            claims = new[] {
                    new Claim("Id", user.Id.ToString()),
                    new Claim("Email", user.Email),
                    new Claim("IsAdmin", user.IsAdmin.ToString())
                };
                var identity = new ClaimsIdentity(claims, "basic");
                context.User = new ClaimsPrincipal(identity);
            }
            await next(context);
        }
コード例 #5
0
        public AuthenticationQuery(JWTService jwtservice, IRepository <Account> repository)
        {
            FieldAsync <StringGraphType>(
                "facebook",
                arguments: new QueryArguments(
                    new QueryArgument <NonNullGraphType <IdGraphType> >
            {
                Name        = "token",
                Description = "A unique short lived access token from facebook.",
            }),
                resolve: async context =>
            {
                var client = new HttpClient
                {
                    BaseAddress = new Uri("https://graph.facebook.com/v3.2/")
                };
                var accessToken = context.GetArgument <string>("token");
                var response    = await client.GetAsync($"me?access_token={accessToken}&fields=id", context.CancellationToken);
                var content     = await response.Content.ReadAsStringAsync();

                if (!response.IsSuccessStatusCode)
                {
                    context.Errors.Add(new ExecutionError(response.ReasonPhrase));
                    return(default);
コード例 #6
0
        public HttpResponseMessage Login([FromBody] UserLoginDto _UserLoginDto)
        {
            UserLoginResponse _ResponseObj = new UserLoginResponse();

            try
            {
                if (!string.IsNullOrEmpty(_UserLoginDto.username) && !string.IsNullOrEmpty(_UserLoginDto.password))
                {
                    if (_UserLoginDto.username == "kelvin" && _UserLoginDto.password == "kelvin123")
                    {
                        string userId = "123456";
                        _ResponseObj.status  = true;
                        _ResponseObj.message = Messages.successful_login;
                        _ResponseObj.token   = JWTService.CreateJwtToken(userId);
                        return(Request.CreateResponse <UserLoginResponse>(HttpStatusCode.OK, _ResponseObj));
                    }
                    else
                    {
                        return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, Messages.incorrect_credentials));
                    }
                }
                if (string.IsNullOrEmpty(_UserLoginDto.username))
                {
                    return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, Messages.username_required));
                }
                if (string.IsNullOrEmpty(_UserLoginDto.password))
                {
                    return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, Messages.password_required));
                }
                return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, Messages.try_again));
            }
            catch (Exception Ex)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, Ex.Message));
            }
        }
コード例 #7
0
 public AuthorizationController(JWTService jwt, UserService user, DiscordService discord)
 {
     _jwtService     = jwt;
     _userService    = user;
     _discordService = discord;
 }
コード例 #8
0
        public ActionResult Register(CustomerItem customer)
        {
            var objr = new CustomerAppItem
            {
                Status = 0
            };

            try
            {
                if (!string.IsNullOrEmpty(customer.Phone) && !string.IsNullOrEmpty(customer.Password))
                {
                    if (_da.CheckUserName(customer.Phone))
                    {
                        return(Json(new BaseResponse <CustomerItem>()
                        {
                            Erros = true,
                            Message = "Số điện thoại đã tồn tại",
                        }, JsonRequestBehavior.AllowGet));
                    }
                    var daten            = DateTime.Now;
                    var date             = daten.TotalSeconds();
                    var saltKey          = FDIUtils.CreateSaltKey(5);
                    var sha1PasswordHash = FDIUtils.CreatePasswordHash(customer.Password, saltKey);

                    //get agencyinfo
                    var agencyDA = new AgencyDA();
                    var agency   = agencyDA.GetItem(customer.PhoneAgency);
                    var obj      = new Base.Customer
                    {
                        FullName     = customer.FullName,
                        Phone        = customer.Phone,
                        PasswordSalt = saltKey,
                        PassWord     = sha1PasswordHash,
                        UserName     = customer.UserName,
                        DateCreated  = date,
                        IsDelete     = false,
                        IsActive     = true,
                        Reward       = 0,
                        AgencyID     = agency?.ID
                    };
                    _da.Add(obj);
                    _da.Save();

                    IAuthContainerModel model = new JWTContainerModel()
                    {
                        Claims = new Claim[]
                        {
                            new Claim(ClaimTypes.Name, obj.UserName),
                            new Claim("ID", obj.ID.ToString()),
                        }
                    };

                    IAuthService authService = new JWTService();
                    var          token       = authService.GenerateToken(model);
                    var          result      = new BaseResponse <CustomerItem>()
                    {
                        Erros = false,
                        Data  = new CustomerItem()
                        {
                            FullName = obj.FullName,
                            Phone    = obj.Phone,
                            Token    = token
                        }
                    };

                    return(Json(result, JsonRequestBehavior.AllowGet));

                    var datee = daten.AddDays(5).TotalSeconds();
                    //var lg = new Ultils();
                    var code    = Ultils.CodeLogin(daten);
                    var dNlogin = new DN_Login
                    {
                        CustomerID  = obj.ID,
                        DateCreated = date,
                        DateEnd     = datee,
                        Code        = code,
                        IsOut       = false
                    };
                    _dl.Add(dNlogin);
                    _dl.Save();
                    objr = new CustomerAppItem
                    {
                        ID     = obj.ID,
                        Status = 1,
                    };
                }
            }
            catch (Exception ex)
            {
                Log2File.LogExceptionToFile(ex);
            }
            return(Json(objr, JsonRequestBehavior.AllowGet));
        }
コード例 #9
0
        public async void VerificarAction(object sender, EventArgs args)
        {
            string resultado = await JWTService.Verificar();

            LblResultado.Text = resultado;
        }
コード例 #10
0
 public IHttpActionResult CCCC(string token)
 {
     return(Json(JWTService.DecodeToken(token)));
 }
コード例 #11
0
 public AuthenticationService(UserService userService, UserSessionService userSessionsService, JWTService JWTService, EncryptionService encryptionService)
 {
     _UserService         = userService;
     _UserSessionsService = userSessionsService;
     _JWTService          = JWTService;
     _EncryptionService   = encryptionService;
 }
コード例 #12
0
 public NotificationsViewModel()
 {
     UserId      = int.Parse(JWTService.DecodeJWT());
     InitCommand = new Command(async() => await Init());
 }
コード例 #13
0
        static void Main(string[] args)
        {
            string[] signUp;
            string[] logIn = null;
            int      recv;

            byte[]     data     = new byte[1024];
            IPEndPoint endpoint = new IPEndPoint(IPAddress.Any, 12000);

            Socket newSocket = new Socket(AddressFamily.InterNetwork,
                                          SocketType.Dgram, ProtocolType.Udp); //Ruajtja e connection qe e marrim

            newSocket.Bind(endpoint);                                          //lidhja e cdo connection ne mberritje

            Console.WriteLine("Duke pritur per nje klient.....");

            IPEndPoint sender     = new IPEndPoint(IPAddress.Any, 12000); //Lidhje e cdo pajisjeje(klienti) me qfardo IP dhe porti: 12000
            EndPoint   tempRemote = (EndPoint)sender;                     //variabla qe e ruan klinetin

Kthehu:
            while (true)
            {
                data = new byte[1024];                                      //resetimi i byte[]
                recv = newSocket.ReceiveFrom(data, ref tempRemote);
                Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv)); //nese ka te dhena per tu lexuar, atehere i shfaqim ato

                string[] result = Encoding.ASCII.GetString(data, 0, recv).Split(' ');

                // ***....
                // ***....
                for (int i = 0; i < data.Length; i++)
                {
                    Console.WriteLine(data[i] + " Length= " + result[i].Length);
                }
                Console.WriteLine(result.Length);


                int messageLength = result[2].Length;

                byte[] message = new byte[messageLength];

                int length = result[1].Length;
                Console.WriteLine(length);
                desKey = new byte[length];

                desKey = DecryptDataOaepSha1(cert, Convert.FromBase64String(result[1]));
                int ivlength = result[0].Length;

                desIv = new byte[ivlength];

                desIv = Convert.FromBase64String(result[0]);
                Console.WriteLine("Gjatesia e pranuar" + data.Length);
                Console.WriteLine(Convert.ToBase64String(desKey));

                byte[] decryptedMessage = DekriptoDes(result[2]);

                Console.WriteLine(Convert.ToBase64String(decryptedMessage));

                string[] tedhenat = Encoding.UTF8.GetString(decryptedMessage).Split(':');

                if (result.Length > 2)
                {
                    signUp = result;

                    //**********************************

                    string connectionString = @"server=localhost;userid=root;password=1234;database=user_db";

                    MySqlConnection connection = null;
                    try
                    {
                        byte[] bytePlainText    = System.Text.Encoding.UTF8.GetBytes(signUp[4]);;
                        byte[] byteSalt         = CreateSalt();
                        string salt             = System.Convert.ToBase64String(byteSalt);
                        String hashedSaltedPass = GenerateSaltedHash(bytePlainText, byteSalt);

                        connection = new MySqlConnection(connectionString);
                        connection.Open();
                        MySqlCommand cmd = new MySqlCommand();
                        cmd.Connection  = connection;
                        cmd.CommandText = "INSERT INTO `users`(`firstname`, `lastname`, `email`, `username`, `password`,`salt`) VALUES(@fn, @ln, @email, @usn, @pass,@salt)";
                        cmd.Prepare();

                        cmd.Parameters.AddWithValue("@fn", signUp[0]);
                        cmd.Parameters.AddWithValue("@ln", signUp[1]);
                        cmd.Parameters.AddWithValue("@email", signUp[2]);
                        cmd.Parameters.AddWithValue("@usn", signUp[3]);
                        cmd.Parameters.AddWithValue("@pass", hashedSaltedPass);
                        cmd.Parameters.AddWithValue("@salt", salt);

                        // check if the textboxes contains the default values
                        if (!checkTextBoxesValues())
                        {
                            // check if the password equal the confirm password
                            if (signUp[4].Equals(signUp[5]))
                            {
                                // check if this username already exists
                                if (checkUsername())
                                {
                                    Console.WriteLine("This Username Already Exists, Select A Different One", "Duplicate Username");
                                }
                                else
                                {
                                    // execute the query
                                    if (cmd.ExecuteNonQuery() == 1)
                                    {
                                        Console.WriteLine("Your Account Has Been Created", "Account Created");
                                    }
                                    else
                                    {
                                        Console.WriteLine("ERROR");
                                    }
                                }
                            }
                            else
                            {
                                Console.WriteLine("Wrong Confirmation Password", "Password Error");
                            }
                        }
                        else
                        {
                            Console.WriteLine("Enter Your Informations First", "Empty Data");
                        }
                    }
                    finally
                    {
                        if (connection != null)
                        {
                            connection.Close();
                        }
                    }

                    // *-*-/-
                    IAuthContainerModel model       = GetJWTContainerModel(signUp[3], signUp[2]);
                    IAuthService        authService = new JWTService(model.SecretKey);

                    string token = authService.GenerateToken(model);

                    if (!authService.IsTokenValid(token))
                    {
                        throw new UnauthorizedAccessException();
                    }
                    else
                    {
                        List <Claim> claims = authService.GetTokenClaims(token).ToList();

                        Console.WriteLine(claims.FirstOrDefault(e => e.Type.Equals(ClaimTypes.Name)).Value);
                        Console.WriteLine(claims.FirstOrDefault(e => e.Type.Equals(ClaimTypes.Email)).Value);
                    }
                    // *-*-/-


                    // check if the username already exists
                    Boolean checkUsername()
                    {
                        DB db = new DB();

                        String username = signUp[3];

                        DataTable table = new DataTable();

                        MySqlDataAdapter adapter = new MySqlDataAdapter();

                        MySqlCommand command = new MySqlCommand("SELECT * FROM `users` WHERE `username` = @usn", db.getConnection());

                        command.Parameters.Add("@usn", MySqlDbType.VarChar).Value = username;

                        adapter.SelectCommand = command;

                        adapter.Fill(table);

                        // check if this username already exists in the database
                        if (table.Rows.Count > 0)
                        {
                            return(true);
                        }
                        else
                        {
                            return(false);
                        }
                    }

                    // check if the textboxes contains the default values
                    Boolean checkTextBoxesValues()
                    {
                        String fname    = signUp[0];
                        String lname    = signUp[1];
                        String email    = signUp[2];
                        String username = signUp[3];
                        String password = signUp[4];

                        if (fname.Equals("first name") || lname.Equals("last name") ||
                            email.Equals("email") || username.Equals("username") ||
                            password.Equals("password"))
                        {
                            return(true);
                        }
                        else
                        {
                            return(false);
                        }
                    }
                }

                else
                {
                    logIn = result;

                    string connectionString = @"server=localhost;userid=root;password=1234;database=user_db";

                    MySqlConnection connection = null;
                    MySqlDataReader reader     = null;
                    try
                    {
                        connection = new MySqlConnection(connectionString);
                        connection.Open();


                        string           stm         = "SELECT * FROM `users` WHERE `username` = '" + logIn[0] + "'"; //and `password` = '" +logIn[1]+"'";
                        MySqlDataAdapter dataAdapter = new MySqlDataAdapter();
                        dataAdapter.SelectCommand = new MySqlCommand(stm, connection);
                        DataTable table = new DataTable();
                        dataAdapter.Fill(table);
                        if (table.Rows.Count > 0)
                        {
                            Console.WriteLine("Username found");
                            string salt             = table.Rows[0]["salt"].ToString();
                            string pass             = table.Rows[0]["password"].ToString();
                            string id               = table.Rows[0]["id"].ToString();
                            byte[] byteSalt         = System.Convert.FromBase64String(salt);
                            byte[] bytePlainText    = System.Text.Encoding.UTF8.GetBytes(logIn[1]);
                            string hashedSaltedPass = GenerateSaltedHash(bytePlainText, byteSalt);
                            if (pass.Equals(hashedSaltedPass))
                            {
                                Console.WriteLine("Loged in");
                                string query = "SELECT * FROM `grades` WHERE `userid` =' " + id + "'";
                                dataAdapter = new MySqlDataAdapter();
                                dataAdapter.SelectCommand = new MySqlCommand(query, connection);
                                DataTable table1 = new DataTable();
                                dataAdapter.Fill(table1);
                                string test = null;
                                for (int i = 0; table1.Rows.Count > i; i++)
                                {
                                    test += table1.Rows[i]["course"].ToString() + " " + table1.Rows[i]["grade"].ToString() + "\n";
                                }

                                byte[] packetData = System.Text.ASCIIEncoding.ASCII.GetBytes(test);
                                newSocket.SendTo(packetData, tempRemote);
                            }
                            else
                            {
                                Console.WriteLine("Wrong password/username");
                                byte[] packetData = System.Text.ASCIIEncoding.ASCII.GetBytes("Wrong password/username");
                                newSocket.SendTo(packetData, tempRemote);
                                goto Kthehu;
                            }
                        }
                        else
                        {
                            Console.WriteLine("Wrong password/username");
                            byte[] packetData = System.Text.ASCIIEncoding.ASCII.GetBytes("Wrong password/username");
                            newSocket.SendTo(packetData, tempRemote);
                            goto Kthehu;
                        }
                    }
                    finally
                    {
                        if (reader != null)
                        {
                            reader.Close();
                        }
                        if (connection != null)
                        {
                            connection.Close();
                        }
                    }
                }
            }
        }
コード例 #14
0
        public async void ValidarToken(object sender, EventArgs args)
        {
            var resultado = await JWTService.Verificar();

            //LblResultado.Text = resultado;
        }
コード例 #15
0
        public static void set_AppSettings()
        {
            try
            {
                if (IsContainsValue("GMPActive"))
                {
                    SIS.Client.blvalue.AppMain.AppValue.GMPActive = Convert.ToBoolean(System.Configuration.ConfigurationManager.AppSettings["GMPActive"]);
                }
                else
                {
                    SIS.Client.blvalue.AppMain.AppValue.GMPActive = true;
                }
                if (IsContainsValue("HTPActive"))
                {
                    Client.blvalue.AppMain.AppValue.HTPActive = Convert.ToBoolean(System.Configuration.ConfigurationManager.AppSettings["HTPActive"]);
                }
                else
                {
                    Client.blvalue.AppMain.AppValue.HTPActive = true;
                }

                if (IsContainsValue("APTActive"))
                {
                    Client.blvalue.AppMain.AppValue.APTActive = Convert.ToBoolean(System.Configuration.ConfigurationManager.AppSettings["APTActive"]);
                }
                else
                {
                    Client.blvalue.AppMain.AppValue.APTActive = true;
                }

                if (IsContainsValue("GYMActive"))
                {
                    Client.blvalue.AppMain.AppValue.APTActive = Convert.ToBoolean(System.Configuration.ConfigurationManager.AppSettings["GYMActive"]);
                }
                else
                {
                    Client.blvalue.AppMain.AppValue.APTActive = true;
                }

                if (IsContainsValue("RACActive"))
                {
                    Client.blvalue.AppMain.AppValue.APTActive = Convert.ToBoolean(System.Configuration.ConfigurationManager.AppSettings["RACActive"]);
                }
                else
                {
                    Client.blvalue.AppMain.AppValue.APTActive = true;
                }

                bool _ConnectionApi = Convert.ToBoolean(System.Configuration.ConfigurationManager.AppSettings["ConnectionApi"]);

                if (SIS.Client.blvalue.AppMain.AppValue.ForceUseLocal)
                {
                    blvalue.Connection = "";
                    _ConnectionApi     = false;
                }
                Data.App.ConnectionDTO AdminConnection = new SIS.Data.App.ConnectionDTO();

                AppMain.AppValue.ApiUrlAdmin = blvalue.Connection;
                if (blvalue.Connection == "")
                {
                    AppMain.AppValue.RunningLocalAdmin = true;
                    blvalue.Connection = "Local";


                    AdminConnection.Server   = System.Configuration.ConfigurationManager.AppSettings["Server"];
                    AdminConnection.Database = System.Configuration.ConfigurationManager.AppSettings["Database"];
                    AdminConnection.UserId   = System.Configuration.ConfigurationManager.AppSettings["Username"];
                    AdminConnection.Password = System.Configuration.ConfigurationManager.AppSettings["Password"];
                }
                bl.blcAdmin = new SIS.Service.Admin.Repository(AppMain.AppValue.RunningLocalAdmin, AppMain.AppValue.ApiUrlAdmin);
                if (!AppMain.AppValue.RunningLocalAdmin & _ConnectionApi == true)
                {
                    SIS.Data.App.SISAdmin _SISAdmin = bl.blcAdmin.get_KodAdmin <SIS.Service.Admin.AdminService, SIS.Data.App.SISAdmin>(r => r.get_KodAdmin());
                    AdminConnection.Server   = _SISAdmin.Server;
                    AdminConnection.Database = _SISAdmin.Database;
                    AdminConnection.UserId   = _SISAdmin.Username;
                    AdminConnection.Password = _SISAdmin.Password;
                }


                if (!AppMain.AppValue.RunningLocalAdmin & _ConnectionApi == false)
                {
                    AdminConnection.Server   = System.Configuration.ConfigurationManager.AppSettings["Server"];
                    AdminConnection.Database = System.Configuration.ConfigurationManager.AppSettings["Database"];
                    AdminConnection.UserId   = System.Configuration.ConfigurationManager.AppSettings["Username"];
                    AdminConnection.Password = System.Configuration.ConfigurationManager.AppSettings["Password"];
                }
                string connection = AdminConnection.Connection(blvalue.Cloude);
                #region Token
                IAuthService        authService = new JWTService();
                IAuthContainerModel model       = GetJWTContainerModel("connection", connection);

                string token = authService.GenerateToken(model);
                if (!string.IsNullOrEmpty(token))
                {
                    connection = token;
                }
                #endregion
                AppMain.AppValue.ConAdmin      = connection;
                AppMain.AppValue.ConAdminFirst = connection;

                SIS.Data.App.GetValue _GetValue = SIS.Client.Admin.bl.get_GetValue();
                _GetValue.ConStr = AppMain.AppValue.ConAdmin;
            }
            catch (Exception ex)
            {
                bl.message.get_Warning(ex.Message, AppMain.AppValue.Language);
            }
        }
 static JWTAuthenticationAttribute()
 {
     JWTService      = SingletonFactoryService.GetJWTService();
     IdentityService = SingletonFactoryService.GetIdentityService();
 }
コード例 #17
0
 public JwtController()
 {
     _jwtService = new JWTService(Secretkey);
 }
コード例 #18
0
        public async Task <object> CheckValidToken(int IdCandidato = 0)
        {
            //se o usuario tiver o manterconectado ativo, renova o token
            if (IdCandidato != 0)
            {
                CandidatoService service   = new CandidatoService();
                Candidato        candidato = service.BuscarCandidato(IdCandidato);
                if (candidato != null)
                {
                    bool manterConectado = new CandidatoService().VerificarManterConectado(IdCandidato);
                    if (manterConectado)
                    {
                        IdentityUser user = await _userManager.FindByEmailAsync(candidato.Email);

                        var roles = await _userManager.GetRolesAsync(user);

                        var token = TokenService.GenerateToken(user, roles.ToList());

                        HttpContext.Response.Cookies
                        .Append("access_token", token, TokenService.GenerateCookies(_config.GetProperty <Environment>("ApiConfig", "Environment")));

                        return(new
                        {
                            ok = true
                        });
                    }
                }
            }

            string jwt = HttpContext.Request.Cookies["access_token"];

            if (string.IsNullOrEmpty(jwt))
            {
                return(new
                {
                    ok = false,
                    message = "Session Expired"
                });
            }
            else
            {
                JWTService helper   = new JWTService();
                DateTime   expiricy = helper.GetExpiryTimestamp(jwt);

                if (expiricy > DateTime.Now)
                {
                    return new
                           {
                               ok = true
                           }
                }
                ;
                else
                {
                    return new
                           {
                               ok      = false,
                               message = "Session Expired"
                           }
                };
            }
        }
コード例 #19
0
        public async Task <Response <MemberResult> > Login(string id, string pw)
        {
            string apiName = "LOGIN";

            #region Anonymous Method
            LoginBadResponse memberBadResponse = delegate(ConTextColor preColor, int status, ConTextColor setColor, string msg)
            {
                UserModel tempModel        = new UserModel();
                string    tempToken        = "";
                string    tempRefreshToken = "";

                ServiceManager.ShowRequestResult(apiName, preColor, status, setColor);
                return(new Response <MemberResult> {
                    data = new MemberResult {
                        token = tempToken, refreshToken = tempRefreshToken, member = tempModel
                    }, status = status, message = msg
                });
            };
            #endregion

            var loginArgs = ComUtil.GetStringLengths(id, pw);

            if (id != null && pw != null && loginArgs[0] > 0 && loginArgs[1] > 0)
            {
                try
                {
                    UserModel user = new UserModel();

                    using (IDbConnection db = GetConnection())
                    {
                        db.Open();

                        string selectSql = $@"
SELECT
    name, 
    email
FROM 
    member_tb
WHERE
    id = '{id}'
AND
    pw = '{pw}'
;";
                        var    response  = await userDBManager.GetSingleDataAsync(db, selectSql, id);

                        if (response != null)
                        {
                            user.id    = id;
                            user.name  = response.name;
                            user.email = response.email;

                            IAuthContainerModel model       = JWTService.GetJWTContainerModel(user.name, user.email);
                            IAuthService        authService = new JWTService(model.SecretKey);

                            string token = authService.GenerateToken(model);
                            // TODO : RefreshToken 발급. => 현재 임시로 빈 값 보냄

                            if (!authService.IsTokenValid(token))
                            {
                                throw new UnauthorizedAccessException();
                            }
                            else
                            {
                                List <Claim> claims = authService.GetTokenClaims(token).ToList();
                                Console.WriteLine("Login UserName : "******"Login Eamil : " + claims.FirstOrDefault(x => x.Type.Equals(ClaimTypes.Email)).Value);

                                ServiceManager.ShowRequestResult("LOGIN", ConTextColor.LIGHT_GREEN, ResponseStatus.OK, ConTextColor.WHITE);
                                return(new Response <MemberResult> {
                                    data = new MemberResult {
                                        token = token, refreshToken = "", member = user
                                    }, message = ResponseMessage.OK, status = ResponseStatus.OK
                                });
                            }
                        }
                        else
                        {
                            return(memberBadResponse(ConTextColor.RED, ResponseStatus.UNAUTHORIZED, ConTextColor.WHITE, ResponseMessage.UNAUTHORIZED));
                        }
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine(apiName + " ERROR : " + e.Message);
                    return(memberBadResponse(ConTextColor.PURPLE, ResponseStatus.INTERNAL_SERVER_ERROR, ConTextColor.WHITE, ResponseMessage.INTERNAL_SERVER_ERROR));
                }
            }
            else
            {
                return(memberBadResponse(ConTextColor.RED, ResponseStatus.BAD_REQUEST, ConTextColor.WHITE, ResponseMessage.BAD_REQUEST));
            }
        }
コード例 #20
0
 public UserController()
 {
     _JWTService = new JWTService();
     ctx         = new KeepCloneContext();
     uow         = new UOW(ctx);
 }
コード例 #21
0
 public string Testing()
 {
     return(JWTService.GenerateToken("*****@*****.**", 1, "admin"));
 }
コード例 #22
0
 public AuthenticationController(DatabaseUserConnector database, JWTService jWTService, UserService userService)
 {
     this.database    = database;
     this.jWTService  = jWTService;
     this.userService = userService;
 }
コード例 #23
0
        public async void GetTokenAction(object sender, EventArgs args)
        {
            string resultado = await JWTService.GetToken(nome.Text, password.Text);

            LblToken.Text = resultado;
        }
コード例 #24
0
 public AttendeeManager()
 {
     _attendeeService = new AttendeesService();
     _jWTService = new JWTService();
     joinEventClaims.Add(ctx.Claims.FirstOrDefault(c => c.ClaimId.Equals(9)).ClaimName);
 }
コード例 #25
0
 public UsuarioController(CempreContext context, IOptions <AppSetting> appSetting)
 {
     _usuarioService = new UsuarioService(context);
     _jwtService     = new JWTService(appSetting);
 }
コード例 #26
0
 private async void GetTokenAction(object sender, EventArgs e)
 {
     LblToken.Text = await JWTService.GetToken(nome.Text, password.Text);
 }
コード例 #27
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="key"></param>
        /// <param name="code">Codelogin khởi tạo</param>
        /// <param name="username">Tài khoản login</param>
        /// <param name="pass">Pass login</param>
        /// <param name="ischeck">Trạng thái duy trì 5 ngày</param>
        /// <returns></returns>
        public ActionResult Login(string key, string username, string pass, bool ischeck)
        {
            var objr = new CustomerAppItem
            {
                Status = 0,
            };
            //var lg = new Ultils();
            var code = Guid.NewGuid().ToString();

            //  if (key != Keyapi) return Json(objr, JsonRequestBehavior.AllowGet);
            var obj = _dl.GetPassByUserName(username);

            if (obj != null)
            {
                var date    = DateTime.Now;
                var dateend = date.AddMinutes(20);
                if (ischeck)
                {
                    dateend = date.AddDays(5);
                }
                var timeend = dateend.TotalSeconds();
                var pas     = FDIUtils.CreatePasswordHash(pass, obj.PasswordSalt);
                if (obj.Password == pas)
                {
                    var dNlogin = new DN_Login
                    {
                        CustomerID  = obj.ID,
                        DateCreated = date.TotalSeconds(),
                        DateEnd     = timeend,
                        Code        = code,
                        IsOut       = false
                    };
                    _dl.Add(dNlogin);
                    _dl.Save();
                    obj.UserName  = obj.UserName;
                    obj.CodeLogin = code;
                    obj.Status    = 1;
                    obj.ID        = obj.ID;

                    IAuthContainerModel model = new JWTContainerModel()
                    {
                        Claims = new Claim[]
                        {
                            new Claim(ClaimTypes.Name, obj.UserName),
                            new Claim("ID", obj.ID.ToString()),
                        }
                    };
                    IAuthService authService = new JWTService();
                    var          token       = authService.GenerateToken(model);
                    var          result      = new BaseResponse <CustomerItem>()
                    {
                        Erros = false,
                        Data  = new CustomerItem()
                        {
                            FullName = obj.FullName,
                            Phone    = obj.Phone,
                            Token    = token
                        }
                    };
                    return(Json(result, JsonRequestBehavior.AllowGet));
                }
                return(Json(new JsonMessage(true, "Mật khẩu không đúng"), JsonRequestBehavior.AllowGet));
            }


            return(Json(new JsonMessage(true, "Tài khoản không tồn tại"), JsonRequestBehavior.AllowGet));
        }
コード例 #28
0
 private async void VerificarAction(object sender, EventArgs e)
 {
     LblResultado.Text = await JWTService.GetToken(nome.Text, password.Text);
 }
コード例 #29
0
 public AuthController() : base()
 {
     DbContext       = FactoryService.GetContext();
     IdentityService = SingletonFactoryService.GetIdentityService();
     JWTService      = SingletonFactoryService.GetJWTService();
 }
コード例 #30
0
 public AuthController(JWTService jWTService, UserService userService, IOptions <AuthSettings> authSettings, AuthService authService) : base(userService)
 {
     this.jWTService   = jWTService;
     this.authSettings = authSettings.Value;
     this.authService  = authService;
 }