private void OnLogIn(object sender, AccessTokenModel token) { Device.BeginInvokeOnMainThread(async() => { await this.Navigation.PushAsync(new CalendarPage(token)); }); }
public static void AddMerchantID(string merchantId, AccessTokenModel data) { WithConnection(conn => { AddMerchantID(merchantId, data, conn); }); }
/// <summary> /// 获取每次操作微信API的Token访问令牌 /// </summary> /// <returns></returns> public static MD_AccessTokenResult GetAccessToken() { string url = ConfigurationManager.AppSettings["hxurl"] + "/token"; //正常情况下access_token有效期为7200秒,这里使用缓存设置短于这个时间即可 MD_AccessTokenResult access_token = MemoryCacheHelper.GetCacheItem <MD_AccessTokenResult>("hxaccess_token", delegate() { MD_AccessTokenResult result = new MD_AccessTokenResult(); string data = "{\"grant_type\": \"client_credentials\",\"client_id\":\"YXA6TSjk4EBLEeekxD1y9NWlTg\",\"client_secret\":\"YXA6RPwUCNQ97-WoQG1-8_ChwTQ1bhs\"}"; string jsonStr = WebHelper.GetHXRequestData(url, "post", "", false, data); if (jsonStr.Contains("error")) { ErrorMsg errorResult = new ErrorMsg(); errorResult = JsonConvert.DeserializeObject <ErrorMsg>(jsonStr); result.ErrorResult = errorResult; result.Result = false; } else { AccessTokenModel model = new AccessTokenModel(); model = JsonConvert.DeserializeObject <AccessTokenModel>(jsonStr); result.SuccessResult = model; result.Result = true; } return(result); }, new TimeSpan(0, 0, 5100000)//过期 ); return(access_token); }
public CalendarViewModel(AccessTokenModel token) { var googleApiService = new GoogleApiService(token); this.EventsListViewModel = new EventsListViewModel(googleApiService); this.AddEventViewModel = new AddEventViewModel(googleApiService); }
private async Task <AccessTokenModel> PerformCodeExchangeAsync(string code, Auth0UserInfo auth0UserInfo, ILogger logger, CancellationToken cancellationToken) { logger.LogInformation($"Exchanging authorization code '{code}' for tokens for client {auth0UserInfo.UserId} {auth0UserInfo.Name}..."); ExchangeTokenModel exchangeTokenModel = new ExchangeTokenModel() { ClientId = _configuration["Strava:ClientId"], ClientSecret = _configuration["Strava:ClientSecret"], AuthorizationCode = code }; var json = JsonConvert.SerializeObject(exchangeTokenModel); HttpResponseMessage response = await _httpClient.PostAsync(new Uri($"https://www.strava.com/oauth/token"), new StringContent(json, Encoding.UTF8, "application/json"), cancellationToken); response.EnsureSuccessStatusCode(); string responseBody = await response.Content.ReadAsStringAsync(); logger.LogInformation($"Received token response from Strava: '{responseBody}'"); AccessTokenModel accessTokenModel = JsonConvert.DeserializeObject <AccessTokenModel>(responseBody); logger.LogInformation($"Parsed Access token: '{accessTokenModel.AccessToken}', expires at '{accessTokenModel.ExpiresAt}'"); return(accessTokenModel); }
public async Task <GetCharactersCharacterIdCalendarEventIdOk[]> GetMails(AccessTokenModel accessToken) { HttpClient client = new HttpClient(); client.DefaultRequestHeaders.Add("Authorization", $"Bearer {accessToken.AccessToken}"); client.DefaultRequestHeaders.Add("User-Agent", "eve-calendar-ical"); HttpResponseMessage responseMessage = await client.GetAsync($"http://esi.evetech.net/latest/characters/{accessToken.CharacterId}/calendar?token=" + accessToken.AccessToken); if (responseMessage.IsSuccessStatusCode) { var response = JsonConvert.DeserializeObject <List <GetCharactersCharacterIdCalendar200Ok> >(await responseMessage.Content.ReadAsStringAsync()); var mails = response.Select(async x => { HttpResponseMessage _responseMessage = await client.GetAsync($"http://esi.evetech.net/latest/characters/{accessToken.CharacterId}/calendar/{x.EventId}/"); return(JsonConvert.DeserializeObject <GetCharactersCharacterIdCalendarEventIdOk>(await _responseMessage.Content.ReadAsStringAsync())); }); return(await Task.WhenAll(mails)); } else { Console.WriteLine(await responseMessage.Content.ReadAsStringAsync()); return(new GetCharactersCharacterIdCalendarEventIdOk[0]); } }
/// <summary> /// Send request for generate token using Owin /// </summary> /// <param name="tokenUrl"></param> /// <param name="requestDetails"></param> /// <returns></returns> public static AccessTokenModel HttpPost(string tokenUrl, string requestDetails) { AccessTokenModel token = null; try { WebRequest webRequest = WebRequest.Create(tokenUrl); webRequest.ContentType = CONTENT_TYPE; webRequest.Method = POST_METHOD; byte[] bytes = Encoding.ASCII.GetBytes(requestDetails); webRequest.ContentLength = bytes.Length; using (Stream outputStream = webRequest.GetRequestStream()) { outputStream.Write(bytes, 0, bytes.Length); } using (WebResponse webResponse = webRequest.GetResponse()) { StreamReader newstreamreader = new StreamReader(webResponse.GetResponseStream()); string newresponsefromserver = newstreamreader.ReadToEnd(); newresponsefromserver = newresponsefromserver.Replace(".expires", "expires").Replace(".issued", "issued"); token = Newtonsoft.Json.JsonConvert.DeserializeObject <AccessTokenModel>(newresponsefromserver);// new JavaScriptSerializer().Deserialize<AccessToken>(newresponsefromserver); } } catch (Exception ex) { Console.WriteLine(ex.Message); token = null; } return(token); }
/// <summary> /// Initialize the token synchronously based on the auth url code. /// </summary> /// <param name="code"></param> public override void InitAccessToken(string code) { IRestRequest request = new RestRequest(Method.POST); request = AddAccessTokenParams(request, code); Token = Execute <AccessTokenModel>(request, AccessTokenUrl); }
public bool updateAccessToken() { SortedDictionary <string, string> ParamList = new SortedDictionary <string, string>(); ParamList.Add("oauth_consumer_key", this._consumerKey); ParamList.Add("oauth_nonce", GetRandomString(8)); ParamList.Add("oauth_timestamp", GetTimeStamp()); ParamList.Add("oauth_version", this.oauth_version); ParamList.Add("oauth_signature_method", this.oauth_signature_method); ParamList.Add("oauth_token", this._access_temple_token); string SourceString = GetApiSourceString(this.accessTokenUrl, ParamList); string SecretKey = this._consumerSecret + "&" + this._access_temple_secret; string Sign = GetSignature(SourceString, SecretKey); ParamList.Add("oauth_signature", Sign); string URL = this.accessTokenUrl + "?" + ParamToUrl(ParamList, false); object jsonAccess = GetGeneralContent(URL); XmlNode node = JsonHelper.DeserializeToXmlNode(jsonAccess.ToString()); AccessTokenModel newToken = new AccessTokenModel(); newToken.AccessToken = node.ChildNodes[0].SelectSingleNode("oauth_token").InnerText; newToken.AccessTokenSecret = node.ChildNodes[0].SelectSingleNode("oauth_token_secret").InnerText; WriteLocalAccessToken(newToken); return(true); }
public void ValidateCDKey(AccessTokenModel token) { string cacheKey = "EBS.AccessToken.All"; var accessTokens = _cacheManager.Get(cacheKey, () => { return(_db.Table.FindAll <AccessToken>()); }); MD5 md5Prider = MD5.Create(); string clientCDKEY = string.Format("{0}{1}{2}", token.StoreId, token.PosId, token.CDKey); //加密 string clientCDKeyMd5 = md5Prider.GetMd5Hash(clientCDKEY); // var entity= _db.Table.Find<AccessToken>(n=>n.CDKey==clientCDKeyMd5); var entity = accessTokens.FirstOrDefault(n => n.CDKey == clientCDKeyMd5); if (entity == null) { throw new Exception("cdkey 不存在"); } if (entity.StoreId == token.StoreId && entity.PosId == token.PosId) { //匹配成功,返回 } else { throw new Exception("cdkey 错误"); } }
public AccessTokenModel GetAccessToken() { AccessTokenModel accessToken = new AccessTokenModel(); accessToken.AccessToken = _accessToken; return(accessToken); }
public AccessTokenModel GetToken(LoginModel objuser, string apiurl) { AccessTokenModel tokenData = new AccessTokenModel(); try { HttpResponseMessage oHttpResponseMessage = new HttpResponseMessage(); using (var client = new HttpClient()) { client.BaseAddress = new Uri(baseURL); var content = new StringContent(JsonConvert.SerializeObject(objuser), Encoding.UTF8, "application/json"); var responseTask = client.PostAsync(apiurl, content);//"/api/LoginAuth/login" responseTask.Wait(); oHttpResponseMessage = responseTask.Result; } if (oHttpResponseMessage.IsSuccessStatusCode) { string jsonResult = oHttpResponseMessage.Content.ReadAsStringAsync().Result; tokenData = JsonConvert.DeserializeObject <AccessTokenModel>(jsonResult); } } catch (Exception ex) { throw ex; } return(tokenData); }
public async Task <UserSession> Login(UserAccountViewModel user, AccessTokenModel token) { // Saved Session string cmd = $@"INSERT INTO `user_access_token` (`user_id`, `access_token`, `login_date`, `expired_date`) VALUES ({user.Id}, '{token.AccessToken}', '{token.LoginDate.ToString("yyyy-MM-dd HH:mm-ss")}', '{token.ExpiredDate.ToString("yyyy-MM-dd HH:mm-ss")}'); SELECT LAST_INSERT_ID();"; var sessionId = (await DALHelper.ExecuteQuery <long>(cmd, dbTransaction: DbTransaction, connection: DbConnection)).First(); return(new UserSession() { LoginResult = 0, SessionId = sessionId, UserName = user.UserName, Email = user.Email, IsSuperAdmin = user.IsSuperAdmin, IsUsed = user.IsUsed, Id = user.Id, Roles = user.Roles.Select(r => r.Name).ToList(), AccessToken = token.AccessToken }); }
public async Task <IActionResult> AADCallback(string code, string state, string error, string error_description) { if (!string.IsNullOrEmpty(error) && !string.IsNullOrEmpty(error_description)) { throw new Exception($"AADLogin Error: {error} => {error_description.Split('\r').FirstOrDefault()}"); } AccessTokenModel accessToken = await GetAADAccessToken(code); if (string.IsNullOrEmpty(accessToken.Error)) { throw new Exception($"{accessToken.Error} => {accessToken.ErrorDescription}"); } MeModel me = await GetAADMe(accessToken.AccessToken); if (me.Error != null) { throw new Exception($"{me.Error.Code} => {me.Error.Message}"); } var user = authManager.SignInAAD(me.UserPrincipalName); if (user == null) { throw new Exception("User not found!"); } await CreateAuthCookie(user, true); return(RedirectToAction("Index", "Home")); }
public void LogAccessToken(AccessTokenModel accessToken) { var apiUrl = baseRoute + "/logAccessToken"; communicationManager = new CommunicationManager(ApplicationSettings.Token, AuthContext.Auth.Token.Token); communicationManager.Post <AccessTokenModel, int>(accessToken, apiUrl); }
public async Task <AccessTokenModel> Get(ClaimsPrincipal identity) { if (!identity.IsAuthenticated()) { return(new AccessTokenModel()); } var claims = new[] { new Claim(JwtRegisteredClaimNames.Sub, identity.FindFirstValue(ClaimTypes.NameIdentifier)), new Claim(JwtRegisteredClaimNames.Jti, await _jwtOptions.JtiGenerator()), new Claim(JwtRegisteredClaimNames.Iat, _jwtOptions.IssuedAt.ToUnixEpochDate().ToString(), ClaimValueTypes.Integer64), identity.FindFirst(ClaimTypes.Name) }.Concat(identity.FindAll(ClaimTypes.Role)).Where(x => x != null).ToArray(); // Create the JWT security token and encode it. var jwt = new JwtSecurityToken( _jwtOptions.Issuer, _jwtOptions.Audience, claims, _jwtOptions.NotBefore, _jwtOptions.Expiration, _jwtOptions.SigningCredentials); var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt); // Serialize and return the response var response = new AccessTokenModel { Token = encodedJwt, Expiration = _jwtOptions.Expiration }; return(response); }
public TokenResponseModel SignIn(string username) { var accessToken = new AccessTokenModel() { Token = CreateAccessToken(username), TokenType = "bearer", ExpiresIn = ExpirationTimeInSeconds }; var refreshToken = new RefreshTokenModel() { Token = CreateRefreshToken(username), IsRevoked = false, User = username }; _refreshTokens.Add(refreshToken); var response = new TokenResponseModel() { AccessToken = accessToken, RefreshToken = refreshToken.Token }; return(response); }
internal Task <string> PostRequestAsync <T>(ClientConfig config, T model, AccessTokenModel token) { Task <string> result = null; using (HttpClient client = new HttpClient()) { try { SetSecurityProtocol(config.ProtocolType); var jsonContent = JsonConvert.SerializeObject(model); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); AddCustomHeaders(client, config.CustomHeaders); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(token.token_type, token.access_token); var byteContent = CreateBinaryContent(jsonContent); Task <HttpResponseMessage> response = client.PostAsync(config._targetUri, byteContent); response.Result.EnsureSuccessStatusCode(); result = response.Result.Content.ReadAsStringAsync(); } catch (HttpRequestException e) { throw e; } } return(result); }
public static void AddTokens(AccessTokenModel data) { WithConnection(conn => { UpdateRecord(data, conn); }); }
/// <summary> /// 获取接口调用凭据 /// </summary> /// <returns></returns> public static string GetAccessToken() { string url = "https://api.weixin.qq.com/cgi-bin/token"; url += "?grant_type=client_credential"; url += "&appid=" + Wx.Config.AppID; url += "&secret=" + Wx.Config.AppSecret; var res = new HttpUtil( ).Get(url); Log.Logger.Log("[wx: GetAccessToken] " + url + "#" + res); try { AccessTokenModel wx_token = JsonUtil.FromJson <AccessTokenModel>(res); if (wx_token != null && wx_token.errcode == 0) { return(wx_token.access_token); } else { Log.Logger.Log("[wx: GetAccessToken Failed] " + url + "#" + res); return(null); } } catch (Exception ex) { Log.Logger.Log("[wx: GetAccessToken Exception] " + url + "#" + ex.Message); return(null); } }
private void getRefereshToken(AccessTokenModel model, Action <AccessTokenModel> callback) { var data = new List <KeyValuePair <string, string> >(); data.Add(new KeyValuePair <string, string>("grant_type", model.grant_type)); data.Add(new KeyValuePair <string, string>("code", model.code)); data.Add(new KeyValuePair <string, string>("redirect_uri", "https://dev.mdcnordic.com/MobilPayService/MobilePayIndex/redirect/")); data.Add(new KeyValuePair <string, string>("code_verifier", model.code_verifier)); data.Add(new KeyValuePair <string, string>("client_id", "mdcnordic")); data.Add(new KeyValuePair <string, string>("client_secret", model.client_secret)); HttpContent content = new FormUrlEncodedContent(data); string jsonContent = content.ReadAsStringAsync().Result; var responseString = ""; using (var httpClient = new HttpClient(new Http2CustomHandler())) { // Send the request to the server HttpResponseMessage response = httpClient.PostAsync("https://api.sandbox.mobilepay.dk/merchant-authentication-openidconnect/connect/token", content).Result; // Get the response responseString = response.Content.ReadAsStringAsync().Result; } JObject json = JObject.Parse(responseString); model.access_token = json.GetValue("access_token").ToString(); model.refresh_token = json.GetValue("refresh_token").ToString(); callback(model); }
public IActionResult Index() { //return Ok("Testing Index"); string access_tokenString = HttpContext.Session.GetString("access_token"); if (access_tokenString == null) { return(Redirect("https://localhost:44311/authorize?client_id=6bf53df0b48d4937a0f94626c7c31fc6&response_type=code&redirect_uri=http://localhost:8000/Home/Return")); } else { //make get request to CountryApi string result = MakeApiCall(access_tokenString).Result; return(Ok(result)); if (result.Contains("Expired acces token")) { AccessTokenModel access_token = JsonConvert.DeserializeObject <AccessTokenModel>(HttpContext.Session.GetString("access_token")); AccessTokenModel newAccessToken = JsonConvert.DeserializeObject <AccessTokenModel>(UseRefreshToken(access_token.refresh_token).Result); newAccessToken.refresh_token = access_token.refresh_token; string newAccessTokenString = JsonConvert.SerializeObject(newAccessToken); HttpContext.Session.Clear(); HttpContext.Session.SetString("access_token", newAccessTokenString); result = MakeApiCall(newAccessTokenString).Result; //return Ok(newAccessToken); } return(Ok(result)); } }
public async Task <IActionResult> GetList() { var currentUser = HttpContext.User; //var jwt = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1bmlxdWVfbmFtZSI6InRlc3QxIiwicm9sZSI6InRlc3QxIiwibmJmIjoxNjA4MDE4MjE0LCJleHAiOjE2MDgwMTgyMjksImlhdCI6MTYwODAxODIxNH0.mSWppuNmp7Lhh5-qfySmOpZx-YK4taV6yOwu2qUv6dU"; //var handler = new JwtSecurityTokenHandler(); //var token = handler.ReadJwtToken(jwt); SharepointClientModel sharepointClientModel = new SharepointClientModel(); sharepointClientModel = new SharepointClientModel() { ClientId = "60891e37-f776-471f-80cf-59e74b0f9b93", ClientSecret = "Yf1MXgrwmv2dq1q0LEVg83kICWI3Da8ukD46g63kMCE=", GrantType = "client_credentials", TenantID = "9b048e01-f1bb-41c1-8279-71c212d0af1c", SiteName = "sainglinhtoo.sharepoint.com", Resource = "00000003-0000-0ff1-ce00-000000000000" }; AccessTokenModel acc = new AccessTokenModel(); acc = await SharePointHelper.GetToken(sharepointClientModel); var json = await SharePointHelper.GetList(acc.access_token); //var jsonData = JsonConvert.SerializeObject(json); var data = JObject.Parse(json); return(Ok(data)); //return Unauthorized(); }
public Model.CloudDisk.AccessTokenModel GetAccessToken() { AccessTokenModel result = new AccessTokenModel(); result.AccessToken = GetLocalStoredAccessToken(); return(result); }
public async Task <UserSession> Login(UserAccountViewModel user, AccessTokenModel token) { var param = new DynamicParameters(); param.Add("@UserId", user.Id, System.Data.DbType.Int32, System.Data.ParameterDirection.Input); param.Add("@AccessToken", token.AccessToken, System.Data.DbType.String, System.Data.ParameterDirection.Input); param.Add("@LoginDate", token.LoginDate, System.Data.DbType.DateTime, System.Data.ParameterDirection.Input); param.Add("@ExpiredDate", token.ExpiredDate, System.Data.DbType.DateTime, System.Data.ParameterDirection.Input); var sessionId = (await DalHelper.SPExecuteQuery <long>(SP_LOGIN, param, dbTransaction: DbTransaction, connection: DbConnection)).First(); return(new UserSession() { LoginResult = 0, SessionId = sessionId, Username = user.Username, Email = user.Email, PhoneNumber = user.PhoneNumber, DisplayName = user.DisplayName, IsSuperAdmin = user.IsSuperAdmin, UserId = user.Id, RoleIds = user.Roles.Select(r => r.Id).ToList(), AccessToken = token.AccessToken }); }
public AccessTokenModel GetAccessToken(string corpid, string corpsecret) { AccessTokenModel accessToken = null; dic.TryGetValue($"{corpid}@{corpsecret}", out accessToken); return(accessToken); }
private async Task <AccessTokenModel> GenerateToken( string login, SigningConfiguration signingConfigurations, TokenConfiguration tokenConfigurations, IDistributedCache cache) { var account = await _accountService.GetAccountInformation(login); ClaimsIdentity identity = new ClaimsIdentity( new GenericIdentity(login, "Login"), new[] { new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString("N")), new Claim("user", login), new Claim(ClaimTypes.Role, account.group_id.ToString()) } ); DateTime creationDate = DateTime.Now; DateTime expirationDate = creationDate + TimeSpan.FromSeconds(tokenConfigurations.TokenExpiration); TimeSpan finalExpiration = TimeSpan.FromSeconds(tokenConfigurations.RefreshTokenExpiration); var handler = new JwtSecurityTokenHandler(); var securityToken = handler.CreateToken(new SecurityTokenDescriptor { Issuer = tokenConfigurations.Issuer, Audience = tokenConfigurations.Audience, SigningCredentials = signingConfigurations.SigningCredentials, Subject = identity, NotBefore = creationDate, Expires = expirationDate }); var token = handler.WriteToken(securityToken); var result = new AccessTokenModel() { Authenticated = true, Created = creationDate.ToString("yyyy-MM-dd HH:mm:ss"), Expiration = expirationDate.ToString("yyyy-MM-dd HH:mm:ss"), AccessToken = token, RefreshToken = RefreshToken.Generate(), Message = "OK" }; var refreshTokenData = new RefreshTokenModel(); refreshTokenData.RefreshToken = result.RefreshToken; refreshTokenData.Login = login; DistributedCacheEntryOptions cacheOptions = new DistributedCacheEntryOptions(); cacheOptions.SetAbsoluteExpiration(finalExpiration); await cache.SetStringAsync(result.RefreshToken, JsonConvert.SerializeObject(refreshTokenData), cacheOptions); return(result); }
/// <summary> /// Checks to see if response is success /// Otherwise, throws Exception /// </summary> /// <param name="request">System.Net.Http.HttpResponseMessage</param> /// <param name="cancellationToken">System.Threading.CancellationToken</param> /// <returns>HttpResponseMessage</returns> protected override async Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { AccessTokenModel maskinportenToken = await _maskinportenClient.CreateToken(); string altinnToken = await _altinnAuthenticationClient.ConvertTokenAsync(maskinportenToken.AccessToken, request.RequestUri); request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", altinnToken); return(await base.SendAsync(request, cancellationToken)); }
public static async Task Main(string[] args) { AccessTokenModel ac = await GetToken(); Console.WriteLine(ac.access_token); await GetList(accessToken : ac.access_token); Console.ReadLine(); }
public static void SignIn(UserModel user, AccessTokenModel token) { var principal = new SecurityPrincipal(new GenericIdentity(token.UserName), new string[] { "Roles" }); principal.Access.User = user; principal.Access.Token = token; Thread.CurrentPrincipal = principal; }