Ejemplo n.º 1
0
        // Private Methods
        private static TokenResponseModel CreateErrorResponseToken(string errorMessage, HttpStatusCode statusCode)
        {
            var errorToken = new TokenResponseModel
            {
                Token    = null,
                Username = null,
                Role     = null,
                RefreshTokenExpiration = DateTime.Now,
                RefreshToken           = null,
                Expiration             = DateTime.Now,
                ResponseInfo           = CreateResponse(errorMessage, statusCode),
            };

            return(errorToken);
        }
Ejemplo n.º 2
0
        public async Task <TokenResponseModel?> CreateUserTokenAsync(string username, string password)
        {
            var userInfo = await _userProvider.GetUserAsync(username, password);

            if (userInfo == null)
            {
                _logger.LogWarning("Could not find specific user");
                return(null);
            }

            var expires = DateTime.Now.AddDays(365);

            var tokenHandler = new JwtSecurityTokenHandler();
            var key          = Encoding.ASCII.GetBytes(_authSettings.Secret);

            var identityClaims = new List <Claim>(new[]
            {
                new Claim(ClaimTypes.NameIdentifier, username),
                new Claim(ClaimTypes.Name, userInfo.Name),
            });

            if (userInfo.Scopes != null)
            {
                foreach (var scope in userInfo.Scopes)
                {
                    identityClaims.Add(new Claim("scope", scope));
                }
            }

            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject            = new ClaimsIdentity(identityClaims),
                Expires            = expires,
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
            };
            var token = tokenHandler.CreateToken(tokenDescriptor);

            var tokenDto = new TokenResponseModel
            {
                UserName = userInfo.UserName,
                Name     = userInfo.Name,
                Scopes   = userInfo.Scopes,
                Expires  = expires,
                Token    = tokenHandler.WriteToken(token)
            };

            return(tokenDto);
        }
Ejemplo n.º 3
0
        public async static Task <TokenResponseModel> GetToken(User user)
        {
            string              json     = JsonConvert.SerializeObject(user);
            var                 content  = new StringContent(json, UnicodeEncoding.UTF8, "application/json");
            HttpClient          client   = new HttpClient();
            HttpResponseMessage response = await client.PostAsync("https://localhost:44316/api/accounts/token", content);

            if (response.StatusCode == System.Net.HttpStatusCode.BadRequest)
            {
                throw new Exception(Application.Current.Resources["m_error_bad_signup"].ToString());
            }
            TokenResponseModel tokenResponseModel = JsonConvert.DeserializeObject <TokenResponseModel>(await response.Content.ReadAsStringAsync());

            Resources.Token = tokenResponseModel.AccessToken;
            return(tokenResponseModel);
        }
Ejemplo n.º 4
0
        private TokenResponseModel ConvertAndRefreshToken(string token)
        {
            var handler = new JwtSecurityTokenHandler();

            token = token.Replace("Bearer ", "");
            var jsonToken        = handler.ReadToken(token);
            var tokenCollection  = handler.ReadToken(token) as JwtSecurityToken;
            var header           = tokenCollection.Claims.FirstOrDefault().Value;
            var headerCollection = header.Split("+");
            var email            = headerCollection[0];
            var isActive         = headerCollection[1] == true.ToString();
            var refreshedToken   = Authorize(email, isActive);
            var result           = new TokenResponseModel(email, isActive, refreshedToken);

            return(result);
        }
Ejemplo n.º 5
0
        public ActionResult TokenHistory(string token)
        {
            TokenResponseModel model = new TokenResponseModel();

            int timeStamp = (Int32)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;
            TokenHistoryRequest request = new TokenHistoryRequest();

            request.MERCHANT  = "OPU_TEST";
            request.TIMESTAMP = timeStamp.ToString();
            request.TOKEN     = token;
            Options options = new Options();

            options.Url         = "https://secure.payu.com.tr/order/token/v2/merchantToken/";
            options.SecretKey   = "SECRET_KEY";
            model.TokenResponse = TokenHistoryRequest.Execute(request, options); //api çağrısının başlatıldığı kısmı temsil eder.
            return(View(model));
        }
