Telegram API error USER_DEACTIVATED after authentication - c#

I'm using a simple client for Telegram API on C# using TLSharp library.
var appId = ConfigurationManager.AppSettings["appId"];
var appSecret = ConfigurationManager.AppSettings["appSecret"];
var clientPhone = ConfigurationManager.AppSettings["clientPhone"];
...
var session = new FileSessionStore();
client = new TelegramClient(int.Parse(appId), appSecret, session, clientPhone);
await client.ConnectAsync();
if (!client.IsUserAuthorized())
{
hash = await client.SendCodeRequestAsync(clientPhone);
await client.MakeAuthAsync(clientPhone, hash, code);
}
var state = await client.SendRequestAsync<TLState>(new TLRequestGetState());
Here I'm getting exception USER_DEACTIVATED.
So, I tried to get new clean account (with new phone number), login throgth mobile telegram client, after that login to web version, searched some channels, subscribe, sent some messages. After that I tried to login with my client app and at FIRST request got same error.
This issue started to reproduce just this week. Before that I successfully used several test accounts, getting messaged, worked with media and dialogs, no any deactivate errors.
What I'm doing wrong? What limits or policies was broked my application and does exists any way to restore my app?
UPDATE
Tried to register new application from another account. After that, repeat same actions with new phone number and another PC with another IP address - banned after first request.
What is going on? Why can telegram blocks my accounts?

Related

Sending a chat message with Microsoft Teams

Is there anyway to send a teams message to a channel or chat that doesn't involve the end user of an app being asked to sign in? What I am trying to do is something like this:
User does something on my web app
Without user interaction, my web app sends a message to a chat or channel on Microsoft Teams
I tried to send it as myself for testing (planned on using a service account later), but after some reading, I've come to find out isn't possible using application API permissions, as documented here:
Here is the code I have that would work if I wasn't using application permissions:
var tenantId = "...";
var clientId = "...";
var clientSecret = "...";
var clientSecretCredential = new ClientSecretCredential(tenantId, clientId, clientSecret);
var graphClient = new GraphServiceClient(clientSecretCredential);
var chatMessage = new ChatMessage
{
Body = new ItemBody
{
Content = "Hello World"
}
};
await graphClient.Teams["..."].Channels["..."].Messages.Request().AddAsync(chatMessage);
It throws this exception:
Microsoft.Graph.ServiceException: 'Code: Unauthorized
Message: Message POST is allowed in application-only context only for import purposes. Refer to https://docs.microsoft.com/microsoftteams/platform/graph-api/import-messages/import-external-messages-to-teams for more details.
Inner error:
AdditionalData:
date: 2023-02-16T04:46:02
request-id: 3cbd9dc8-a86a-43e9-a5fe-e9e9b3433566
client-request-id: 3cbd9dc8-a86a-43e9-a5fe-e9e9b3433566
ClientRequestId: 3cbd9dc8-a86a-43e9-a5fe-e9e9b3433566
Is it possible to send a message to a teams chat/channel without user interaction?
As per the documentation, application permissions are supported only for migration purposes. For this, your team and channel both must be created in a migrated state. However, you can use this graph API in a delegated context (with signed-in user).
Reference Document: https://learn.microsoft.com/en-us/graph/api/chatmessage-post?view=graph-rest-1.0&tabs=csharp
Using proactive messages you can send a message to a teams chat/channel without user interaction.
Reference Document: https://learn.microsoft.com/en-us/microsoftteams/platform/resources/bot-v3/bot-conversations/bots-conv-proactive

Reply to bot from web API

In short, I'm trying to resume a conversation with a bot after a successful web API login. But I'm having trouble sending a reply to the bot. I have the ChannedId as well as the UserId. I'm not sure whether this is enough. I'm also not sure how to construct a new ConversationReference, which from my understanding is required to perform the reply (Conversation.ResumeAsync)
I have looked at the following example: MicrosoftDX/AuthBot, but the example uses ResumptionCookie which is deprecated. Furthermore, the example utilizes Azure AD authentication. I use cookie authentication in my web API
I require a response from my web API to continue the login form flow on the bot.
var conversationReference = ???;
// Create the message that is send to conversation to resume the login flow
var message = conversationReference.GetPostToUserMessage();
using (var scope = DialogModule.BeginLifetimeScope(Conversation.Container, message))
{
var client = scope.Resolve<IConnectorClient>();
var sc = scope.Resolve<IStateClient>();
await Conversation.ResumeAsync(conversationReference, message);
}

MSAL Error message AADSTS65005 when trying to get token for accessing custom api

