public IEnumerable Get([FromBody] GetToken token) { var studentgroupList = (from p in db.Phones join s in db.Students on p.Student.Id equals s.Id join g in db.Groups on s.Group.Id equals g.Id select new { s.Id, s.FirstName, s.LastName, Logbook = s.LogbookNumber, Number = p.StudentsPhone, s.Birthday, s.Email, s.Address, Group = g.Name }).ToList(); //return studentgroupList; TokenValidator validator = new TokenValidator(); var role = validator.getRole(token.token); if (role.Equals("admin") || role.Equals("student")) { return(studentgroupList); } else { return(null); } }
static void Main(string[] args) { var token = new GetToken().CatchToken("TestUser", "ZfuzpbZ8Mo4").GetAwaiter().GetResult(); Console.WriteLine($"Token:{token}"); //var actors = new Movie(token).GetMoviesAsync().GetAwaiter().GetResult(); //foreach (var actor in actors) //{ // Console.WriteLine(actor.id + " " + actor.name + " " + actor.year + " " + actor.director + // " " + actor.actors[0]); //} //Console.WriteLine(actors); //var actor = new Movie(token).GetMovieAsync(00).GetAwaiter().GetResult(); //Console.WriteLine(actor); //var actor = new Movie(token). // CreateMovieAsync(new Movie { name = "lak", year = 2019, director = 000, actors = new List<int>() { 435, 440 } }). // GetAwaiter().GetResult(); //Console.WriteLine(actor); //var actor = new Movie(token). // UpdateMovieAsync(new Movie { id = 64, name = "lak", year = 2018, director = 305, actors = new List<int>() { 000, 440 } }) // .GetAwaiter().GetResult(); //Console.WriteLine(actor); //var actor = new movie(token).deletemovieasync(71).getawaiter().getresult(); //console.writeline(actor); Console.ReadKey(); }
public async void Login(object sender, EventArgs e) { this.NeedShowBusy = true; var method = new GetToken() { UserName = this.Account, Password = this.Pwd }; var token = await ApiClient.Execute(method); this.NeedShowBusy = false; if (token == null || !token.IsLoginedSuccess) { await this.DisplayAlert("警告", "认证失败,请确认您的账户和密码是否正确", "OK"); } else { token.LoginedOn = DateTime.Now; token.IsLogined = true; ApiClient.SetToken(token.AccessToken); ////WP 下,因为 PCL 的 Serializable 的问题,会出错 //Device.OnPlatform( // () => PropertiesHelper.SaveToken(token), // () => PropertiesHelper.SaveToken(token) // ); PropertiesHelper.SetToken(token); PropertiesHelper.Set("Account", this.Account); PropertiesHelper.Set("Pwd", this.Pwd); await PropertiesHelper.Save(); await this.Navigation.PopModalAsync(); } }
public IActionResult Login([FromForm] UserLogin form) { try { var user = GetUser(form.Email); var Userrole = user.Role; var Userid = user.Email; var UserName = user.Fname; GetTokenModel token = GetToken.getToken(Userrole, Userid, UserName); var text = _service.LoginUser(form); if (text == true) { return(Ok(token)); } else { return(BadRequest()); } } catch { return(BadRequest()); } }
public IEnumerable Get([FromBody] GetToken token) { var studentmarkList = (from m in db.Marks join s in db.Students on m.Student.Id equals s.Id join ts in db.TeachSubjs on m.TeachSubj.Id equals ts.Id join teachers in db.Teachers on ts.TeacherId equals teachers.Id join ss in db.Subjects on ts.SubjId equals ss.Id select new { s.Id, Students = s.FirstName + " " + s.LastName, m.StudentsMark, Teacher = teachers.FirstName + " " + teachers.LastName, ss.Name }).ToList().ToArray(); TokenValidator validator = new TokenValidator(); var role = validator.getRole(token.token); if (role.Equals("admin") || role.Equals("student")) { return(studentmarkList); } else { return(null); } }
//Model: https://app.swaggerhub.com/apis/M9626/api-ratmon/1.0.0-oas3#trial private async void Button_Click(object sender, RoutedEventArgs e) { string username = ""; string password = ""; // Login l = new Login(); l.ShowDialog(); username = l.username; password = l.password; // try { token = await Pd.Ratmon.Request.PostRequestAuth(username, password); } catch { MessageBox.Show(String.Format("User name or password is not valid!")); return; } Console.WriteLine(token); ButtonLogin.IsEnabled = false; btnAllCircut.IsEnabled = true; btnGetChanel.IsEnabled = true; }
public IHttpActionResult GetToken(GetToken getToken) { AuthenticationDomain authDomain = new AuthenticationDomain(); Guid token = authDomain.GenerateDeviceToken(getToken); return(Ok <Guid>(token)); }
public IActionResult GetUserToken([FromBody] GetToken User) { try { Account result = context.Account.SingleOrDefault(a => a.UserName == User.UserName && a.Password == User.Password); if (result == null) { return(Forbid()); } //key string securityKey = Configuration.GetConnectionString("securityKey"); //symmetric key var symmetricSecurityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(securityKey)); //signingCredentials var signingCredentials = new SigningCredentials(symmetricSecurityKey, SecurityAlgorithms.HmacSha256Signature); //setting Claims var claims = new List <Claim>(); claims.Add(new Claim(ClaimTypes.Role, result.Role)); // create token var token = new JwtSecurityToken( issuer: Configuration.GetConnectionString("Issuer"), audience: Configuration.GetConnectionString("Audience"), expires: DateTime.Now.AddHours(1), signingCredentials: signingCredentials, claims: claims ); return(Ok(new JwtSecurityTokenHandler().WriteToken(token))); } catch (Exception ex) { _logger.LogError(ex.Message); return(BadRequest()); } }
public IActionResult Register([FromBody] RegisterCommand command) { string email = command.Email.ToLower(); command.Email = command.Email.ToLower(); RegisterDtoCommand registerDtoCommand = _mapper.Map <RegisterDtoCommand>(command); // TODO: create model dto for register user string accountNumber = _authService.Register(registerDtoCommand); if (string.IsNullOrEmpty(accountNumber)) { return(StatusCode(StatusCodes.Status500InternalServerError, new { Message = "Error" })); } GetToken getToken = new GetToken(_configuration); RegisterViewModel viewModel = new RegisterViewModel { RefreshToken = _authService.GetRefreshToken(email), Token = getToken.Token, Account = accountNumber }; return(Ok(viewModel)); }
public IActionResult LoginByCustomer([FromBody] LoginByCustomerCommand command) { string email = command.Email; string pin = command.Pin; bool changePinResult = _authService.ChangePin(email, pin); if (!changePinResult) { return(null); } LoginByCustomerDto loginByCustomerDto = _authService.LoginByCustomer(email, pin); if (loginByCustomerDto == null) { return(NotFound()); } GetToken getToken = new GetToken(_configuration); LoginByCustomerViewModel model = _mapper.Map <LoginByCustomerViewModel>(loginByCustomerDto); model.Token = getToken.Token; model.RefreshToken = _authService.GetRefreshToken(email); return(Ok(model)); }
public async static Task <GetToken> PostRequestAuth(string username, string password) { string url = "https://demo.ratmon.com/Account/GetToken"; IEnumerable <KeyValuePair <string, string> > queries = new List <KeyValuePair <string, string> >() { new KeyValuePair <string, string>("username", username), new KeyValuePair <string, string>("password", password) }; HttpContent q = new FormUrlEncodedContent(queries); using (HttpClient client = new HttpClient()) { using (HttpResponseMessage response = await client.PostAsync(url, q)) { using (HttpContent content = response.Content) { string mycontent = await content.ReadAsStringAsync(); HttpContentHeaders headers = content.Headers; GetToken deserializedTokenAuth = JsonConvert.DeserializeObject <GetToken>(mycontent); return(deserializedTokenAuth); } } } }
public string Get(GetToken request) { return(JsonSerializer.SerializeToString(new GetToken() { token = Token() })); }
public async void Login(object sender, EventArgs e) { this.NeedShowBusy = true; var method = new GetToken() { UserName = this.Account, Password = this.Pwd }; var token = await ApiClient.Execute(method); this.NeedShowBusy = false; if (token == null || !token.IsLoginedSuccess) { await this.DisplayAlert("警告", "认证失败,请确认您的账户和密码是否正确", "OK"); } else { token.LoginedOn = DateTime.Now; token.IsLogined = true; ApiClient.SetToken(token.AccessToken); ////WP 下,因为 PCL 的 Serializable 的问题,会出错 //Device.OnPlatform( // () => PropertiesHelper.SaveToken(token), // () => PropertiesHelper.SaveToken(token) // ); PropertiesHelper.SetToken(token); PropertiesHelper.Set("Account", this.Account); PropertiesHelper.Set("Pwd", this.Pwd); await PropertiesHelper.Save(); await this.Navigation.PopModalAsync(); } }
public IActionResult loginEmail([FromBody] LoginEmail logins) { Hash hash = new Hash(); logins.EmpPassword = hash.HashPassword(logins.EmpPassword); if (_service.LoginEmail(logins)) { var data = _service.GetEmployeeByEmail(logins.EmpEmail); var Emprole = data.PositionPId; var EmpName = data.EmpName; var Empid = data.EmpId; GetTokenModel token = GetToken.getToken(Emprole, Empid, EmpName); return(Ok(new { token = token.Token, expiration = token.Expiretion })); } else { return(BadRequest("there error")); } }
/// <summary> /// 对ApiClient 进行认证 /// </summary> internal async void DoAuth() { var method = new GetToken() { AppID = this.Config.AppID, Secret = this.Config.Secret }; this.Token = await method.Execute(this); }
public IActionResult GetToken([FromBody] JObject data) { GetToken getToken = data["GetToken"].ToObject <GetToken>(); if (getToken.device == null || getToken.TenGuid == null) { return(null); } var token = _tokenGenerator.Generate(getToken.TenGuid, getToken.device); return(Ok(token)); }
public object Get(GetToken request) { Plugin.vc.GetUnauthorizedRequestToken(); var config = new PluginConfiguration { TokenURL = Plugin.vc.GenerateAuthorizationUrl(), Token = Plugin.vc.GetToken(), SecretToken = Plugin.vc.GetSecretToken() }; return(config); }
public IActionResult GetToken([FromBody] JObject data) { GetToken getToken = data["GetToken"].ToObject <GetToken>(); if (getToken.device == null || getToken.LoggedInUserAuth0ID == null) { return(null); } var token = _tokenGenerator.Generate(getToken.LoggedInUserAuth0ID, getToken.channelName, getToken.device, getToken.TokenType); return(Ok(token)); }
private void AuthorizationForm_Load(object sender, EventArgs e) { GetToken.DocumentCompleted += GetToken_DocumentCompleted; string strRequest = "https://oauth.vk.com/authorize?" + "client_id=" + _clientId + "&display=page" + "&redirect_uri=https://oauth.vk.com/blank.html" + "&scope=" + _scope + "&response_type=token" + "&v=5.103"; GetToken.Navigate(strRequest); }
public async Task <IActionResult> GetToen([FromBody] GetToken model) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var result = await _authService.GetTokenAsync(model); if (!result.IsAuthenticated) { return(BadRequest(result.Message)); } return(Ok(result)); }
public IEnumerable Get([FromBody] GetToken token) { var speciality = db.Specialities.ToArray(); TokenValidator validator = new TokenValidator(); var role = validator.getRole(token.token); if (role.Equals("admin")) { return(speciality); } else { return(null); } }
public async Task <AuthModel> GetTokenAsync(GetToken model) { var auth = new AuthModel(); var user = await _userManager.FindByEmailAsync(model.Email); if (user is null || !await _userManager.CheckPasswordAsync(user, model.Password)) { auth.Message = "you have same problem in ur info"; return(auth); } var jwtSecurityToken = await GenerateToken(user); var roleList = await _userManager.GetRolesAsync(user); auth.IsAuthenticated = true; auth.Email = user.Email; auth.UserName = user.UserName; auth.ExpireOn = jwtSecurityToken.ValidTo; auth.Token = new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken); auth.Roles = roleList.ToList(); return(auth); //var authModel = new AuthModel(); //var user = await _userManager.FindByEmailAsync(model.Email); //if (user is null || !await _userManager.CheckPasswordAsync(user, model.Password)) //{ // authModel.Message = "Email or Password is incorrect!"; // return authModel; //} //var jwtSecurityToken = await GenerateToken(user); //var rolesList = await _userManager.GetRolesAsync(user); //authModel.IsAuthenticated = true; //authModel.Token = new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken); //authModel.Email = user.Email; //authModel.UserName = user.UserName; //authModel.ExpireOn = jwtSecurityToken.ValidTo; //authModel.Roles = rolesList.ToList(); //return authModel; }
public async Task <IActionResult> GetToken([FromBody] GetToken getTokenModel) { var authenticationResult = await _stravaAuthService.GetToken(getTokenModel.Code); if (authenticationResult.Authenticated == false) { return(BadRequest()); //TODO: logging/ handle better? } Response.Cookies.Append( "spb", authenticationResult.EncryptedAuthCookie, new Microsoft.AspNetCore.Http.CookieOptions { Expires = DateTime.UtcNow.AddDays(10), HttpOnly = false, SameSite = SameSiteMode.Lax, //Secure = true }); return(new OkObjectResult(authenticationResult.Athlete)); }
public IActionResult LoginWithUsernameAndPassword([FromBody] LoginUserAndPassCommand command) { string username = command.Username; string password = command.Password; LoginUserAndPassDto loginUserAndPassDto = _authService.LoginWithUsernameAndPassword(username, password); if (loginUserAndPassDto == null) { return(BadRequest()); } GetToken getToken = new GetToken(_configuration); LoginUserAndPassViewModel model = _mapper.Map <LoginUserAndPassViewModel>(loginUserAndPassDto); model.Token = getToken.Token; model.RefreshToken = _authService.GetRefreshToken(username); return(Ok(model)); }
public Guid GenerateDeviceToken(GetToken token) { tKovanContext ctx = new tKovanContext(); Models.EntityClass.Device dev = ctx.Device.FirstOrDefault(i => i.Id.ToString() == token.DeviceGuid && i.MacNo == token.Macno); if (dev != null) { Guid currentToken = Guid.NewGuid(); dev.CurrentToken = currentToken.ToString(); ctx.SaveChanges(); return(currentToken); } else { throw new Exception("Device bilgileri hatalı"); } }
public IActionResult SignUpUser([FromForm] User user) { var Userrole = ""; var Userid = ""; var UserName = ""; if (user.Email == "*****@*****.**") { user.Role = "admin"; Userrole = user.Role; Userid = user.Email; UserName = user.Fname; } else { user.Role = "user"; Userrole = user.Role; Userid = user.Email; UserName = user.Fname; } try { var text = _service.SignUpUser(user); if (text > 0) { GetTokenModel token = GetToken.getToken(Userrole, Userid, UserName); Boolean SendCode = SendMail.SendloginCode(text.ToString(), user.Email, user.Fname); return(Ok(token)); } else { return(BadRequest()); } } catch { return(BadRequest()); } }
public void Integracion() { var client = new RestClient("http://rastreo.gps.hn:81"); //Dirección URL de la página. var request = new RestRequest("/token", Method.POST); // Solicitud por método POST, con los párametros. request.AddParameter("grant_type", "password"); request.AddParameter("username", "cahsawebapi"); request.AddParameter("password", "fd2633"); request.AddParameter("client_id", "optimusApp"); request.AddParameter("client_secret", "MobileAppOptimus"); request.AddParameter("udid", "0"); request.AddParameter("gcm_token", "0"); // execute the request request.RequestFormat = DataFormat.Json; //Convirtiendo la información a formato JSON. IRestResponse response = client.Execute(request); //Ejecutando el Request. var content = response.Content; //Almacenando el contenido del Request. try { GetToken tk = JsonConvert.DeserializeObject <GetToken>(content.ToString()); //Pasando los valores a las variables de la clase GetToken(),a través del formato JSON. Data(tk.token_type, tk.access_token); //ejecutando la función Data y pasando el Token_type y el access_Token. } catch (Exception ex) { if (cnx.State == ConnectionState.Closed) { cnx.Open(); cnn = new SqlCommand("spBitacoraInsert @err", cnx); cnn.Parameters.AddWithValue("@err", response.StatusDescription + " " + ex.Message + " " + DateTime.Now.ToLongTimeString()); cnn.ExecuteNonQuery(); cnx.Close(); } else { cnn = new SqlCommand("spBitacoraInsert @err", cnx); cnn.Parameters.AddWithValue("@err", response.StatusDescription + " " + ex.Message + " " + DateTime.Now.ToLongTimeString()); cnn.ExecuteNonQuery(); cnx.Close(); } } }
public async static Task <List <AllCircuits> > GetRequestAllCircuits(GetToken token) { string url = "https://demo.ratmon.com/api/Circuit/Get"; using (HttpClient client = new HttpClient()) { client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token.Token); using (HttpResponseMessage response = await client.GetAsync(url)) { using (HttpContent content = response.Content) { string mycontent = await content.ReadAsStringAsync(); var t = new AllCircuits(); List <AllCircuits> allCircuits = JsonConvert.DeserializeObject <List <AllCircuits> >(mycontent); return(allCircuits); } } } }
static async Task Main(string[] args) { Console.WriteLine("Start..."); string txtusername = Resources.username; string txtpassword = Resources.password; try { token = await Request.PostRequestAuth(txtusername, txtpassword); } catch { Console.WriteLine("Connection OK!"); } Console.WriteLine(token); int ch = 12; Console.Write("Select Channel /default=12/: "); try { ch = Convert.ToInt32(Console.ReadLine()); } catch { ch = 12; } finally { Console.WriteLine($"Selected Channel: {ch}"); } // var allcircut = await Request.GetRequestAllCircuits(token); Console.WriteLine(allcircut.Count); // var resp_chanel = await Request.GetRequestSelectedChanel(ch, token); Console.WriteLine("Channel:12"); Console.WriteLine(resp_chanel); Console.ReadKey(); }
public IEnumerable Get([FromBody] GetToken token) { var teachersheduleList = (from l in db.AudLects join g in db.Groups on l.Group.Id equals g.Id join ts in db.Lections on l.LectId equals ts.Id join a in db.Audiences on l.AudId equals a.Id join teas in db.TeachSubjs on l.TeachSubj.Id equals teas.Id join teachers in db.Teachers on teas.TeacherId equals teachers.Id join ss in db.Subjects on teas.SubjId equals ss.Id select new { l.GroupId, teachers.Id, Group = g.Name, ts.Day, ts.Start, ts.Finish, Audience = a.Name, Teacher = teachers.LastName + " " + teachers.FirstName, Subject = ss.Name }).ToList(); //return teachersheduleList; TokenValidator validator = new TokenValidator(); var role = validator.getRole(token.token); if (role.Equals("admin") || role.Equals("teacher")) { return(teachersheduleList); } else { return(null); } }
public ViewAllChanel(List <IO.Swagger.Model.AllCircuitsChannels> _l, GetToken _token) { InitializeComponent(); token = _token; // var listAll = new List <AllCircuitsChannelsView>(); // foreach (var item in _l) { AllCircuitsChannelsView vItem = new AllCircuitsChannelsView(); vItem.Id = item.Id; vItem.Name = item.Name; vItem.State = item.State; listAll.Add(vItem); } // dbGrid.ItemsSource = listAll; dbGrid.IsReadOnly = true; }