Ejemplo n.º 6
0
        // Getting a token based on credentials
        public static void SetToken(string username, string password)
        {
            RestClient restClient = new RestClient(baseUrl);

            RestRequest restRequest = new RestRequest(loginEndpoint, Method.GET);

            restRequest.AddParameter("moodlewsrestformat", "json");
            restRequest.AddParameter("username", username);
            restRequest.AddParameter("password", password);
            restRequest.AddParameter("service", service);

            string requestResponse = restClient.Execute(restRequest).Content;

            TokenResponseModel tokenResponse = JsonConvert.DeserializeObject <TokenResponseModel>(requestResponse);

            token = tokenResponse.Token;
        }
Ejemplo n.º 7
0
        public static async Task <Result> RecaptchaTokenVerify(IHttpClientFactory clientFactory, GoogleSettings googleOptions, string token)
        {
            var tokenResponse = new TokenResponseModel()
            {
                Success = false
            };

            using (var client = clientFactory.CreateClient(HttpClientNames.GoogleRecaptcha))
            {
                var response = await client.GetStringAsync($"{googleOptions.RecaptchaVerifyApi}?secret={googleOptions.SecretKey}&response={token}");

                tokenResponse = JsonConvert.DeserializeObject <TokenResponseModel>(response);
            }

            return((!tokenResponse.Success || tokenResponse.Score < (decimal)0.5)
                                 ? Result.Failure("Recaptcha token is invalid")
                                 : Result.Ok());
        }
Ejemplo n.º 8
0
        public ActionResult TokenServiceCreateToken(string refNo)
        {
            TokenResponseModel model = new TokenResponseModel();
            int timeStamp            = (Int32)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;

            TokenServiceCreateTokenRequest request = new TokenServiceCreateTokenRequest();

            request.MERCHANT  = "OPU_TEST";
            request.REFNO     = refNo;
            request.TIMESTAMP = timeStamp.ToString();
            Options options = new Options();

            options.Url       = "https://secure.payu.com.tr/order/token/v2/merchantToken/";
            options.SecretKey = "SECRET_KEY";

            model.TokenResponse = TokenServiceCreateTokenRequest.Execute(request, options);
            return(View(model));
        }
Ejemplo n.º 9
0
        public TokenResponseModel Post([FromBody] CreateHeroRequest createHeroRequest)
        {
            TokenResponseModel token = null;

            try
            {
                AOResult <HeroUnitModel> heroResult = _heroService.CreateHero(createHeroRequest);
                if (heroResult.IsSuccess)
                {
                    token = _tokenService.CreateTokenAsync(heroResult.Result.Name);
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message + " hero not created");
            }

            return(token);
        }
Ejemplo n.º 10
0
        public GSTNResult <TokenResponseModel> RequestToken(string username, string otp)
        {
            TokenRequestModel model = new TokenRequestModel {
                action   = "AUTHTOKEN",
                username = username
            };

            model.app_key = EncryptionUtils.RsaEncrypt(GSTNConstants.GetAppKeyBytes());
            model.otp     = EncryptionUtils.AesEncrypt(otp, GSTNConstants.GetAppKeyBytes());
            var output = this.Post <TokenRequestModel, TokenResponseModel>(model);

            this.username     = username;
            token             = output.Data;
            this.AuthToken    = token.auth_token;
            this.DecryptedKey = EncryptionUtils.AesDecrypt(token.sek, GSTNConstants.GetAppKeyBytes());
            var Decipher = System.Text.Encoding.UTF8.GetString(DecryptedKey);

            return(output);
        }