I downloaded the example below to get an access token from MS Graph and it worked fine. Now I changed the code to get a token from a custom web API. On apps.dev.microsoft.com I registered a client application and an the API.
Client and server registration in AD
private static async Task<AuthenticationResult> GetToken()
{
const string clientId = "185adc28-7e72-4f07-a052-651755513825";
var clientApp = new PublicClientApplication(clientId);
AuthenticationResult result = null;
string[] scopes = new string[] { "api://f69953b0-2d7f-4523-a8df-01f216b55200/Test" };
try
{
result = await clientApp.AcquireTokenAsync(scopes, "", UIBehavior.SelectAccount, string.Empty);
}
catch (Exception x)
{
if (x.Message == "User canceled authentication")
{
}
return null;
}
return result;
}
When I run the code I login to AD via the dialog en get the following exception in the debugger:
Error: Invalid client Message = "AADSTS65005: The application
'CoreWebAPIAzureADClient' asked for scope 'offline_access' that
doesn't exist on the resource. Contact the app vendor.\r\nTrace ID:
56a4b5ad-8ca1-4c41-b961-c74d84911300\r\nCorrelation ID:
a4350378-b802-4364-8464-c6fdf105cbf1\r...
Error message
Help appreciated trying for days...
For anyone still striking this problem, please read this:
https://www.andrew-best.com/posts/please-sir-can-i-have-some-auth/
You'll feel better after this guy reflects all of your frustrations, except that he works it out...
If using adal.js, for your scope you need to use
const tokenRequest = {
scopes: ["https://management.azure.com/user_impersonation"]
};
I spent a week using
const tokenRequest = {
scopes: ["user_impersonation"]
};
.. since that is the format that the graph API scopes took
As of today, the V2 Endpoint does not support API access other than the Microsoft Graph. See the limitations of the V2 app model here.
Standalone Web APIs
You can use the v2.0 endpoint to build a Web API that is secured with
OAuth 2.0. However, that Web API can receive tokens only from an
application that has the same Application ID. You cannot access a Web
API from a client that has a different Application ID. The client
won't be able to request or obtain permissions to your Web API.
For the specific scenario that you are trying to accomplish, you need to use the V1 App Model (register apps on https://portal.azure.com).
In the very near future, V2 apps will be enabled to call other APIs other than Microsoft Graph, so your scenario will be supported, but that is just not the case today. You should keep an eye out on our documentation for this update.
In your (server) application registration in AAD, you need to specify your scopes in the oauth2Permissions element.
You may already have a user_impersonation scope set. Copy that as a baseline, give it a unique GUID and value, and then AAD will let your client request an access token with your new scope.

LoginAsync sometimes times out

I have some authentication code for an Azure hosted mobile app that is being called from a WPF client. It attempts to authenticate the user as part of the initialisation of a Prism module that contains an authentication service. The async method to authenticate is written as follows:
public async Task AcquireTokenAndAuthenticateWebApiAsync()
{
try
{
//todo these are hardcoded :-( ... need to come from app settings!!
// settings for authentication
string resourceId = "https://windinspectordevmobileappservice.azurewebsites.net";
//string resourceId = "http://localhost:51293/";
string clientId = "5fe3b968-1d23-4667-9c31-86fac4ab4aec";
Uri redirectUri = new Uri("https://windinspectordevmobileappservice.azurewebsites.net/.auth/login/done"); // Page to say you have sucessfully signed in
const string appServiceUrl = "https://windinspectordevmobileappservice.azurewebsites.net";
string authorityUri = "https://login.windows.net/dnv.onmicrosoft.com";
this.authContext = new AuthenticationContext(authorityUri);
// authenticate against the AD
var result = await authContext.AcquireTokenAsync(
resourceId, clientId, redirectUri,
new PlatformParameters(PromptBehavior.Auto, false));
this.authResult = result;
// authenticate against the web api
Client = new MobileServiceClient(appServiceUrl);
JObject payload = new JObject();
payload["access_token"] = authResult.AccessToken;
var user = await Client.LoginAsync(
MobileServiceAuthenticationProvider.WindowsAzureActiveDirectory,
payload).ConfigureAwait(false);
this.authenticatedUserName = this.authResult.UserInfo.DisplayableId;
}
catch (InvalidOperationException e)
{
}
}
About 50% of the time the call to LoginAsync is successful. However, at other times the LoginAsync call simply times out (the task times out with an exception). What could cause this?
I've attempted to turn on the logs in the client, but see no reason for the timeout in the logs:
Application Log from Successful LoginAsync Call:
2017-01-27T16:24:29 PID[23292] Verbose Received request: POST https://windinspectordevmobileappservice.azurewebsites.net/.auth/login/aad
2017-01-27T16:24:29 PID[23292] Verbose JWT validation succeeded. Subject: '__HeuajpWfXmUxZBrDvwAqcV0UOirMVrs5iCwvpnrrY', Issuer: 'https://sts.windows.net/adf10e2b-b6e9-41d6-be2f-c12bb566019c/'.
2017-01-27T16:24:29 PID[23292] Information Login completed for 'max.palmer#dnvgl.com'. Provider: 'aad'.
2017-01-27T16:24:29 PID[23292] Information Sending response: 200.77 OK
2017-01-27 16:24:29 WINDINSPECTORDEVMOBILEAPPSERVICE POST /.auth/login/aad X-ARR-LOG-ID=4f08
Application Log from LoginAsync call that times out:
734a-75e2-4674-a9c8-bd74caa1aa3f 443 - 80.5.95.115 ZUMO/3.1+(lang=Managed;+os=Windows;+os_version=6.2.0.9200;+arch=Win32NT;+version=3.1.50105.0) - - windinspectordevmobileappservice.azurewebsites.net 200 77 0 1089 2739 109
2017-01-27T16:26:29 No new trace in the past 1 min(s).
2017-01-27T16:26:34 PID[23292] Verbose Received request: POST https://windinspectordevmobileappservice.azurewebsites.net/.auth/login/aad
2017-01-27T16:29:29 No new trace in the past 1 min(s).
NB looking at these logs, when the login call is successful, I see "JWT validation succeeded", when it is not, I never see this line and it times out. I've checked many samples online for using this authentication pattern and the code looks good to me. I've also tried shifting the code to be called via an async command Execute method so that I'm async all the way (up).
Any thoughts on what else I can do to try to understand what might be the cause of the timeout in some cases?
One question I had is that the source code for MobileServiceClient is hosted at:
https://github.com/Azure/azure-mobile-services
However, this repository is marked as deprecated (or at least Mobile Services is deprecated in favour of Mobile Apps). I presume this class is still the one to use with Mobile Apps?
Is there any way I can step into the code? Do I need to fetch the source from Git and debug that?

tweetsharp - app stops being able to tweet after a few hours

I have a asp.net 4.5 webforms site that allows users to link their account to twitter and tweet directly from my site.
My app is registered with twitter and I am able to successfully authorise my app for the user's account and initially can tweet fine, but after a few hours the tweets stop working. I am using tweetsharp to handle the authorisation.
my code is:
TwitterClientInfo twitterClientInfo = new TwitterClientInfo();
twitterClientInfo.ConsumerKey = ConsumerKey;
twitterClientInfo.ConsumerSecret = ConsumerSecret;
var requestToken = new OAuthRequestToken { Token = oauthtoken };
TwitterService twitterService = new TwitterService(ConsumerKey, ConsumerSecret);
OAuthAccessToken accessToken = twitterService.GetAccessToken(requestToken, oauthverifier);
twitterService.AuthenticateWith(accessToken.Token, accessToken.TokenSecret);
TwitterUser user = twitterService.VerifyCredentials(new VerifyCredentialsOptions());
SendTweetOptions options = new SendTweetOptions();
options.Status = tweetText;
twitterService.SendTweet(options);
what i have noticed is that while the app is successfully tweeting, the accessToken.Token value that is being used to authenticate the user has a proper value (a long string of numbers and upper/lowercase characters) however when it stops tweeting the accessToken.Token value is just a single question mark "?".
Twitter says it doesn't expire tokens so i am at a loss to understand what is happening or how it can be resolved? if i went in to my twitter account and deauthorised my app and went through the authorisation again it would work fine for a few hours, but obviously that's not something i can ask my users to do.
can anyone suggest a resolution to this - either to stop the accessToken value becoming ? or to handle it and get a proper value if it does (without reauthorising the app)
Well, without beginning to understand the actual issue, I managed to fix it
Instead of retrieving the access token every time via:
var requestToken = new OAuthRequestToken { Token = oauthtoken };
OAuthAccessToken accessToken = twitterService.GetAccessToken(requestToken, oauthverifier);
twitterService.AuthenticateWith(accessToken.Token, accessToken.TokenSecret);
i only do that once and store accessToken.Token and accessToken.TokenSecret in the database and retrieve them when tweeting and supply them
twitterService.AuthenticateWith(accessTokenFromDB, accessokenSecretFromDB);
I have seen somewhere that Twitter doesn't expire tokens, so this should work. Certainly it's been working for me all weekend whereas the original code would stop working after a few hours.
Thought this might help some others who have the same issue.

Categories