Beispiel #1
0
        internal static async Task <string> GetToken()
        {
            Dictionary <string, string> values = new Dictionary <string, string> {
                { "username", "foodvam_test" }, { "password", "sAuTqQ7hA3QfMwqf" }
            };

            try {
                FormUrlEncodedContent content = new FormUrlEncodedContent(values);
                using (HttpClient http = new HttpClient())
                    using (HttpResponseMessage response = await http.PostAsync("https://sso.rfibank.ru/api/token-auth/", content)) {
                        string responseString = await response.Content.ReadAsStringAsync();

                        if (response.IsSuccessStatusCode)
                        {
                            TokenResp result = JsonConvert.DeserializeObject <TokenResp>(responseString);
                            token = result.Token;
                            if (String.IsNullOrEmpty(token) == true)
                            {
                                throw new ApiException("Token is invalid");
                            }
                        }
                    }
            } catch (Exception er) {
                Console.Out.WriteLine("Error: SSO get token / {0}", er.Message);
            }

            //      client.DefaultRequestHeaders.Add("Authorization", token);

            return(token);
        }
        public async Task <bool> AttempLogin(HttpSessionStateBase currentSession)
        {
            bool  isSuccess = true;
            LogIn userlogin = new LogIn()
            {
                emailAddress = this.emailAddress, passWord = this.passWord
            };
            HttpGetObject httpreq = new HttpGetObject();

            httpreq.endPoint = loginEndPoint;

            APIClient           api  = new APIClient();
            HttpResponseMessage resp = await api.postAsync(httpreq, api.convertToContent(userlogin));

            if (!resp.IsSuccessStatusCode)
            {
                isSuccess = false;
                return(isSuccess);
            }
            string val = await resp.Content.ReadAsStringAsync();

            APIKeyResp apikey = JsonConvert.DeserializeObject <APIKeyResp>(val);

            //use API Key to request token

            httpreq.endPoint = tokenEndPoint;
            resp             = await api.postAsync(httpreq, api.convertToContent(apikey));

            if (!resp.IsSuccessStatusCode)
            {
                isSuccess = false;
                return(isSuccess);
            }
            val = await resp.Content.ReadAsStringAsync();

            TokenResp token = JsonConvert.DeserializeObject <TokenResp>(val);

            httpreq.accessToken = token.token;
            httpreq.endPoint    = userProfileEndPoint;
            //httpreq.

            resp = await api.getAsync(httpreq);

            if (!resp.IsSuccessStatusCode)
            {
                isSuccess = false;
                return(isSuccess);
            }

            val = await resp.Content.ReadAsStringAsync();

            GenericResp genId = JsonConvert.DeserializeObject <GenericResp>(val);

            UserSession.SetLoginValues(currentSession, apikey.apiKey, token.token, Convert.ToInt32(genId.id));


            return(isSuccess);
        }
Beispiel #3
0
        public IActionResult Login(LoginRequestDto request)
        {
            TokenResp resp = _IsDbService.Login(request);

            if (resp != null)
            {
                return(Ok(new
                {
                    token = resp.JWTtoken,
                    refreshToken = resp.RefreshToken
                }));
            }
            else
            {
                return(Unauthorized());
            }
        }
Beispiel #4
0
 public TokenResp CheckToken(string token)
 {
     using (var client = new SqlConnection(connString))
         using (var com = new SqlCommand())
         {
             client.Open();
             com.Connection  = client;
             com.CommandText = "select * from RefreshToken where RefreshToken.RefreshToken=@token ";
             com.Parameters.AddWithValue("token", token);
             var dr = com.ExecuteReader();
             if (!dr.Read())
             {
                 return(null);
             }
             else
             {
                 var response = new TokenResp();
                 response.login = dr["Login"].ToString();
                 response.name  = dr["Name"].ToString();
                 return(response);
             }
         }
 }
Beispiel #5
0
        public TokenResp Login(LoginRequestDto req)
        {
            string salt = "";
            string hash = "";
            string newSalt;

            byte[] randomBytes = new byte[128 / 8];
            using (var generator = RandomNumberGenerator.Create())
            {
                generator.GetBytes(randomBytes);
                newSalt = Convert.ToBase64String(randomBytes);
            }
            string login = "";
            string haslo = "";
            //string salt = "";

            var valueBytes = KeyDerivation.Pbkdf2(
                password: req.Haslo,
                salt: Encoding.UTF8.GetBytes(newSalt),
                prf: KeyDerivationPrf.HMACSHA512,
                iterationCount: 40000,
                numBytesRequested: 256 / 8
                );

            using (SqlConnection con = new SqlConnection(ConnString))
                using (SqlCommand com = new SqlCommand())
                {
                    com.Connection = con;
                    con.Open();
                    com.CommandText = "select * from student where IndexNumber = @IndexNumber";
                    com.Parameters.AddWithValue("IndexNumber", req.Login);
                    var dr = com.ExecuteReader();
                    if (dr.Read())
                    {
                        login = dr["IndexNumber"].ToString();
                        haslo = dr["password"].ToString();
                        salt  = dr["salt"].ToString();
                    }
                    dr.Close();
                    var good = IStudentsDbService.Validate(req.Haslo, salt, haslo);
                    if (good)
                    {
                        var claims = new Claim[2];
                        if (req.Login.Equals("s18371"))
                        {
                            claims = new[]
                            {
                                new Claim(ClaimTypes.NameIdentifier, req.Login),
                                new Claim(ClaimTypes.Role, "employee")
                            };
                        }
                        else
                        {
                            claims = new[]
                            {
                                new Claim(ClaimTypes.NameIdentifier, req.Login),
                                new Claim(ClaimTypes.Role, "student")
                            };
                        }
                        var key   = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["SecretKey"]));
                        var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
                        var token = new JwtSecurityToken
                                    (
                            issuer: "Gakko",
                            audience: "Students",
                            claims: claims,
                            expires: DateTime.Now.AddMinutes(10),
                            signingCredentials: creds
                                    );
                        var token2       = new JwtSecurityTokenHandler().WriteToken(token);
                        var refreshToken = Guid.NewGuid();
                        var trok         = new TokenResp();
                        //using (SqlConnection con = new SqlConnection(ConnString))
                        //using (SqlCommand com = new SqlCommand())
                        com.CommandText = "update student set refreshToekn = @refreshToken where IndexNumber = @IndexNumber2";
                        com.Parameters.AddWithValue("IndexNumber2", req.Login);
                        com.Parameters.AddWithValue("refreshToken", refreshToken);
                        com.ExecuteNonQuery();
                        trok.JWTtoken     = token2;
                        trok.RefreshToken = refreshToken;
                        return(trok);
                    }
                    else
                    {
                        return(null);
                    }
                }
            throw new NotImplementedException();
        }