Ejemplo n.º 11
0
        public TokenResponseModel RenewAccessToken(RenewTokenInputType renewToken)
        {
            var result = new TokenResponseModel {
                Message = "Success"
            };

            ClaimsPrincipal principal = GetClaimsFromExpiredToken(renewToken.AccessToken);

            if (principal == null)
            {
                result.Message = "Invalid Token";
                return(result);
            }
            string email = principal.Claims.Where(_ => _.Type == "Email").Select(_ => _.Value).FirstOrDefault();

            if (string.IsNullOrEmpty(email))
            {
                result.Message = "Invalid Token";
                return(result);
            }

            var user = _authContext.User
                       .Where(_ => _.EmailAddress == email && _.RefreshToken == renewToken.RefreshToken && _.RefershTokenExpiration > DateTime.Now).FirstOrDefault();

            if (user == null)
            {
                result.Message = "Invalid Token";
                return(result);
            }

            var userRoles = _authContext.UserRoles.Where(_ => _.UserId == user.UserId).ToList();

            result.AccessToken = GetJWTAuthKey(user, userRoles);

            result.RefreshToken = GenerateRefreshToken();

            user.RefreshToken           = result.RefreshToken;
            user.RefershTokenExpiration = DateTime.Now.AddDays(7);

            _authContext.SaveChanges();

            return(result);
        }
Ejemplo n.º 12
0
        public GSTNResult <TokenResponseModel> RefreshToken()
        {
            RefreshTokenModel model = new RefreshTokenModel
            {
                action   = "REFRESHTOKEN",
                username = userid
            };

            model.app_key    = EncryptionUtils.AesEncrypt(GSTNConstants.GetAppKeyBytes(), this.DecryptedKey);
            model.auth_token = this.AuthToken;
            var output = this.Post <RefreshTokenModel, TokenResponseModel>(model);

            token             = output.Data;
            this.AuthToken    = token.auth_token;
            this.DecryptedKey = EncryptionUtils.AesDecrypt(token.sek, GSTNConstants.GetAppKeyBytes());
            var Decipher = System.Text.Encoding.UTF8.GetString(DecryptedKey);

            return(output);
        }
Ejemplo n.º 13
0
        public static TokenResponseModel GetJwt(UserModel usuario, List <Claim> extraClaims = null)
        {
            var       utc0          = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
            var       now           = DateTime.Now;
            const int expireMinutes = 518400;

            var claims = new List <Claim>
            {
                new Claim(JwtRegisteredClaimNames.Sub, usuario.User),
                new Claim("id", usuario.Id.ToString()),
                new Claim("user", usuario.User),
                new Claim("name", usuario.Name),
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                new Claim(JwtRegisteredClaimNames.Iat, ((int)now.Subtract(utc0).TotalSeconds).ToString(), ClaimValueTypes.Integer64)
            };

            if (extraClaims != null)
            {
                claims.AddRange(extraClaims);
            }

            var jwt = new JwtSecurityToken(
                issuer: ValidIssuer,
                audience: ValidAudiences?.FirstOrDefault(),
                claims: claims,
                notBefore: now,
                expires: now.Add(TimeSpan.FromMinutes(expireMinutes)),
                signingCredentials: new SigningCredentials(SigningKey(), SecurityAlgorithms.HmacSha256)
                );

            var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt);

            var response = new TokenResponseModel
            {
                AccessToken  = encodedJwt,
                ExpiresAt    = DateTime.UtcNow.AddDays(1),
                RefreshToken = Guid.NewGuid().ToString()
            };

            response.AccessId = RefreshTokenManager?.Save(new TokenItemModel(usuario, response.AccessToken, response.RefreshToken, response.ExpiresAt));

            return(response);
        }
Ejemplo n.º 14
0
        private async Task <Models.APIResponse <TokenResponseModel> > CreateEncodedJwtToken(CommonUser user)
        {
            var claims = new[]
            {
                new Claim(JWTClaim.Sid, user.Id.ToString()),
                new Claim(JWTClaim.Sub, user.Email),
                new Claim(JWTClaim.Jti, await _jwtOptions.JtiGenerator()),
                new Claim(JWTClaim.Iat, ToUnixEpochDate(_jwtOptions.IssuedAt).ToString(), ClaimValueTypes.Integer64),
                new Claim(JWTClaim.SystemPermission, ((int)user.Permission).ToString())
            };

            // Create the JWT security token and encode it.
            var jwt = new JwtSecurityToken(
                issuer: _jwtOptions.Issuer,
                audience: _jwtOptions.Audience,
                claims: claims,
                notBefore: _jwtOptions.NotBefore,
                expires: _jwtOptions.Expiration,
                signingCredentials: _jwtOptions.SigningCredentials);

            var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt);
            var now        = DateTime.UtcNow;
            var expires    = now.AddMonths(6);

            var tokenReponse = new TokenResponseModel {
                Token      = encodedJwt,
                Expires    = expires.ToUnixTime(),
                FirstName  = user.FirstName,
                LastName   = user.LastName,
                Id         = user.Id,
                Email      = user.Email,
                Permission = user.Permission
            };

            if (!string.IsNullOrWhiteSpace(user.ProfileImageKey))
            {
                tokenReponse.ProfileImageUrl = AppSettings.AmazonS3Url + user.ProfileImageKey;
            }

            return(new APIResponse <TokenResponseModel> {
                Data = tokenReponse
            });
        }
