public static Tokens GetTokens(string consumerKey, string consumerSecret, string tokensFileName) { Tokens tokens = null; bool isTokensFileValid = false; if (File.Exists(tokensFileName)) { using (StreamReader reader = File.OpenText(tokensFileName)) { JsonSerializer serializer = new JsonSerializer(); AccessTokens at = (AccessTokens)serializer.Deserialize(reader, typeof(AccessTokens)); if (at.CONSUMER_KEY == consumerKey && at.CONSUMER_SECRET == consumerSecret) { tokens = Tokens.Create(consumerKey, consumerSecret, at.ACCESS_TOKEN, at.ACCESS_TOKEN_SECRET); UserResponse user = tokens.Account.VerifyCredentials(); if (user != null) { tokens.UserId = user.Id.Value; tokens.ScreenName = user.ScreenName; isTokensFileValid = true; } } } } if (!isTokensFileValid) { tokens = CreateTokensByPin(consumerKey, consumerSecret); SaveTokensFile(tokens, tokensFileName); } return(tokens); }
/// <summary> /// Attempts to unlock the provided cheat. /// </summary> /// <param name="cheat">The cheat to unlock</param> private void UnlockCheat(Cheat cheat) { if (!this.LockedCheatList.Contains(cheat)) { throw new Exception("Cheat must be a locked cheat"); } AccessTokens accessTokens = SettingsViewModel.GetInstance().AccessTokens; // We need the unlocked cheat, since the locked one does not include the payload try { UnlockedCheat unlockedCheat = SqualrApi.UnlockCheat(accessTokens.AccessToken, cheat.CheatId); BrowseViewModel.GetInstance().SetCoinAmount(unlockedCheat.RemainingCoins); this.LockedCheatList.Remove(cheat); this.UnlockedCheatList.Insert(0, unlockedCheat.Cheat); LibraryViewModel.GetInstance().OnUnlock(unlockedCheat.Cheat); } catch (Exception ex) { OutputViewModel.GetInstance().Log(OutputViewModel.LogLevel.Error, "Error unlocking cheat", ex); } }
public static bool IsAuthorized(HttpContextBase context) { if (context == null) { throw new ArgumentNullException(nameof(context)); } var user = context.User as ClaimsPrincipal; if (user?.Identity == null) { return(false); } long loginId = context.ReadClaim <long>("loginid"); long userId = context.ReadClaim <int>("userid"); long officeId = context.ReadClaim <int>("officeid"); string email = context.ReadClaim <string>(ClaimTypes.Email); var expriesOn = new DateTime(context.ReadClaim <long>("exp"), DateTimeKind.Utc); string ipAddress = context.GetClientIpAddress(); string userAgent = context.GetUserAgent(); string clientToken = context.Request.GetClientToken(); if (string.IsNullOrWhiteSpace(clientToken)) { return(false); } if (loginId <= 0) { Log.Warning( "Invalid login claims supplied. Access was denied to user {userId}/{email} for officeId {officeId} having the loginId {loginId}. Token: {clientToken}.", userId, email, officeId, loginId, clientToken); Thread.Sleep(new Random().Next(1, 60) * 1000); return(false); } if (expriesOn <= DateTimeOffset.UtcNow) { Log.Debug( "Token expired. Access was denied to user {userId}/{email} for officeId {officeId} having the loginId {loginId}. Token: {clientToken}.", userId, email, officeId, loginId, clientToken); return(false); } bool isValid = AccessTokens.IsValid(clientToken, ipAddress, userAgent); if (expriesOn <= DateTimeOffset.UtcNow) { Log.Debug( "Token invalid. Access was denied to user {userId}/{email} for officeId {officeId} having the loginId {loginId}. Token: {clientToken}.", userId, email, officeId, loginId, clientToken); return(false); } return(isValid); }
/// <summary> /// 重新获取access_token /// </summary> /// Author : 俞立钢 /// Company : 绍兴标点电子技术有限公司 /// Created : 2014-10-15 15:01:17 private void RequestAccessToken() { _baseInfo = GetBaseInfo(); string url = string.Format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}", _baseInfo.Appid, _baseInfo.Appsecret); string json = PublicFun.RequestGetData(url); AccessTokens tokens = json.ResolveJson(); if (tokens.access_token != null) { //获取成功,写入信息 TxtAccessToken.Text = tokens.access_token; BaseInfo info = new BaseInfo(); DateTime start = DateTime.Now; DateTime end = start.AddSeconds(Convert.ToDouble(_baseInfo.TimeSpace)); info.Id = _baseInfo.Id; info.StartDateTime = start.ToString("yyyy-MM-dd HH:mm:ss"); info.EndDateTime = end.ToString("yyyy-MM-dd HH:mm:ss"); info.AccessToken = TxtAccessToken.Text; BaseInfoDao.UpdateBaseInfo(info); //更新缓存 _cacheBaseInfo.Remove(PublicFileds.BaseInfo); _cacheBaseInfo.Insert(PublicFileds.BaseInfo, BaseInfoDao.SelectBaseInfo(info.Id)); } else { MessageBox.Show("获取失败!!!"); } }
protected override void Initialize(RequestContext context) { string tenant = TenantConvention.GetTenant(); string clientToken = context.HttpContext.Request.GetClientToken(); var provider = new Provider(); var token = provider.GetToken(clientToken); if (token != null) { bool isValid = AccessTokens.IsValidAsync(tenant, token.ClientToken, context.HttpContext.GetClientIpAddress(), context.HttpContext.GetUserAgent()).GetAwaiter().GetResult(); if (isValid) { AppUsers.SetCurrentLoginAsync(tenant, token.LoginId).GetAwaiter().GetResult(); var loginView = AppUsers.GetCurrentAsync(tenant, token.LoginId).GetAwaiter().GetResult(); this.AppUser = new AppUser { Tenant = tenant, ClientToken = token.ClientToken, LoginId = loginView.LoginId, UserId = loginView.UserId, Name = loginView.Name, OfficeId = loginView.OfficeId, OfficeName = loginView.OfficeName, Email = loginView.Email, RoleId = loginView.RoleId, RoleName = loginView.RoleName, IsAdministrator = loginView.IsAdministrator }; var identity = new ClaimsIdentity(token.GetClaims(), DefaultAuthenticationTypes.ApplicationCookie, ClaimTypes.NameIdentifier, ClaimTypes.Role); identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, token.LoginId.ToString(CultureInfo.InvariantCulture))); if (loginView.RoleName != null) { identity.AddClaim(new Claim(ClaimTypes.Role, loginView.RoleName)); } if (loginView.Email != null) { identity.AddClaim(new Claim(ClaimTypes.Email, loginView.Email)); } context.HttpContext.User = new ClaimsPrincipal(identity); } } if (this.AppUser == null) { this.AppUser = new AppUser { Tenant = tenant }; } base.Initialize(context); }
/// <summary> /// Adds the cheat to the selected library. /// </summary> /// <param name="cheat">The cheat to add.</param> private void AddCheatToLibrary(Cheat cheat) { if (!this.CheatsAvailable.Contains(cheat)) { OutputViewModel.GetInstance().Log(OutputViewModel.LogLevel.Error, "Unable to add cheat to library"); return; } AccessTokens accessTokens = SettingsViewModel.GetInstance().AccessTokens; try { SqualrApi.AddCheatToLibrary(accessTokens.AccessToken, this.ActiveLibrary.LibraryId, cheat.CheatId); cheat.LoadDefaultStreamSettings(); this.cheatsAvailable.Remove(cheat); this.cheatsInLibrary.Insert(0, cheat); this.RaisePropertyChanged(nameof(this.CheatsAvailable)); this.RaisePropertyChanged(nameof(this.CheatsInLibrary)); } catch (Exception ex) { OutputViewModel.GetInstance().Log(OutputViewModel.LogLevel.Error, "Error adding cheat to library", ex); } }
/// <summary> /// Selects a specific game for which to view the store. /// </summary> /// <param name="game">The selected game.</param> public void SelectGame(Game game) { // Deselect current game this.IsCheatListLoading = true; this.LockedCheatList = null; this.UnlockedCheatList = null; Task.Run(() => { try { // Select new game AccessTokens accessTokens = SettingsViewModel.GetInstance().AccessTokens; StoreCheats storeCheats = SqualrApi.GetStoreCheats(accessTokens.AccessToken, game.GameId); this.LockedCheatList = new FullyObservableCollection <Cheat>(storeCheats.LockedCheats); this.UnlockedCheatList = new FullyObservableCollection <Cheat>(storeCheats.UnlockedCheats); } catch (Exception ex) { OutputViewModel.GetInstance().Log(OutputViewModel.LogLevel.Error, "Error loading cheats", ex); BrowseViewModel.GetInstance().NavigateBack(); } finally { this.IsCheatListLoading = false; } }); }
protected async Task <ActionResult> OnAuthenticatedAsync(LoginResult result, SignInInfo model = null) { if (!result.Status) { int delay = new Random().Next(1, 5) * 1000; await Task.Delay(delay).ConfigureAwait(false); return(new HttpStatusCodeResult(HttpStatusCode.Forbidden, JsonConvert.SerializeObject(result))); } Guid?applicationId = null; if (model != null) { applicationId = model.ApplicationId; } var loginView = await AppUsers.GetCurrentAsync(this.Tenant, result.LoginId).ConfigureAwait(false); var manager = new Provider(this.Tenant, applicationId, result.LoginId, loginView.UserId, loginView.OfficeId); var token = manager.GetToken(); await AccessTokens.SaveAsync(this.Tenant, token, this.RemoteUser.IpAddress, this.RemoteUser.UserAgent).ConfigureAwait(true); string domain = TenantConvention.GetDomain(); this.AddAuthenticationCookie(domain, token); this.AddCultureCookie(domain, model?.Culture.Or("en-US")); return(this.Ok(token.ClientToken)); }
private static AccessTokens GetTokens(string uri, string body) { AccessTokens tokens = null; var request = (HttpWebRequest)WebRequest.Create(uri); request.Method = "POST"; request.Accept = "application/json"; request.ContentType = "application/x-www-form-urlencoded"; request.ContentLength = body.Length; using (Stream requestStream = request.GetRequestStream()) { StreamWriter writer = new StreamWriter(requestStream); writer.Write(body); writer.Close(); } var response = (HttpWebResponse)request.GetResponse(); using (Stream responseStream = response.GetResponseStream()) { var reader = new StreamReader(responseStream); string json = reader.ReadToEnd(); reader.Close(); tokens = JsonConvert.DeserializeObject(json, typeof(AccessTokens)) as AccessTokens; } return(tokens); }
public BedrockTokenPair RefreshAccessToken(string refreshToken) { if (string.IsNullOrEmpty(refreshToken)) { throw new ArgumentException("The refresh token is missing."); } try { AccessTokens tokens = GetTokensUsingGET($"{this.RefreshUri}", new Dictionary <string, string> { { "client_id", MSA_CLIENT_ID }, { "grant_type", "refresh_token" }, { "scope", "service::user.auth.xboxlive.com::MBI_SSL" }, { "redirect_uri", RedirectUri }, { "refresh_token", refreshToken } }); return(new BedrockTokenPair() { AccessToken = tokens.AccessToken, ExpiryTime = DateTime.UtcNow.AddSeconds(tokens.Expiration), RefreshToken = tokens.RefreshToken }); } catch (WebException ex) { Log.Warn("RefreshAccessToken failed likely due to an invalid client ID or refresh token\n" + ex.ToString()); } return(null); }
/// <summary> /// Deletes the selected library after prompting the user. /// </summary> private void DeleteLibrary() { if (this.ActiveLibrary == null) { OutputViewModel.GetInstance().Log(OutputViewModel.LogLevel.Error, "No library selected"); return; } MessageBoxResult result = CenteredDialogBox.Show( "Delete library '" + this.ActiveLibrary.LibraryName + "'?", "Confirm Library Delete", MessageBoxButton.YesNoCancel, MessageBoxImage.Question); if (result == MessageBoxResult.Yes) { Task.Run(() => { try { AccessTokens accessTokens = SettingsViewModel.GetInstance().AccessTokens; SqualrApi.DeleteLibrary(accessTokens?.AccessToken, this.ActiveLibrary.LibraryId); this.libraries.Remove(this.ActiveLibrary); this.ActiveLibrary = null; this.RaisePropertyChanged(nameof(this.Libraries)); this.RaisePropertyChanged(nameof(this.ActiveLibrary)); } catch (Exception ex) { OutputViewModel.GetInstance().Log(OutputViewModel.LogLevel.Error, "Error deleting library", ex); } }); } }
/// <summary> /// Determine if the user is logged in to Twitch. /// </summary> private void UpdateLoginStatus() { this.IsLoginStatusLoading = true; try { AccessTokens accessTokens = SettingsViewModel.GetInstance().AccessTokens; if (accessTokens == null || accessTokens.AccessToken.IsNullOrEmpty()) { this.IsLoggedIn = false; return; } User user = SqualrApi.GetTwitchUser(accessTokens.AccessToken); SqualrApi.Connect(accessTokens.AccessToken); this.ActiveUser = user; this.IsLoggedIn = true; } catch (Exception ex) { OutputViewModel.GetInstance().Log(OutputViewModel.LogLevel.Warn, "Unable to log in using stored credentials", ex); this.IsLoggedIn = false; } finally { this.IsLoginStatusLoading = false; } }
public string GenerateAccesstoeken(string email, int minute = 60) { try { var member = db.Members.SingleOrDefault(m => m.email.Equals(email)); if (member == null) { throw new Exception("not found member"); } var accessToken = new AccessTokens { token = Guid.NewGuid().ToString(), exprise = DateTime.Now.AddMinutes(minute), memberID = member.id }; this.db.AccessTokens.Add(accessToken); this.db.SaveChanges(); return(accessToken.token); } catch (Exception ex) { throw ex.GetErrorException(); } }
public static Tokens GetTokens() { Tokens tokens = null; if (File.Exists(TOKEN_FILE_NAME)) { using (StreamReader reader = File.OpenText(TOKEN_FILE_NAME)) { JsonSerializer serializer = new JsonSerializer(); AccessTokens at = (AccessTokens)serializer.Deserialize(reader, typeof(AccessTokens)); tokens = Tokens.Create(Credential.CONSUMER_KEY, Credential.CONSUMER_SECRET, at.ACCESS_TOKEN, at.ACCESS_TOKEN_SECRET); } } else { OAuth.OAuthSession session = OAuth.Authorize(Credential.CONSUMER_KEY, Credential.CONSUMER_SECRET); Uri authorizeUri = session.AuthorizeUri; Process.Start(authorizeUri.AbsoluteUri); Console.Write("Input PIN: "); string pin = Console.ReadLine(); tokens = OAuth.GetTokens(session, pin); AccessTokens at = new AccessTokens() { ACCESS_TOKEN = tokens.AccessToken, ACCESS_TOKEN_SECRET = tokens.AccessTokenSecret }; using (StreamWriter writer = File.CreateText(TOKEN_FILE_NAME)) { JsonSerializer serializer = new JsonSerializer(); serializer.Serialize(writer, at); } } return(tokens); }
public IActionResult Renew([FromBody] AccessTokens reqData) { int resHttpStatusCode = 400; dynamic response = new ExpandoObject(); response.success = "false"; try { if (reqData != null && AuthToken.VerifyRefreshToken(reqData.refreshToken, reqData.accessToken)) { var value = _cache.StringGet(reqData.accessToken); _cache.KeyDelete(reqData.accessToken); var newAccessToken = AuthToken.RefreshAccessToken(reqData.accessToken); _cache.StringSet(newAccessToken, value); resHttpStatusCode = 200; response.success = "true"; response.accessToken = newAccessToken; } else { response.msg = "Invalid request"; } } catch (Exception e) { CLogger.Log(e); resHttpStatusCode = 500; response.msg = "Internal server error"; } HttpContext.Response.StatusCode = resHttpStatusCode; return(new JsonResult(response)); }
public Guid IssueAccessToken() { var accessToken = Guid.NewGuid(); AccessTokens.Add(accessToken); return(accessToken); }
public void InitalizeContext() { this.accesstokensManager = new Mock <IAccessTokensManager>(); this.service = new AccessTokens { AccessTokensManager = this.accesstokensManager.Object, }; }
public bool ValidateToken(ref TokenIdentity tokenIdentity) { bool result = false; try { tokenIdentity.SetAuthenticationType("Custom"); // Base64 decode the string, obtaining the token:guid:username:timeStamp. string key = Encoding.UTF8.GetString(Convert.FromBase64String(tokenIdentity.Token)); // Split the parts. string[] parts = key.Split(new char[] { ':' }); if (parts.Length == 5) { // Get the hash message, username, and timestamp. string hash = parts[0]; string guid = parts[1]; int userId = Int32.Parse(parts[2], CultureInfo.InvariantCulture); string username = parts[3]; long ticks = Int64.Parse(parts[4], CultureInfo.InvariantCulture); tokenIdentity.EffectiveTime = ticks; DateTime timeStamp = new DateTime(ticks); // Ensure the timestamp is valid. bool expired = Math.Abs((DateTime.Now.AddHours(7) - timeStamp).TotalSeconds) > _expirationSeconds; if (!expired) { // Hash the message with the key to generate a token. string computedToken = GenerateToken(userId, username, tokenIdentity.UserAgent, tokenIdentity.IP, guid, ticks).Token; // Compare the computed token with the one supplied and ensure they match. if (String.Equals(tokenIdentity.Token, computedToken, StringComparison.InvariantCulture)) { using (ApplicationDbContext db = new ApplicationDbContext()) { AccessTokens accessToken = db.AccessTokens.SingleOrDefault(x => x.Token == computedToken); //connection.Open(); //AccessToken accessToken = connection.QuerySingleOrDefault<AccessToken>(SchemaAuth.AccessTokens_GetByToken, new { Token = computedToken }, commandType: System.Data.CommandType.StoredProcedure); if (accessToken != null && Math.Abs((DateTime.Now - accessToken.EffectiveTime).TotalSeconds) < _expirationSeconds && accessToken.UserName.Equals(username)) { result = true; tokenIdentity.SetIsAuthenticated(true); tokenIdentity.UserName = username; } } } } } } catch (NullReferenceException ex) { return(false); } return(result); }
public void RevokeAccessToken(Guid accessToken) { var issuedAccessToken = AccessTokens.SingleOrDefault(x => x == accessToken); if (issuedAccessToken != null) { AccessTokens.Remove(issuedAccessToken); } }
public ActionResult SignOut() { if (this.MetaUser != null) { AccessTokens.Revoke(this.MetaUser.ClientToken); } FormsAuthentication.SignOut(); return(this.Redirect(this.GetReturnUrl())); }
public async Task <ActionResult> SignOutAsync() { if (!string.IsNullOrWhiteSpace(this.AppUser?.ClientToken)) { await AccessTokens.RevokeAsync(this.Tenant, this.AppUser.ClientToken).ConfigureAwait(true); } FormsAuthentication.SignOut(); return(View(GetRazorView <AreaRegistration>("SignOut/Index.cshtml", this.Tenant))); }
public async Task <ActionResult> RevokeAsync() { if (!string.IsNullOrWhiteSpace(this.AppUser?.ClientToken)) { await AccessTokens.RevokeAsync(this.Tenant, this.AppUser.ClientToken).ConfigureAwait(true); await this.RefreshTokens().ConfigureAwait(true); } return(this.Ok("OK")); }
private AccessTokens BuildAccessToken(string userId, string clientAppId, string refreshToken, Jwt.Algorithm alg, string grantType) { var obj = new AccessTokens(); obj.Id = Guid.NewGuid(); obj.RefreshToken = refreshToken; obj.IssuedDateTime = DateTimes.GetCurrentUtcDateTimeInThaiTimeZone(DateTimes.DateTimeFormat.YearMonthDayByDashTHourMinuteSecondByColonZ, DateTimes.LanguageCultureName.ENGLISH_UNITED_STATES, DateTimes.DateTimeUtcOffset.HHMMByColon); var AccessTokenExpiryDateTime = DateTime.UtcNow.AddSeconds(Convert.ToDouble(_config["Jwt:Expires"])); obj.ExpiryDateTime = DateTimes.ConvertToUtcDateTimeInThaiTimeZone(AccessTokenExpiryDateTime, DateTimes.DateTimeFormat.YearMonthDayByDashTHourMinuteSecondByColonZ, DateTimes.LanguageCultureName.ENGLISH_UNITED_STATES, DateTimes.DateTimeUtcOffset.HHMMByColon); Claim[] claims; if (grantType == GRANT_TYPE_PASSWORD) { claims = new[] { new Claim(JwtRegisteredClaimNames.Sub, userId), new Claim(JwtRegisteredClaimNames.Jti, obj.Id.ToString("N")), new Claim(JwtRegisteredClaimNames.Iat, DateTimes.ConvertToUnixTimeByDateTime(DateTime.UtcNow).ToString(), System.Security.Claims.ClaimValueTypes.Integer32), new Claim(JwtRegisteredClaimNames.Nbf, DateTimes.ConvertToUnixTimeByDateTime(DateTime.UtcNow).ToString(), System.Security.Claims.ClaimValueTypes.Integer32), new Claim("appid", clientAppId) }; } else { claims = new[] { new Claim(JwtRegisteredClaimNames.Jti, obj.Id.ToString("N")), new Claim(JwtRegisteredClaimNames.Iat, DateTimes.ConvertToUnixTimeByDateTime(DateTime.UtcNow).ToString(), System.Security.Claims.ClaimValueTypes.Integer32), new Claim(JwtRegisteredClaimNames.Nbf, DateTimes.ConvertToUnixTimeByDateTime(DateTime.UtcNow).ToString(), System.Security.Claims.ClaimValueTypes.Integer32), new Claim("appid", clientAppId) }; } var token = new JwtSecurityToken( issuer: _config["Jwt:Issuer"], audience: _config["Jwt:Audience"], claims: claims, expires: AccessTokenExpiryDateTime, notBefore: DateTime.UtcNow, signingCredentials: Jwt.CreateSigningCredentials(alg, _config, _azObj) ); obj.AccessToken = new JwtSecurityTokenHandler().WriteToken(token); obj.Status = true; // Write Generated AccessToken to AuthDB (For future checking) var authAccessToken = _authObj.PutAccessTokens(obj); // Update RefreshToken to AuthDB (For future checking) var authRefreshToken = _authObj.PutRefreshTokensAccessToken(refreshToken, obj.AccessToken, obj.IssuedDateTime); return(obj); }
public async Task <ActionResult> RevokeAsync() { if (!string.IsNullOrWhiteSpace(this.AppUser?.ClientToken)) { await AccessTokens.RevokeAsync(this.Tenant, this.AppUser.ClientToken).ConfigureAwait(true); string key = "access_tokens_" + this.Tenant; var factory = new DefaultCacheFactory(); factory.Remove(key); } return(this.Ok("OK")); }
public static DocSharingServiceClient GetDocSharingClient(string userName) { var token = AccessTokens.Get(userName); if (token == OAuth20AccessToken.Invalid) { throw new InvalidOAuth20AccessTokenException("eCollege API", userName); } var auth = new OAuth20(token); var client = new DocSharingServiceClient(baseUri, auth); return(client); }
// PUT https://undone-auth.firebaseio.com/AccessTokens.json?access_token=<ACCESS_TOKEN> public async Task <HttpResponseMessage> PutAccessTokens(AccessTokens token) { var client = new HttpClient(); client.BaseAddress = new Uri(projectUrl); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json")); var jsonString = JsonConvert.SerializeObject(token); var uniqueId = token.AccessToken.Replace(".", "---"); var response = await client.PutAsync("AccessTokens/" + uniqueId + ".json?access_token=" + accessToken, new StringContent(jsonString, Encoding.UTF8, "application/json")); return(response); }
public async Task <ActionResult> SignOutAsync() { if (!string.IsNullOrWhiteSpace(this.AppUser?.ClientToken)) { await AccessTokens.RevokeAsync(this.Tenant, this.AppUser.ClientToken).ConfigureAwait(true); string key = "access_tokens_" + this.Tenant; var factory = new DefaultCacheFactory(); factory.Remove(key); } FormsAuthentication.SignOut(); return(this.View(this.GetRazorView <AreaRegistration>("SignOut/Index.cshtml", this.Tenant))); }
/// <summary> /// Add Oauth2 token to the bombardier generator /// </summary> /// <param name="token"></param> /// <param name="authenticationType"></param> /// <returns></returns> public BombardierGeneratorOptions AddOAuth2Token(string token, AuthenticationType authenticationType) { if (string.IsNullOrEmpty(token)) { throw new ArgumentException($"{nameof(token)} is null."); } if (authenticationType == null) { throw new ArgumentException($"{nameof(authenticationType)} is null."); } AccessTokens.Add(authenticationType, token); return(this); }
static void SaveTokensFile(Tokens tokens, string tokensFileName) { AccessTokens at = new AccessTokens(); at.CONSUMER_KEY = tokens.ConsumerKey; at.CONSUMER_SECRET = tokens.ConsumerSecret; at.ACCESS_TOKEN = tokens.AccessToken; at.ACCESS_TOKEN_SECRET = tokens.AccessTokenSecret; using (StreamWriter writer = File.CreateText(tokensFileName)) { JsonSerializer serializer = new JsonSerializer(); serializer.Serialize(writer, at); } }
public ActionResult Logout([FromBody] AccessTokens reqData) { int resHttpStatusCode = 400; if (!(string.IsNullOrEmpty(reqData.accessToken) || string.IsNullOrEmpty(reqData.refreshToken)) && _cache.KeyExists(reqData.accessToken) && _cache.KeyExists(reqData.refreshToken)) { _cache.KeyDelete(reqData.accessToken); _cache.KeyDelete(reqData.refreshToken); resHttpStatusCode = 200; } HttpContext.Response.StatusCode = resHttpStatusCode; return(new JsonResult(new { success = resHttpStatusCode == 200 ? "true" : "false" })); }