API call not working from Azure - asp.net-mvc

I have an test API (get method) which I have deployed on production with test data.
This API if I call from anywhere directly from Browser , it works perfectly.
I created a web application, just a submit click button, to call that API. I deployed web application on Azure.
It doesn't work. It keeps giving me Operation has timed out exception. API doesn't get a hit. API get request works from browser. I tried to using logger in api, log file remains blank.
Can please anyone help me in this?
EDIT:
When I call through browser, I get following response
This XML file does not appear to have any style information associated with it. The document tree is shown below.
<ArrayOfMessage xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/ValidationWebApi">
<Message>
<MessageDesc>
[{"NO":"111","NAME":"Miss Jane ","EXTENSION":"","MOBILE":"","EMAIL_ID":SOME EMAIL ID}]
</MessageDesc>
<MessageId i:nil="true"/>
<WebApiInfo i:nil="true"/>
<isValid>1</isValid>
</Message>
</ArrayOfMessage>
But if I call through Azure hosted site, I get following error...
`System.Net.WebException: The operation has timed out at System.Net.WebClient.DownloadDataInternal(Uri address, WebRequest& request) at System.Net.WebClient.DownloadString(Uri address) at System.Net.WebClient.DownloadString(String address) at Test.btnSubmit_Click(Object sender, EventArgs e)
Edit:
The way this has been called to check whether it gets hit or not is as follows
This is button click event. we are just trying to print this response on screen. Get method is used.
string strApi = "https://domain.com/myApiName/Jane";
try
{
using (var client = new WebClient())
{
var result = client.DownloadString(strApi);
Response.Write(result);
}
}
I get exception on var result statement. It waits there for sometime and gives exception.
Regards,
Ashay

Try enabling CORS ( cross-origin HTTP request ) to you API controller ..
Thanks
Kasam Shaikh

Related

Slack Conversations API conversations.kick returning "channel_not_found" for a public channel

I am writing a Slack integration that can boot certain users out of public channels when certain conditions are met. I have added several OAuth scopes to the bot token, including the following:
channels:history
channels:manage
channels:read
chat:write
chat:write.public
groups:write
im:write
mpim:write
users:read
I am writing my bot in Python using the slack-bolt library and asyncio. However when I try to invoke this code:
await app.client.conversations_kick(channel=channel_id, user=user_id)
I get the following error:
slack_sdk.errors.SlackApiError: The request to the Slack API failed. (url: https://www.slack.com/api/conversations.kick)
The server responded with: {'ok': False, 'error': 'channel_not_found'}
I know for a fact that both the channel_id and user_id arguments I'm passing in are valid. The channel ID I'm using is the string C01PAE3DB0A. I know it is valid because I can use the very same value for channel_id in the following API call:
response = await app.client.conversations_info(channel=channel_id)
And when I call conversations_info like that I get all of the information about my channel. (The same is true for calling users_info with the user_id - it returns successfully.) So why is that when I pass my valid channel_id parameter to conversations_kick I consistently receive this channel_not_found error? What am I missing?
So I got in touch directly with Slack support about this and they confirmed that there is a bug on their end. Specifically, the bug is that I should have received a restricted_action error response instead of a channel_not_found response. Apparently this is a known issue that is on their backlog.
The reason the API call would (try to) return this restricted_action error is simply because there is a workspace setting that, by default, prevents non-admins from kicking people out of public channels. Furthermore, this setting can only be changed by the workspace owner - one tier above admins.
But assuming you are the owner of the Slack workspace, you simply have to log into the Settings & Permissions page, which should look something like this:
And then you have to change the setting labeled "People who can remove members from public channels" from "Workspace admins and owners only (default)" to "Everyone, except guests."
Once I made that change, my API calls started succeeding.

Azure AD Ms Identity callback URL (error AADSTS50011)

I'm integrating Azure AD and MS-Identity on a web app with Angular.
It works on my machine, but when I deploy it, I get an issue with the callback URL.
First, to make sure the callback URL is ok, I extract it from the microsoft login popup window's URL:
Then, I url decode the content. The URL seems fine and it is available in my Azure app's redirect URL.
Then I login to Microsoft normally and I get this error (AADSTS50011):
Then I inspect the URL again (inside the query string from the urldecoded popup window's URL) and now the URL seems to have been "tampered with".
It's now something like this:
http://somedomain:80/some_page/somequerystring
instead of
https://somedomain/some_page/somequerystring
so I wonder if it's part of the problem or if it's normal behavior.
It is also mentionned "If you contact your administrator, send this info to them." I suppose I'm the "administrator" so what can I do with that "Copy info to clipboard" info to investigate the problem?
Is your application hosting on http (80) or https (443)? If your app service is terminating your TLS connection and handling that for you instead of your app, your sign-on will construct the redirect using the http request scheme. I hooked into the OnRedirectToIdentityProvider event to correct the scheme.
services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApp(options =>
{
Configuration.Bind("AzureAd", options);
options.Events ??= new OpenIdConnectEvents();
options.Events.OnRedirectToIdentityProvider += _fixRedirect;
});
...
private async Task _fixRedirect(RedirectContext context)
{
context.Request.Scheme = "https";
if(!context.ProtocolMessage.RedirectUri.StartsWith("https"))
context.ProtocolMessage.RedirectUri =
context.ProtocolMessage.RedirectUri.Replace("http", "https");
await Task.CompletedTask;
}

Is there a way to get the URL after a redirect in postman?

I'm working with an API, which after filling out the log in form on their website, redirects back to our website, with a unique code at the end of the URL.
Example URL after redirect:
https://www.mywebsite.com/?code=12431453154545
I have been unable to find a way of viewing this URL in Postman.
Ideally I need to be able to work with that URL to extract the code and store it as a variable.
Any help will be muchly appreciated. I've been trying this all day :( .
When you turn off following redirects in Postman settings, you will be able to inspect 3xx HTTP response which will contain Location header with the URL you want to read.
const url = require("url");
var location = pm.response.headers.get("location");
if (typeof location !== typeof undefined) {
var redirectUrl = url.parse(location, true);
query = redirectUrl.query;
if ("code" in query) {
pm.globals.set("code", query.code);
console.log(pm.globals.get("code"));
}
}
Note that this solution will not work when multiple subsequent redirects happen as you will be inspecting only the first 3xx response. You could solve this by following redirects manually and sending your own requests from Postman script as described in Postman manual.

Get access_token using Windows Service's or Console App. for Instagram Api

My windows service is collect instagram datas from instagram api. I was using client_id but this uses format is removed.
Instagram api is want to access_token but Oauth 2.0 is web-based. or not?
I using .NET and my application type is windows service and web request don't work because this call url: "https://www.instagram.com/oauth/authorize/?client_id=CLIENT-ID&redirect_uri=REDIRECT-URI&response_type=code" is have one more contain redirect. so web response haven't contain my web application link also auto redirect is open..
what should I do?
Thanks..
Steps to get instagram access token
register ur application in instagram account.
get a client id and client secret.
Step 1: HIT the below url.
https://api.instagram.com/oauth/authorize/?client_id=CLIENT-ID&redirect_uri=REDIRECT-URI&response_type=code
step 2: after hitting above url you will be taken to login page. enter the login credentials and take the code from address bar.
it will be live for only 20 seconds i guess.
step 3: The code which you got put it in CODE parameter in the below source code, then run the below code in console application n hit breakpoint at response. you will get access token and userid.
public void GetDataInstagramToken()
{
try
{
NameValueCollection parameters = new NameValueCollection();
parameters.Add("client_id", "CLIENT-ID");
parameters.Add("client_secret", "CLIENT-Secret");
parameters.Add("grant_type", "authorization_code");
parameters.Add("redirect_uri", "REDIRECT-URI");
parameters.Add("code", "CODE");
WebClient client = new WebClient();
var result = client.UploadValues("https://api.instagram.com/oauth/access_token", "POST", parameters);
var response = System.Text.Encoding.Default.GetString(result);
// deserializing nested JSON string to object
var jsResult = (JObject)JsonConvert.DeserializeObject(response);
string accessToken = (string)jsResult["access_token"];
}
catch (Exception)
{
//exception catch
}
}

FacebookRealtimeUpdateController Override Post and return 'OK'

Using Mvc.Facebook.Realtime the FacebookRealtimeUpdateController provides a process for handling user events (HandleUpdateAsync) , but not for page events.
Microsoft.AspNet.Mvc.Facebook.Realtime Namespace
I have managed to process page events by overriding the 'POST'
Public Overrides Function Post() As Task(Of Net.Http.HttpResponseMessage)
Dim content = Request.Content
Dim jsonContent As String = content.ReadAsStringAsync().Result
Dim ConvertedJson As RealTimeEvent = JsonConvert.DeserializeObject(Of RealTimeEvent)(jsonContent)
' Do something with the page events
Return MyBase.Post
End Function
However Facebook resends all events immediately , which I believe is because I am not returning a '200 OK' back to Facebook. (See quote)
First you'll need to prepare the page that will act as your callback URL. This URL will need to be accessible by Facebook servers, and be able to receive both the POST data that is sent when an update happens, but also accept GET requests in order to verify subscriptions.
This URL should always return a 200 OK HTTP response when invoked by Facebook.
I wiresharked my server and I do not see a 200 OK HTTP response, so I believe this something to do with the way I am overloading the post.
Can I somehow return an OK response from my overridden function or maybe it would be better to drop the whole Microsoft.AspNet.Mvc.Facebook.Realtime solution and just handle the Subscription GETs and Posts from facebook myself?
Update: I turned off "only my own code' and I can see an exception occurring in the AspNet.MVC.Facebook.dll.
So new question, How do I isolate this exception?
For others looking.
The issue was actually the HandleUpdateAsync function which must be overridden. This is fired after the 'Post'
If you don't return a valid task the exception is thrown inside AspNet.MVC.Facebook.dll and Facebook is never given a 200 OK.
I was using This blog on how to use the FacebookRealtimeUpdateController but in that version the 'HandleUpdateAsync' does not return a task and the processing is done in the function.
So by creating a task that does nothing , everything appears to be working fine.
Public Overrides Function HandleUpdateAsync(notification As ChangeNotification) As Task
Dim newtask As New Task(New System.Action(Sub()
Dim x As String = ""
End Sub))
Return newtask
End Function
Edit: But it creates a massive memory leak which cannot be cleared even with recycling..
So the real solution is to just create your own controller and forget the FacebookRealtimeUpdateController completely.
Very easy to do and saves allot of hassle!

Resources