Ejemplo n.º 15
0
        void LoginToGoogle()
        {
            string access_token;

            LoginServices loginservice = new LoginServices();
            var           auth         = new OAuth2Authenticator(
                clientId: "549020993769-tn974vfkrovsr1k4g65135k6m02vec6j.apps.googleusercontent.com",
                scope: "https://www.googleapis.com/auth/userinfo.email",
                authorizeUrl: new Uri("https://accounts.google.com/o/oauth2/auth"),
                redirectUrl: new Uri("http://bunchy.com/oauth2callback"),
                getUsernameAsync: null);

            auth.Completed += (sender, e) =>
            {
                e.Account.Properties.TryGetValue("access_token", out access_token);
                access_token_return = access_token;
                Console.WriteLine(access_token);
                _TokenResponse     = BunchyAuth(access_token_return, "google");
                e.Account.Username = _TokenResponse.Username;
                if (e.Account.Username == "New User")
                {
                    AccountStore.Create(this).Save(e.Account, "google");
                    var newuserintent = new Intent(this, typeof(NewUserActivity));
                    StartActivity(newuserintent);
                }
                else
                {
                    AccountStore.Create(this).Save(e.Account, "google");
                    var rideintent = new Intent(this, typeof(RidesActivity));
                    StartActivity(rideintent);
                }



                //textView.Text = access_token;
            };

            //_TokenResponse = await loginservice.LoginExternal(access_token,"google");

            var intent = auth.GetUI(this);

            StartActivity(intent);
        }
Ejemplo n.º 16
0
        public async Task <TokenResponseModel> sigIn(Usuario entidad)
        {
            try
            {
                string json = JsonConvert.SerializeObject(entidad, Formatting.Indented,
                                                          new JsonSerializerSettings
                {
                    ReferenceLoopHandling = ReferenceLoopHandling.Ignore
                });

                HttpClientHandler handler  = new HttpClientHandler();
                var httpClient             = new HttpClient(handler);
                HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, Path_Servicio.obtenerUrl() + "token");

                //request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", Hefesoft.Standard.Static.Variables_Globales.Bearer);
                request.Content = new StringContent("grant_type=password&username="******"&password="******"application/x-www-form-urlencoded");
                MediaTypeHeaderValue contentType = request.Content.Headers.ContentType;
                contentType.MediaType = "application/json";



                request.Content.Headers.ContentType = contentType;

                if (handler.SupportsTransferEncodingChunked())
                {
                    request.Headers.TransferEncodingChunked = true;
                }
                HttpResponseMessage response = await httpClient.SendAsync(request);

                var resultadoString = response.Content.ReadAsStringAsync().Result;

                TokenResponseModel tokenResponse = (TokenResponseModel)JsonConvert.DeserializeObject(resultadoString, typeof(TokenResponseModel));
                Hefesoft.Standard.Static.Variables_Globales.Bearer = tokenResponse.AccessToken;
                return(tokenResponse);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Ejemplo n.º 17
0
        // Creating JWT Authentication Token
        private async Task <TokenResponseModel> GenerateNewToken(ApplicationUser user, LoginViewModel model)
        {
            var key   = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(_appSettings.Secret));
            var roles = await _userManager.GetRolesAsync(user);

            var tokenHandler = new JwtSecurityTokenHandler();

            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new Claim[]
                {
                    new Claim(JwtRegisteredClaimNames.Sub, model.Email),
                    new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                    new Claim(ClaimTypes.NameIdentifier, user.Id),
                    new Claim(ClaimTypes.Role, roles.FirstOrDefault()),
                    new Claim("LoggedOn", DateTime.Now.ToString(CultureInfo.InvariantCulture)),
                }),

                SigningCredentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256Signature),
                Issuer             = _appSettings.Site,
                Audience           = _appSettings.Audience,
                Expires            = (string.Equals(roles.FirstOrDefault(), "Admin", StringComparison.CurrentCultureIgnoreCase)) ? DateTime.UtcNow.AddMinutes(60) : DateTime.UtcNow.AddMinutes(Convert.ToDouble(_appSettings.ExpireTime))
            };

            var userClaims = await _userManager.GetClaimsAsync(user);

            var token = tokenHandler.CreateToken(tokenDescriptor);

            var authToken = new TokenResponseModel
            {
                Token        = token.ToString(),
                Expiration   = token.ValidTo,
                Role         = roles.FirstOrDefault(),
                Username     = user.UserName,
                UserId       = user.Id,
                ResponseInfo = CreateResponse("Auth Token Created", HttpStatusCode.OK)
            };

            return(authToken);
        }
