private static IObservable<List> ShowListCore(OAuthClient client, string endpoint, UserId ownerId) { return Observable .Defer(() => client.GetResponseText()) .Select(json => List.Parse(json, ownerId)) .OnErrorRetry(3) .WriteLine(endpoint, list => list.FullName); }
private void btnCleanup_Click(object sender, EventArgs e) { string clientId = ConfigurationManager.AppSettings["ClientId"]; //Clean out any cached credentials/tokens. using (OAuthClient client = new OAuthClient(clientId)) { client.CleanUp(); } authResult = null; }
public void OAuthClient_ValidLogin_FreshUser_AccessTokenProvided() { // arrange var tokenService = GetTokenStorageService(cachedTokensFile); var email = TU.RandomAlphaNumString(); var client = new OAuthClient(clientConsumer, tokenService, new HttpRequestReader()); // act var result = client.Login(email); // assert Assert.IsTrue(result); }
public void OAuthClient_ValidLogin_AccessTokenProvided() { // arrange var tokenService = GetTokenStorageService(cachedTokensFile); var email = ConfigurationManager.AppSettings["UserEmail"]; var client = new OAuthClient(clientConsumer, tokenService, new HttpRequestReader()); // act var result = client.Login(email); // assert Assert.IsTrue(result); }
public async Task<string> Index() { try { string username = ConfigurationManager.AppSettings["Weee.WarmUpUserUsername"]; string password = ConfigurationManager.AppSettings["Weee.WarmUpUserPassword"]; if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password)) { return "Skipping warm-up - No user details provided."; } Stopwatch stopwatch = Stopwatch.StartNew(); string baseUrl = ConfigurationManager.AppSettings["Weee.SiteRoot"]; string clientId = ConfigurationManager.AppSettings["Weee.ApiClientID"]; string clientSecret = ConfigurationManager.AppSettings["Weee.ApiSecret"]; // Fetch an access token for the warm-up user. IOAuthClient client = new OAuthClient(baseUrl, clientId, clientSecret); var tokenResponse = await client.GetAccessTokenAsync(username, password); if (tokenResponse.AccessToken == null) { if (tokenResponse.IsHttpError) { throw new Exception(string.Format("Request for access token returned HttpError: Status - {0}, Reason - {1}, Error - {2}", tokenResponse.HttpErrorStatusCode, tokenResponse.HttpErrorReason, tokenResponse.Error)); } else if (tokenResponse.IsError) { throw new Exception(string.Format("Request for access token returned Error: {0}", tokenResponse.Error)); } else { throw new Exception("Request for access token returned null."); } } // Fetch the user info for the warm-up user. IUserInfoClient userInfoClient = new UserInfoClient(baseUrl); var userInfo = await userInfoClient.GetUserInfoAsync(tokenResponse.AccessToken); return string.Format("Warm-up complete in {0} seconds.", stopwatch.Elapsed.TotalSeconds); } catch (Exception ex) { throw new Exception("API warm-up failed.", ex); } }
public void OAuthClient_HasAccessToken_MakesSuccessfulRequest() { // arrange var tokenService = GetTokenStorageService(cachedTokensFile); var email = ConfigurationManager.AppSettings["UserEmail"]; var client = new OAuthClient(clientConsumer, tokenService, new HttpRequestReader()); // act var result = client.Login(email); client.Request(new System.Uri("http://fantasysports.yahooapis.com/fantasy/v2/users;use_login=1/games"), new System.Net.Http.HttpMethod("GET")); // assert Assert.IsTrue(result); }
protected virtual async Task<KeyPair> GetRequestToken(IWebAuthenticator authorizer) { var oauthClient = new OAuthClient(ApplicationInfo); var resp = await oauthClient.Ajax(UrlGetRequestToken, parameters: new HttpParameters { { "oauth_callback", (await authorizer.GetCallback()).ToString() } }, dataType: DataType.UrlEncoded ); if (resp.oauth_callback_confirmed != "true") throw new ProtocolException("Expected oauth_callback_confirmed to be true"); return new KeyPair( key: resp.oauth_token, secret: resp.oauth_token_secret ); }
public StreamingClient(TwitterToken token, string endpoint) { this.endpoint = token.Endpoints[endpoint]; this.client = new OAuthClient( token.Application.ConsumerKey, token.Application.ConsumerSecret, token.TokenKey, token.TokenSecret) { Url = this.endpoint.Definition.Url, MethodType = this.endpoint.Definition.MethodType == HttpMethod.Get ? MethodType.Get : MethodType.Post, }; var profile = TwitterClient.Current.CurrentNetworkProfile; if (profile != null) { if (profile.Proxy != null) { this.client.ApplyBeforeRequest += req => req.Proxy = profile.Proxy.GetProxy(); } } }
public static bool IsMatchRedirectUri(this OAuthClient oAuthClient, PostRegisterRequest request) { return(IsMatchRedirectUri(oAuthClient, request.redirect_uri)); }
public static bool IsValid(this OAuthClient oAuthClient) { return(oAuthClient?.Scopes?.Any() == true && !oAuthClient.IsLocked && !oAuthClient.IsDeleted); }
protected override void AddCustomProperties(System.Collections.Specialized.NameValueCollection properties) { base.AddCustomProperties(properties); properties.Add("Twitter", string.Format("http://twitter.com/{0}", OAuthClient.GetCurrentUser <TwitterUserData>().ScreenName)); }
public async Task <bool> Handle(AuthenticateInstruction authenticateInstruction, OAuthClient client, string expectedIssuer) { if (authenticateInstruction == null) { throw new ArgumentNullException(nameof(authenticateInstruction)); } if (client == null) { throw new ArgumentNullException(nameof(client)); } var clientAssertion = authenticateInstruction.ClientAssertion; var isJwsToken = _jwtParser.IsJwsToken(clientAssertion); if (!isJwsToken) { throw new OAuthException(ErrorCodes.INVALID_CLIENT_AUTH, ErrorMessages.BAD_CLIENT_ASSERTION_FORMAT); } var jwsPayload = _jwsGenerator.ExtractPayload(clientAssertion); if (jwsPayload == null) { throw new OAuthException(ErrorCodes.INVALID_CLIENT_AUTH, ErrorMessages.BAD_CLIENT_ASSERTION_FORMAT); } var clientId = jwsPayload.GetIssuer(); var payload = await _jwtParser.Unsign(clientAssertion, clientId).ConfigureAwait(false); if (payload == null) { throw new OAuthException(ErrorCodes.INVALID_CLIENT_AUTH, ErrorMessages.BAD_CLIENT_ASSERTION_SIGNATURE); } return(ValidateJwsPayLoad(payload, "")); }
public AudioHelper(LavaNode lavanode, EmbedHelper eh) { Node = lavanode; embedHelper = eh; // TODO: Make SpotifyClient own class if (Program.BotConfig.SpotifyClientId != "" && Program.BotConfig.SpotifySecret != "") { var config = SpotifyClientConfig.CreateDefault(); var request = new ClientCredentialsRequest(Program.BotConfig.SpotifyClientId, Program.BotConfig.SpotifySecret); var response = new OAuthClient(config).RequestToken(request); var spotify = new SpotifyClient(config.WithToken(response.Result.AccessToken)); Spotify = spotify; _disconnectTokens = new ConcurrentDictionary <ulong, CancellationTokenSource>(); SpotifyLogin = true; } // Handler for when a LavaTrack is started // args: TrackStartEventArgs Node.OnTrackStarted += async(args) => { var player = args.Player; var queue = await GetNewEmbedQueueString(player); var embed = await embedHelper.BuildMusicEmbed(player, Color.DarkTeal); //If for some reason Volume is set to 0 (100%) it will set to default volume if (player.Volume == 0) { await player.UpdateVolumeAsync(Program.BotConfig.Volume); } var content = queue switch { "" => NoSongsInQueue, _ => string.Format(QueueMayHaveSongs, queue) }; await Program.BotConfig.BotEmbedMessage.ModifyAsync(x => { x.Embed = embed; x.Content = content; }); if (!_disconnectTokens.TryGetValue(args.Player.VoiceChannel.Id, out var value)) { return; } if (value.IsCancellationRequested) { return; } value.Cancel(true); }; // Handler for when a LavaTrack is ended, stopped, or skipped // args: TrackEndedEventArgs Node.OnTrackEnded += async(args) => { var player = args.Player; if (RepeatFlag) { await player.PlayAsync(RepeatTrack); return; } RepeatFlag = false; if (!args.Reason.ShouldPlayNext()) { return; } if (!player.Queue.TryDequeue(out var track) && player.Queue.Count == 0) { var embed = await EmbedHelper.BuildDefaultEmbed(); await Program.BotConfig.BotEmbedMessage.ModifyAsync(x => { x.Content = NoSongsInQueue; x.Embed = embed; }); if (!StayFlag) { _ = InitiateDisconnectAsync(args.Player, TimeSpan.FromMinutes(15)); } return; } await args.Player.PlayAsync(track); }; // Handler for when a LavaTrack throws an exception // args: TrackExceptionEventArgs Node.OnTrackException += async(args) => { var player = args.Player; var errorMessage = args.ErrorMessage switch { "This video cannot be viewed anonymously." => "This video most likely hasn't premiered yet.", "Received unexpected response from YouTube." => "YouTube is most likely down.", _ => "Video might still be processing, try again later." }; var msg = await embedHelper.BuildTrackErrorEmbed($"[{player.Track.Title}]({player.Track.Url})\n{errorMessage}"); await player.TextChannel.SendAndRemove(embed : msg); if (player.Queue.Count == 0) { //If no songs in queue it will stop playback to reset the embed await player.StopAsync(); return; } //If queue has any songs it will skip to the next track await player.SkipAsync(); return; }; // Handler for when a LavaTrack gets stuck // args: TrackStuckEventArgs Node.OnTrackStuck += async(args) => { var player = args.Player; var msg = await embedHelper.BuildTrackErrorEmbed($"[{player.Track.Title}]({player.Track.Url})\nTrack got stuck, moving on..."); await player.TextChannel.SendAndRemove(embed : msg); if (player.Queue.Count == 0) { //If no songs in queue it will stop playback to reset the embed await player.StopAsync(); return; } //If queue has any songs it will skip to the next track await player.SkipAsync(); return; }; } /// <summary> /// Initiates a disconnect from the voice channel /// </summary> /// <param name="player">Instance of LavaPlayer for the guild</param> /// <param name="timeSpan">TimeSpan for length before disconnecting</param> /// <returns></returns> private async Task InitiateDisconnectAsync(LavaPlayer player, TimeSpan timeSpan) { if (!_disconnectTokens.TryGetValue(player.VoiceChannel.Id, out var value)) { value = new CancellationTokenSource(); _disconnectTokens.TryAdd(player.VoiceChannel.Id, value); } else if (value.IsCancellationRequested) { _disconnectTokens.TryUpdate(player.VoiceChannel.Id, new CancellationTokenSource(), value); value = _disconnectTokens[player.VoiceChannel.Id]; } var isCancelled = SpinWait.SpinUntil(() => value.IsCancellationRequested, timeSpan); if (isCancelled) { return; } await Node.LeaveAsync(player.VoiceChannel); var msg = await embedHelper.BuildMessageEmbed("Muse has disconnected due to inactivity."); await player.TextChannel.SendAndRemove(embed : msg); }
/// <summary>绑定用户,用户未有效绑定或需要强制绑定时</summary> /// <param name="uc"></param> /// <param name="client"></param> public virtual IManageUser OnBind(UserConnect uc, OAuthClient client) { var prv = Provider; // 如果未登录,需要注册一个 var user = prv.Current; if (user == null) { var set = Setting.Current; if (!set.AutoRegister) { throw new InvalidOperationException("绑定要求本地已登录!"); } // 先找用户名,如果存在,就加上提供者前缀,直接覆盖 var name = client.UserName; if (name.IsNullOrEmpty()) { name = client.NickName; } if (!name.IsNullOrEmpty()) { user = prv.FindByName(name); if (user != null && !set.ForceBindUser) { name = client.Name + "_" + name; user = prv.FindByName(name); } } else // QQ、微信 等不返回用户名 { // OpenID和AccessToken不可能同时为空 var openid = client.OpenID; if (openid.IsNullOrEmpty()) { openid = client.AccessToken; } // 过长,需要随机一个较短的 var num = openid.GetBytes().Crc(); name = client.Name + "_" + num.ToString("X8"); user = prv.FindByName(name); } if (user == null) { // 新注册用户采用魔方默认角色 var rid = set.DefaultRole; //if (rid == 0 && client.Items.TryGetValue("roleid", out var roleid)) rid = roleid.ToInt(); //if (rid <= 0) rid = GetRole(client.Items, rid < -1); // 注册用户,随机密码 user = prv.Register(name, Rand.NextString(16), rid, true); //if (user is UserX user2) user2.RoleIDs = GetRoles(client.Items, rid < -2).Join(); } } uc.UserID = user.ID; uc.Enable = true; return(user); }
/// <summary>登录成功</summary> /// <param name="client">OAuth客户端</param> /// <param name="context">服务提供者。可用于获取HttpContext成员</param> /// <returns></returns> public virtual String OnLogin(OAuthClient client, IServiceProvider context) { var openid = client.OpenID; if (openid.IsNullOrEmpty()) { openid = client.UserName; } // 根据OpenID找到用户绑定信息 var uc = UserConnect.FindByProviderAndOpenID(client.Name, openid); if (uc == null) { uc = new UserConnect { Provider = client.Name, OpenID = openid } } ; uc.Fill(client); // 强行绑定,把第三方账号强行绑定到当前已登录账号 var forceBind = false; #if __CORE__ var httpContext = context.GetService <IHttpContextAccessor>().HttpContext; var req = httpContext.Request; #else var req = context.GetService <HttpRequest>(); #endif if (req != null) { forceBind = req.Get("sso_action").EqualIgnoreCase("bind"); } // 可能因为初始化顺序的问题,导致前面没能给Provider赋值 var prv = Provider; if (prv == null) { prv = Provider = ManageProvider.Provider; } // 检查绑定,新用户的uc.UserID为0 var user = prv.FindByID(uc.UserID); if (forceBind || user == null || !uc.Enable) { user = OnBind(uc, client); } // 填充昵称等数据 Fill(client, user); if (user is IAuthUser user3) { user3.Logins++; user3.LastLogin = DateTime.Now; user3.LastLoginIP = WebHelper.UserHost; user3.Save(); } try { uc.Save(); } catch (Exception ex) { //为了防止某些特殊数据导致的无法正常登录,把所有异常记录到日志当中。忽略错误 XTrace.WriteException(ex); } if (!user.Enable) { throw new InvalidOperationException("用户已禁用!"); } // 登录成功,保存当前用户 //prv.Current = user; prv.SetCurrent(user, context); // 单点登录不要保存Cookie,让它在Session过期时请求认证中心 //prv.SaveCookie(user); var set = Setting.Current; if (set.SessionTimeout > 0) #if __CORE__ { ManagerProviderHelper.SaveCookie(prv, user, TimeSpan.FromSeconds(set.SessionTimeout), httpContext); } #else { prv.SaveCookie(user, TimeSpan.FromSeconds(set.SessionTimeout), context); } #endif return(SuccessUrl); }
public async Task GetTokenStatus_ShouldThrowOnNullUserId() { var client = new OAuthClient(new Uri("http://localhost"), new BotAccessTokenStub("token")); await Assert.ThrowsAsync <ValidationException>(() => client.UserToken.GetTokenStatusAsync(null)); }
private void ObtainAuthorisationAsync() { string clientId = ConfigurationManager.AppSettings["ClientId"]; string scope = ConfigurationManager.AppSettings["Scope"]; if (authResult == null) { OAuthClient client = new OAuthClient(clientId); client.AuthoriseCompleted += new OAuthEvents.AuthoriseCompletedHandler(client_AuthoriseCompleted); try { //If you have problems connecting try setting the IWebProxy //in the call to client.Authorise below. string authId = client.BeginAuthorise(new AuthorisationInfo() { Scope = scope }); } catch (Exception ex) { MessageBox.Show(ex.Message); } } }
public static bool IsCorrectSecret(this OAuthClient oAuthClient, TokenRequest request) { return(request.grant_type != GrandType.AuthorizationCode || PasswordUtils.IsVerifiedPassword(request.client_secret, oAuthClient.ClientSecret)); }
protected virtual async Task<KeyPair> GetAccessToken(KeyPair requestToken, string oAuthVerifier) { var oauthClient = new OAuthClient(ApplicationInfo, requestToken); var resp = await oauthClient.Ajax(UrlGetAccessToken, parameters: new HttpParameters { { "oauth_verifier", oAuthVerifier } }, dataType: DataType.UrlEncoded); return new KeyPair( key: resp.oauth_token, secret: resp.oauth_token_secret ); }
private static BossResponse OAuthFind(PlaceByCoordinates request, string consumerKey, string consumerSecret, int retry = 0) { try { using (var oAuth = new OAuthClient()) { var json = oAuth.Get(request.GetUri(), consumerKey, consumerSecret); var bossContainer = JsonConvert.DeserializeObject<BossContainer>(json); if (bossContainer != null) return bossContainer.BossResponse; throw new InvalidOperationException("Unable to parse BOSS GEO Response. Raw JSON:\r\n" + json); } } catch (ProtocolException ex) { if (retry < RetryLimit && ex.InnerException is WebException) return OAuthFind(request, consumerKey, consumerSecret, ++retry); throw; } catch (CommunicationException ex) { if (retry < RetryLimit && ex.Message == "Server Error") return OAuthFind(request, consumerKey, consumerSecret, ++retry); throw; } }
public AuthenticationHeaderValue GenerateAuthorizationHeader(IRequest request) { if (request.RequiresAuthentication()) { var oAuthClient = new OAuthClient(new TwitterProvider(request.ConsumerKey, request.ConsumerSecret, null)); AuthenticationHeaderValue header = oAuthClient.SignRequest( request.HttpMethod, GenerateUri(request), request.AccessToken, request.GetContent(), request.AccessTokenSecret); return header; } else { return null; } }
public async Task GetUserToken_ShouldThrowOnEmptyUserId() { var client = new OAuthClient(mockConnectorClient, "https://localhost"); await Assert.ThrowsAsync <ArgumentNullException>(() => client.GetUserTokenAsync(string.Empty, "mockConnection", string.Empty)); }
public async Task GetSigninLink_ShouldThrowOnNullState() { var client = new OAuthClient(new Uri("http://localhost"), new BotAccessTokenStub("token")); await Assert.ThrowsAsync <ValidationException>(() => client.BotSignIn.GetSignInUrlAsync(null)); }
public async Task SignOutUser_ShouldThrowOnEmptyConnectionName() { var client = new OAuthClient(mockConnectorClient, "https://localhost"); await Assert.ThrowsAsync <ArgumentNullException>(() => client.SignOutUserAsync("userid", string.Empty)); }
public ConnectorClientFactory(IAddress address, MicrosoftAppCredentials credentials) { SetField.NotNull(out this.address, nameof(address), address); SetField.NotNull(out this.credentials, nameof(credentials), credentials); this.serviceUri = new Uri(address.ServiceUrl); string key = $"{serviceUri}{credentials.MicrosoftAppId}"; if (!connectorClients.TryGetValue(key, out connectorClient)) { connectorClient = new ConnectorClient(this.serviceUri, this.credentials); connectorClients[key] = connectorClient; } if (!stateClients.TryGetValue(key, out stateClient)) { if (IsEmulator(this.address)) { // for emulator we should use serviceUri of the emulator for storage stateClient = new StateClient(this.serviceUri, this.credentials); } else { if (!string.IsNullOrEmpty(settingsStateApiUrl.Value)) { stateClient = new StateClient(new Uri(settingsStateApiUrl.Value), this.credentials); } else { stateClient = new StateClient(this.credentials); } } stateClients[key] = stateClient; } if (!oauthClients.TryGetValue(key, out oauthClient)) { bool isEmulatingOAuthCards = false; // whether to emulate MicrosoftAppCredentials msAppCredentials = this.credentials; // credentials to use for oauth APIs Uri oauthEndpoint = null; // denotes the default endpoint if (String.IsNullOrEmpty(credentials?.MicrosoftAppId) || String.IsNullOrEmpty(credentials?.MicrosoftAppPassword)) { // if there is no AppId or Password, do not use credentials with the OAuthClient msAppCredentials = null; if (IsEmulator(this.address)) { // if using the emulator, this forces the mode to be "emulating OAuthCards" isEmulatingOAuthCards = true; oauthEndpoint = this.serviceUri; } } else if (IsEmulator(this.address) && emulateOAuthCards.Value) { // if the config is asking for the mode of "emulating OAuthCards" isEmulatingOAuthCards = true; oauthEndpoint = this.serviceUri; } else if (!string.IsNullOrEmpty(settingsOAuthApiUrl.Value)) { // if there is a custom OAuth API URI oauthEndpoint = new Uri(settingsOAuthApiUrl.Value); } // create the client if (oauthEndpoint != null) { oauthClient = new OAuthClient(oauthEndpoint, msAppCredentials); } else { oauthClient = new OAuthClient(msAppCredentials); } // if using the emulator, then tell it whether to emulate OAuthCards or not if (IsEmulator(this.address)) { var emulatorOAuthClient = new OAuthClient(this.serviceUri, msAppCredentials); Task.Run(async() => await emulatorOAuthClient.OAuthApi.SendEmulateOAuthCardsAsync(isEmulatingOAuthCards).ConfigureAwait(false)).Wait(); } if (oauthClient != null) { oauthClients[key] = oauthClient; } } }
public async Task GetSigninLink_ShouldThrowOnEmptyConnectionName() { var activity = new Activity(); var client = new OAuthClient(mockConnectorClient, "https://localhost"); await Assert.ThrowsAsync <ArgumentNullException>(() => client.GetSignInLinkAsync(activity, string.Empty)); }
/// <summary>填充用户,登录成功并获取用户信息之后</summary> /// <param name="client"></param> /// <param name="user"></param> protected virtual void Fill(OAuthClient client, IManageUser user) { client.Fill(user); var dic = client.Items; // 用户信息 if (dic != null && user is UserX user2) { if (user2.Mail.IsNullOrEmpty() && dic.TryGetValue("email", out var email)) { user2.Mail = email; } if (user2.Mail.IsNullOrEmpty() && dic.TryGetValue("mail", out email)) { user2.Mail = email; } if (user2.Mobile.IsNullOrEmpty() && dic.TryGetValue("mobile", out var mobile)) { user2.Mobile = mobile; } if (user2.Code.IsNullOrEmpty() && dic.TryGetValue("code", out var code)) { user2.Code = code; } if (user2.Sex == SexKinds.未知 && dic.TryGetValue("sex", out var sex)) { user2.Sex = (SexKinds)sex.ToInt(); } var set = Setting.Current; // 使用认证中心的角色 var roleId = GetRole(dic, true); if (roleId > 0) { user2.RoleID = roleId; var ids = GetRoles(client.Items, true).ToList(); if (ids.Contains(roleId)) { ids.Remove(roleId); } if (ids.Count == 0) { user2.RoleIDs = null; } else { user2.RoleIDs = "," + ids.OrderBy(e => e).Join() + ","; } } else if (user2.RoleID <= 0 && set.DefaultRole > 0) { user2.RoleID = set.DefaultRole; } // 头像 if (user2.Avatar.IsNullOrEmpty()) { user2.Avatar = client.Avatar; } // 下载远程头像到本地,Avatar还是保存远程头像地址 if (user2.Avatar.StartsWithIgnoreCase("http") && !set.AvatarPath.IsNullOrEmpty()) { FetchAvatar(user); } } }
public bool Add(OAuthClient data) { data.AllowedScopes = _scopes.Where(s => data.AllowedScopes.Any(_ => _.Name == s.Name)).ToList(); _clients.Add((OpenIdClient)data.Clone()); return(true); }
/// <summary>获取OAuth客户端</summary> /// <param name="name"></param> /// <returns></returns> public virtual OAuthClient GetClient(String name) => OAuthClient.Create(name);
public Task <bool> Delete(OAuthClient data, CancellationToken cancellationToken) { _clients.Remove(_clients.First(c => c.ClientId == data.ClientId)); return(Task.FromResult(true)); }
public static JObject ToDto(this OAuthClient client) { var result = new JObject { { "client_id", client.ClientId }, { "create_datetime", client.CreateDateTime }, { "update_datetime", client.UpdateDateTime }, { "preferred_token_profile", client.PreferredTokenProfile }, { RegisterRequestParameters.TokenEndpointAuthMethod, client.TokenEndPointAuthMethod }, { RegisterRequestParameters.JwksUri, client.JwksUri }, { RegisterRequestParameters.SoftwareId, client.SoftwareId }, { RegisterRequestParameters.SoftwareVersion, client.SoftwareVersion }, { RegisterRequestParameters.TokenSignedResponseAlg, client.TokenSignedResponseAlg }, { RegisterRequestParameters.TokenEncryptedResponseAlg, client.TokenEncryptedResponseAlg }, { RegisterRequestParameters.TokenEncryptedResponseEnc, client.TokenEncryptedResponseEnc }, { RegisterRequestParameters.TokenExpirationTimeInSeconds, client.TokenExpirationTimeInSeconds }, { RegisterRequestParameters.RefreshTokenExpirationTimeInSeconds, client.RefreshTokenExpirationTimeInSeconds } }; if (client.Secrets != null) { result.Add("secrets", new JArray(client.Secrets.Select(_ => _.ToDto()))); } if (client.Contacts != null) { result.Add(RegisterRequestParameters.Contacts, new JArray(client.Contacts)); } if (client.PolicyUris != null) { result.Add(RegisterRequestParameters.PolicyUri, new JArray(client.PolicyUris.Select(_ => _.ToDto()))); } if (client.RedirectionUrls != null) { result.Add(RegisterRequestParameters.RedirectUris, new JArray(client.RedirectionUrls)); } if (client.GrantTypes != null) { result.Add(RegisterRequestParameters.GrantTypes, new JArray(client.GrantTypes)); } if (client.ResponseTypes != null) { result.Add(RegisterRequestParameters.ResponseTypes, new JArray(client.ResponseTypes)); } if (client.ClientNames != null) { result.Add(RegisterRequestParameters.ClientName, new JArray(client.ClientNames.Select(_ => ToDto(_)))); } if (client.ClientUris != null) { result.Add(RegisterRequestParameters.ClientUri, new JArray(client.ClientUris.Select(_ => ToDto(_)))); } if (client.LogoUris != null) { result.Add(RegisterRequestParameters.LogoUri, new JArray(client.LogoUris.Select(_ => ToDto(_)))); } if (client.AllowedScopes != null) { result.Add(RegisterRequestParameters.Scope, new JArray(client.AllowedScopes.Select(_ => _.Name))); } if (client.TosUris != null) { result.Add(RegisterRequestParameters.TosUri, new JArray(client.TosUris.Select(_ => ToDto(_)))); } return(result); }
protected override UserData GetCurrentUser() { return(OAuthClient.GetCurrentUser <FacebookUserData>()); }
protected override UserData GetCurrentUser() { return(OAuthClient.GetCurrentUser <TwitterUserData>()); }
private void loginButton_Click(object sender, EventArgs e) { OAuthClient.Authorize(); }
public SupportController(AppSettings appSettings, OAuthClient oAuthClient) { _appSettings = appSettings; _oAuthClient = oAuthClient; }
protected virtual JObject BuildResponse(OAuthClient oauthClient, string issuer) { return(oauthClient.ToDto(issuer)); }
public static bool IsMatchRedirectUri(this OAuthClient oAuthClient, GetAuthorizeRequest request) { return(IsMatchRedirectUri(oAuthClient, request.redirect_uri)); }
public async Task GetAadTokensAsync_ShouldThrowOnNullResourceUrls() { var client = new OAuthClient(new Uri("http://localhost"), new BotAccessTokenStub("token")); await Assert.ThrowsAsync <ValidationException>(() => client.UserToken.GetAadTokensAsync("user", "connection", null)); }
public static bool IsMatchRedirectUri(this OAuthClient oAuthClient, TokenRequest request) { return(request.grant_type != GrandType.AuthorizationCode || IsMatchRedirectUri(oAuthClient, request.redirect_uri)); }
public void OAuthClient_ShouldNotThrowOnHttpUrl() { var client = new OAuthClient(new Uri("http://localhost"), new BotAccessTokenStub("token")); Assert.NotNull(client); }
public async Task GetUserToken_ShouldThrowOnEmptyConnectionName() { var client = new OAuthClient(new Uri("http://localhost"), new BotAccessTokenStub("token")); await Assert.ThrowsAsync <ValidationException>(() => client.UserToken.GetTokenAsync("userid", null, string.Empty)); }
public async Task SignOutUser_ShouldThrowOnEmptyUserId() { var client = new OAuthClient(new Uri("http://localhost"), new BotAccessTokenStub("token")); await Assert.ThrowsAsync <ValidationException>(() => client.UserToken.SignOutAsync(null, "mockConnection")); }
public void Setup() { clientConsumer = A.Fake<IClientConsumer>(); tokenService = A.Fake<ITokenStorageService>(); httpRequestReader = A.Fake<IHttpRequestReader>(); client = new OAuthClient(clientConsumer, tokenService, httpRequestReader); }
private void ObtainAuthorisation() { string clientId = ConfigurationManager.AppSettings["ClientId"]; string scope = ConfigurationManager.AppSettings["Scope"]; if (authResult == null) { using (OAuthClient client = new OAuthClient(clientId)) { try { //If you have problems connecting try setting the IWebProxy //in the call to client.Authorise below. authResult = client.Authorise(new AuthorisationInfo() { Scope = scope }); //Allow tokens to be used if token was returned. btnUseToken.Enabled = true; } catch (Exception ex) { MessageBox.Show(ex.Message); } } } }
public void UploadFile(byte[] content, string filename, string target) { ocl = DropboxClient.CreateOAuthClient(APP_KEY, APP_SECRET); ai = ocl.GetAuthorizeInfo(); RequestToken = ai.RequestToken; RequestTokenSecret = ai.RequestTokenSecret; redirect_url = ai.AuthorizeUrl; AccessTokenInfo t = ocl.GetAccessToken(RequestToken, RequestTokenSecret); Token = t.Token; TokenSecret = t.TokenSecret; DropboxClient cl = new DropboxClient(APP_KEY, APP_SECRET, Token, TokenSecret); HigLabo.Net.Dropbox.UploadFileCommand ul = new HigLabo.Net.Dropbox.UploadFileCommand(); ul.Root = RootFolder.Sandbox; ul.FolderPath = target; ul.FileName = filename; ul.LoadFileData(content); Metadata md = cl.UploadFile(ul); }