Ejemplo n.º 18
0
        public async Task <TokenResponseModel> Login(string username, string password)
        {
            //HttpWebRequest request = new HttpWebRequest(new Uri("http://192.168.56.1:1524/token"));
            HttpWebRequest request = new HttpWebRequest(new Uri("http://bunchyapi.azurewebsites.net/token"));

            request.Method = "POST";

            string postString = String.Format("username={0}&password={1}&grant_type=password", "craig", "pword");

            //Log.Info("bunchy",postString);
            byte[] bytes = Encoding.UTF8.GetBytes(postString);

            using (Stream requestStream = await request.GetRequestStreamAsync())
            {
                requestStream.Write(bytes, 0, bytes.Length);
            }

            try
            {
                HttpWebResponse httpResponse = (HttpWebResponse)(await request.GetResponseAsync());
                string          json;
                using (Stream responseStream = httpResponse.GetResponseStream())
                {
                    json = new StreamReader(responseStream).ReadToEnd();
                }
                TokenResponseModel tokenResponse = JsonConvert.DeserializeObject <TokenResponseModel>(json);
                //App.UserPreferences.SetString("Token",tokenResponse.AccessToken);
                //App.UserPreferences.SetString("UserName",username);
                //App.RegisterUser.RegisterWithGCMAndriod();
                return(tokenResponse);
            }
            catch (Exception ex)
            {
                //Log.Info("bunchy",ex.Message);
                TokenResponseModel tokenResponse = new TokenResponseModel();
                tokenResponse.AccessToken = null;
                return(tokenResponse);
            }
        }
Ejemplo n.º 19
0
        public TokenResponseModel Login(LoginInputType loginInput)
        {
            var result = new TokenResponseModel {
                Message = "Success"
            };

            if (string.IsNullOrEmpty(loginInput.Email) ||
                string.IsNullOrEmpty(loginInput.Password))
            {
                result.Message = "Invalid Credentials";
                return(result);
            }

            var user = _authContext.User.Where(_ => _.EmailAddress == loginInput.Email).FirstOrDefault();

            if (user == null)
            {
                result.Message = "Invalid Credentials";
                return(result);
            }

            if (!ValidatePasswordHash(loginInput.Password, user.Password))
            {
                result.Message = "Invalid Credentials";
                return(result);
            }

            var roles = _authContext.UserRoles.Where(_ => _.UserId == user.UserId).ToList();

            result.AccessToken = GetJWTAuthKey(user, roles);

            result.RefreshToken = GenerateRefreshToken();

            user.RefreshToken           = result.RefreshToken;
            user.RefershTokenExpiration = DateTime.Now.AddDays(7);
            _authContext.SaveChanges();

            return(result);
        }
Ejemplo n.º 20
0
        /// <summary>
        /// Gets a Token from the Token Service
        /// </summary>
        /// <param name="authentication">The authentication body</param>
        /// <returns></returns>
        public async Task <TokenResponseModel> GetTokenAsync(AuthenticationModel authentication)
        {
            try
            {
                var client   = CreateClient();
                var response = await client.PostAsync <string>(
                    "/token",
                    JsonConvert.SerializeObject(authentication),
                    new TextMediaFormatter());

                var tokenResponse = new TokenResponseModel
                {
                    StatusCode = response.StatusCode
                };

                var responseText = await response.Content.ReadAsStringAsync();

                if (response.StatusCode == HttpStatusCode.OK)
                {
                    return(new TokenResponseModel
                    {
                        StatusCode = response.StatusCode,
                        AuthToken = responseText
                    });
                }
                else
                {
                    return(new TokenResponseModel
                    {
                        StatusCode = response.StatusCode,
                        Message = responseText
                    });
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Ejemplo n.º 21
0
        public async Task <bool> Login(string username, string password, string facebookAccessToken)
        {
            try
            {
                string url = WebApiUrlToken;

                HttpWebRequest request = new HttpWebRequest(new Uri(url));
                request.Timeout = Timeout;
                request.Method  = "POST";
                string postString = String.Format("username={0}&password={1}&grant_type=password",
                                                  System.Net.WebUtility.UrlEncode(username),
                                                  System.Net.WebUtility.UrlEncode(password));
                if (string.IsNullOrEmpty(facebookAccessToken) == false)
                {
                    postString += "&facebookToken=" + System.Net.WebUtility.UrlEncode(facebookAccessToken);
                }
                byte[] bytes = Encoding.UTF8.GetBytes(postString);
                using (Stream requestStream = await request.GetRequestStreamAsync())
                {
                    requestStream.Write(bytes, 0, bytes.Length);
                }

                HttpWebResponse httpResponse = (HttpWebResponse)(await request.GetResponseAsync());
                string          json;
                using (Stream responseStream = httpResponse.GetResponseStream())
                {
                    json = new StreamReader(responseStream).ReadToEnd();
                }
                TokenResponseModel tokenResponse = JsonConvert.DeserializeObject <TokenResponseModel>(json);
                keyChain.AccessToken = tokenResponse.AccessToken;
                return(true);
            }
            catch (Exception exc)
            {
                LastException        = exc;
                keyChain.AccessToken = null;
                return(false);
            }
        }
Ejemplo n.º 22
0
        public async Task <JsonResult> TokenVerify(string token)
        {
            var verified = true;
            TokenResponseModel tokenResponse = new TokenResponseModel()
            {
                Success = false
            };

            using (var client = _clientFactory.CreateClient())
            {
                var response = await client.GetStringAsync($"{googleRecaptchaVerifyApi}?secret={googleSecretKey}&response={token}");

                tokenResponse = JsonConvert.DeserializeObject <TokenResponseModel>(response);
            }
            // Recaptcha V3 Verify Api send score 0-1. If score is low such as less than 0.5, you can think that it is a bot and return false.
            // If token is not success then return false
            if (!tokenResponse.Success || tokenResponse.Score < (decimal)0.5)
            {
                verified = false;
            }
            return(Json(verified));
        }
Ejemplo n.º 23
0
        public object Login(Login login)
        {
            TokenResponseModel token = new TokenResponseModel();
            string             pass  = Crypto.SHA256(login.Password);

            if (!ModelState.IsValid)
            {
                return(new HttpResponseException(HttpStatusCode.BadRequest).ToString());
            }
            else if (db.Logins.Where(x => x.UserName == login.UserName).ToList().Count() == 0)
            {
                token.AccessToken   = null;
                token.Username      = null;
                token.UserId        = 0;
                token.resultMessage = "Failed";
                token.result        = false;
                return(token);
            }
            else if (db.Logins.Where(x => x.UserName == login.UserName && x.Password == pass).ToList().Count() == 0)
            {
                token.AccessToken   = null;
                token.Username      = null;
                token.UserId        = 0;
                token.resultMessage = "Failed";
                token.result        = false;
                return(token);
            }
            else
            {
                int    id = db.Logins.Where(x => x.UserName == login.UserName).Select(x => x.UserId).Single();
                string s  = JwtManager.GenerateToken(login.UserName);
                token.AccessToken   = s;
                token.Username      = login.UserName;
                token.UserId        = id;
                token.resultMessage = "Successful";
                token.result        = true;
                return(token);
            }
        }
Ejemplo n.º 24
0
        /// <summary>
        /// Gets a Token from the Token Service
        /// </summary>
        /// <param name="authentication">The authentication body</param>
        /// <returns></returns>
        public async Task<TokenResponseModel> GetTokenAsync(AuthenticationModel authentication)
        {
            try
            {
                var response = await this.client.PostAsync<string>(
                    "/token", 
                    TokenCryptoManager.Instance.Encrypt(JsonConvert.SerializeObject(authentication)), 
                    new TextMediaFormatter());

                var tokenResponse = new TokenResponseModel
                {
                    StatusCode = response.StatusCode
                };

                var responseText = await response.Content.ReadAsStringAsync();
                if (response.StatusCode == HttpStatusCode.OK)
                {
                    return new TokenResponseModel
                    {
                        StatusCode = response.StatusCode,
                        AuthToken = responseText
                    };
                }
                else
                {
                    return new TokenResponseModel
                    {
                        StatusCode = response.StatusCode,
                        Message = responseText
                    };
                }
            }
            catch (Exception ex)
            {

                throw ex;
            }
            
        }
Ejemplo n.º 25
0
        public static async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Anonymous, "post")] HttpRequestMessage req, TraceWriter log)
        {
            try
            {
                log.Info("C# HTTP trigger function processed a request.");

                var data = await RequestDecoder.Decode <TokenCreatePostModel>(req);

                var response = new TokenResponseModel
                {
                    id       = data.email,
                    name     = GetName(data.email),
                    iconURL  = Gravatar.GetImageUrl(data.email),
                    password = new Jwt(data.email).Encode()
                };
                return(req.CreateResponse(HttpStatusCode.OK, response));
            }
            catch (HttpResponseException error)
            {
                return(error.Response);
            }
        }
Ejemplo n.º 26
0
        private async void loginButton_Click(object sender, EventArgs e)
        {
            using (var client = new HttpClient())
            {
                client.BaseAddress = this.URI_TOKEN;
                var content = new FormUrlEncodedContent(new[]
                {
                    new KeyValuePair <string, string>("username", this.textBoxUserName.Text),
                    new KeyValuePair <string, string>("password", this.textBoxPassword.Text),
                    new KeyValuePair <string, string>("grant_type", "password")
                });

                var result = client.PostAsync("/Token", content).Result;

                if (result.IsSuccessStatusCode)
                {
                    string jsonMessage;
                    using (Stream responseStream = await result.Content.ReadAsStreamAsync())
                    {
                        jsonMessage = new StreamReader(responseStream).ReadToEnd();
                    }

                    TokenResponseModel tokenResponse = (TokenResponseModel)JsonConvert.DeserializeObject(jsonMessage, typeof(TokenResponseModel));

                    if (tokenResponse != null)
                    {
                        this.parent.Bearer          = tokenResponse.AccessToken;
                        this.parent.StatusLabel     = String.Format("Logged user: {0}", this.textBoxUserName.Text);
                        this.parent.SetAvailability = true;
                        MessageBox.Show(String.Format("Welcome, {0}!", this.textBoxUserName.Text), "Login");
                    }
                }
                else
                {
                    MessageBox.Show(result.ReasonPhrase, "Error");
                }
            }
        }
Ejemplo n.º 27
0
        public async Task <JsonResultData> Login([FromBody] UserLoginModel model)
        {
            var result = await _signInManager
                         .PasswordSignInAsync(model.Email, model.Password, model.RememberMe, lockoutOnFailure : false);

            if (result.Succeeded)
            {
                var user = await _customerService.GetUserByTermAsync(model.Email);

                var token = GenerateToken(user);

                var tokenResponse = new TokenResponseModel
                {
                    User        = user,
                    AccessToken = token,
                    ExpiresIn   = (int)TimeSpan.FromDays(1).TotalSeconds
                };

                return(JsonResultData.Success(tokenResponse));
            }

            return(JsonResultData.Error("Username or password isn't correct."));
        }
Ejemplo n.º 28
0
        public async Task <TokenResponseModel> SignInAsync(UserSignInModel signInModel)
        {
            var user = await _userManager.FindByNameAsync(signInModel.Email);

            if (user is null)
            {
                throw new CustomExeption(Constants.Error.LOGIN_FAILD_NO_USER_WITH_THIS_EMAIL,
                                         StatusCodes.Status400BadRequest);
            }

            var signIn = await _signInManager.PasswordSignInAsync(signInModel.Email, signInModel.Password, false, false);

            if (!signIn.Succeeded)
            {
                throw new CustomExeption(Constants.Error.LOGIN_FAILD_WRONG_PASSWORD, StatusCodes.Status400BadRequest);
            }

            var roleList = await _userManager.GetRolesAsync(user);

            if (roleList is null)
            {
                throw new Exception($"{Constants.Error.ERROR_NO_USERROLE} {StatusCodes.Status500InternalServerError}");
            }

            bool isRoleAdmin = roleList.Any(s => s.Contains("admin"));

            var result = new TokenResponseModel();

            if (isRoleAdmin)
            {
                result.AccessToken = _jwtProvider.GenerateJwt(signInModel.Email, "admin");
                return(result);
            }

            result.AccessToken = _jwtProvider.GenerateJwt(signInModel.Email, "user");
            return(result);
        }
Ejemplo n.º 29
0
        public async Task <IActionResult> Token([FromBody] AuthorizationCodeGrantRequestModel model)
        {
            if ("authorization_code".Equals(model.GrantType, StringComparison.OrdinalIgnoreCase))
            {
                var message = new AccessTokenRequestMessage(model.Code)
                {
                    ClientId     = model.ClientId,
                    ClientSecret = model.ClientSecret,
                    Code         = model.Code,
                    RedirectUri  = model.ClientSecret
                };
                var result = await _sagaBus.SendAsync <AccessTokenRequestMessage, OAuth20Result>(message);

                switch (result.State)
                {
                case OAuth20State.AuthorizationCodeGenerated:
                    return(BadRequest());

                case OAuth20State.Finished:
                    return(Ok(TokenResponseModel.FromOAuth20Result(result)));
                }
            }
            return(BadRequest());
        }
Ejemplo n.º 30
0
        public async Task GivenTokenRequest_WhenGetToken_ThenGetTokenSuccessful()
        {
            //?Given
            var request      = new TokenRequestModel();
            var tokenReponse = new TokenResponse();
            var expected     = new TokenResponseModel();

            _tokenManager.Setup(x => x.GetToken(It.IsAny <TokenRequest>()))
            .ReturnsAsync(tokenReponse)
            .Verifiable();

            _mapper.Setup(x => x.Map <TokenResponseModel>(tokenReponse))
            .Returns(expected);

            //?When
            var actual = await _authController.GetToken(request);

            //?Then
            Assert.IsAssignableFrom <OkObjectResult>(actual);
            Assert.Equal(((OkObjectResult)actual).Value, expected);

            _tokenManager.Verify();
            _mapper.Verify();
        }
        public TokenResponseModel SignIn(string username)
        {
            var accessToken = new AccessTokenModel()
            {
                Token     = CreateAccessToken(username),
                TokenType = "bearer",
                ExpiresIn = ExpirationTimeInSeconds
            };

            var refreshToken = new RefreshTokenModel()
            {
                Token = GetNewRefreshToken(username)
            };

            _refreshTokens.Add(refreshToken);

            var response = new TokenResponseModel()
            {
                AccessToken  = accessToken,
                RefreshToken = refreshToken.Token
            };

            return(response);
        }
Ejemplo n.º 32
0
 public void OnAuthenticated(TokenResponseModel tokenResponse)
 {
     Console.WriteLine("User authenticated");
     bearerToken = "Bearer " + tokenResponse.AccessToken;
 }