Telegram SetWebHook Self Signed Certificate - ssl

I'm Trying to Send a Self Signed Certificate To telegram .
The Configuration will be done through PostMan And My Bot Server is Ok (tests through getUpdates and action call over ssl connection responded successfully).
Here is what i send to telegram :
api.telegram.org/botMY TOKEN/setWebhook?url=MY SWERVER IP:443/api/webhook
and i DO attach the PUBLICKEY.pem as a binary body to the request.
Here is what i get :
{ "ok": true, "result": true, "description": "Webhook was set" }
the problem is when i check the webHook via getWebHookInfo :
{
"ok": true,
"result": {
"url": "94.183.157.125:443/api/webhook",
"has_custom_certificate": false,
"pending_update_count": 5,
"last_error_date": 1476206652,
"last_error_message": "Connection timed out"
}
}
in which the attribute "has_custom_certificate" : false means it did't get my certificate :\
What am i doing wrong here ?
Any alternatives to PostMan ??
One Step Further
I tried the HttpClient as below but it didn't work eighter :\
public string SetWebHook()
{
FileStream paramFileStream = new FileStream(#"E:\PATH.......\YOURPUBLIC.pem", FileMode.Open);
HttpContent fileStreamContent = new StreamContent(paramFileStream);
var response = string.Empty;
using (var client = new HttpClient())
using (var formData = new MultipartFormDataContent())
{
formData.Add(fileStreamContent, "Certificate", "YOURPUBLIC.pem");
response = client.PostAsync("https://api.telegram.org/botMYTOKEN/setWebhook?url=MYSERVERIP:443/api/webhook", formData).Result.ToString();
}
return response;
}

You must use curl to upload your certificate (pem)
And
You should use HTTPS:// for your url

Related

ASP.NET core blazor webassembly getting token for Identity Server 4 Postman testing

I am trying to test my api with postman in a blazor webassembly asp.net core hosted app with identity server 4 individual accounts. Unfortunately, despite having tried many different configuration options to get a new token, I have been unable to get one. Here is what I've tried
This one results in the postman browser emulator pop up and never finishes.
This one fails but I get the more informative error that info: Microsoft.AspNetCore.Authorization.DefaultAuthorizationService[2] Authorization failed. These requirements were not met: DenyAnonymousAuthorizationRequirement: Requires an authenticated user.
However, when I then try and use the default testing username and password I get Error: unauthorized_client
I followed the set up step by step in this article using the API authorization options instead of the profile service option (and I'm developing locally, not using azure.) What do I need to do to get a token? I appreciate the help, thanks.
EDIT: attempted adding a new Client in ConfigureServices but the same behavior happens with the postman browser emulator pop up and never finishing.
services.AddIdentityServer()
.AddApiAuthorization<ApplicationUser, ApplicationDbContext>(options => {
options.IdentityResources["openid"].UserClaims.Add("name");
options.ApiResources.Single().UserClaims.Add("name");
options.IdentityResources["openid"].UserClaims.Add("role");
options.ApiResources.Single().UserClaims.Add("role");
options.Clients.Add(new IdentityServer4.Models.Client()
{
ClientId = "postman",
AllowedGrantTypes = GrantTypes.Code,
AllowOfflineAccess = true,
ClientSecrets = { new Secret("secret".Sha256()) },
RedirectUris = { "http://localhost:21402/signin-oidc", "https://oauth.pstmn.io/v1/browser-callback" },
PostLogoutRedirectUris = { "http://localhost:21402/" },
FrontChannelLogoutUri = "http://localhost:21402/signout-oidc",
AllowedScopes =
{
IdentityServerConstants.StandardScopes.OpenId,
IdentityServerConstants.StandardScopes.Profile,
IdentityServerConstants.StandardScopes.Email,
"Onero.ServerAPI"
},
});
});
If you're using authorization code grant, use this URL for the callback URL and leave Authorize using browser unchecked. You also need to add the URL to the list of RedirectUris for your app.
https://oauth.pstmn.io/v1/browser-callback
This page just posts a message to the parent of the auth popup (i.e. Postman window)
<script>
let data = {
isAuthCallback: true,
queryString: window.location.search || '',
hash: window.location.hash || ''
};
window.opener.postMessage(data, '*');
</script>
If you don't want to allow this URL (you probably want to protect tokens from 3rd parties) you can host this page in your app.
[HttpGet("postman-callback")]
public IActionResult PostmanCallback()
{
return new ContentResult {
ContentType = "text/html",
StatusCode = 200,
Content = #"
<html><body><script>
let data = {
isAuthCallback: true,
queryString: window.location.search || '',
hash: window.location.hash || ''
};
window.opener.postMessage(data, '*');
</script></body></html>"
};
}
After days of reading the docs and blogs to get an overall picture I finally was able to do it! What I did was the following:
Looked closely at the output from starting up my Server project, which is where I saw this:
That made me realize that I had been using the wrong endpoint for the Auth URL in Postman. So I changed it to https://localhost:5001/connect/authorize. I then used this configuration in Postman
Combined with adding the Postman client like so in the Server's Startup.cs file
services.AddIdentityServer()
.AddApiAuthorization<ApplicationUser, ApplicationDbContext>(options => {
...
options.Clients.Add(new IdentityServer4.Models.Client()
{
ClientId = "Postman",
AllowedGrantTypes = GrantTypes.Code,
AllowOfflineAccess = true,
ClientSecrets = { new Secret("secret".Sha256()) },
RedirectUris = { "http://localhost:21402/signin-oidc", "https://oauth.pstmn.io/v1/browser-callback" },
PostLogoutRedirectUris = { "http://localhost:21402/" },
FrontChannelLogoutUri = "http://localhost:21402/signout-oidc",
AllowedScopes =
{
"Onero.ServerAPI"
},
});;
});
And that finally got that little Postman page to pop up, bring me to the default IdentityServer AuthUI page, login with my default user and there we go, finally get the darn token.
Biggest take away: make sure to read the server output to make sure your endpoints are correct so you can fill out the parameters in Postman correctly.
Thanks for the help!

Website login automation without XHR request

Background: I'm trying to automate local ISP login using simple request in python (without selenium, that's last resort as I'm trying to learn other ways too).
Upon inspecting website, submit button calls the validateForm() function.
function validateForm(){
var input=true;
var uname = "?"+document.login.Username.value+"+/#";
var pwd = "?"+document.login.Password.value+"+/#";
document.login.LoginName.value=encodeURIComponent(uname);
document.login.LoginPassword.value=encodeURIComponent(pwd);
if (input==true&&document.login.checker.checked)
toMem(this);
}
function toMem(a) {
newCookie('theName', document.login.Username.value); // add a new cookie as shown at left for every
newCookie('theEmail', document.login.Password.value); // field you wish to have the script remember
}
function newCookie(Username,value,days) {
var days = 30; // the number at the left reflects the number of days for the cookie to last
// modify it according to your needs
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString(); }
else var expires = "";
document.cookie = Username+"="+value+expires+"; path=/";
}
No where it is sending any request.
The website doesn't make any XHR request. I'm not able to grasp how they are making the login work. I found one request from 'other' tab of network (chrome dev tools). From where it is generating this request!!!
fetch("http://ip:port/Sristi3/SRISTI/loginUI.do2", {
"headers": {
"accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
"accept-language": "en-US,en;q=0.9,bn;q=0.8",
"cache-control": "no-cache",
"content-type": "application/x-www-form-urlencoded",
"pragma": "no-cache",
"upgrade-insecure-requests": "1"
},
"referrer": "http://ip:port/Sristi3/SRISTI/Login.jsp?",
"referrerPolicy": "no-referrer-when-downgrade",
"body": "Username=username&Password=password&LoginName=encodedusername&LoginPassword=encodedpass",
"method": "POST",
"mode": "cors",
"credentials": "include"
});
I tried to simply paste the request in console but this also does not make the login. Returned a promise with [[PromiseStatus]]: "rejected" and [[PromiseValue]]: TypeError: Failed to fetch, message: "Failed to fetch", stack: "TypeError: Failed to fetch". What and where to look for? Any help?

405 error with JIRA REST API using node js

I am trying to create an automated JIRA ticket using the REST API but I keep getting a 405 error.
I am using the examples here: https://developer.atlassian.com/server/jira/platform/jira-rest-api-examples/
Also, when I visit the post URL directly I do not get any errors so I doubt it is a server issue. Any ideas?
var Client = require('node-rest-client').Client;
client = new Client();
// Provide user credentials, which will be used to log in to Jira.
var loginArgs = {
data: {
"username": "user",
"password": "pass"
},
headers: {
"Content-Type": "application/json"
}
};
client.post("https://jira.mydomain.com/rest/auth/1/session", loginArgs, function(data, response) {
if (response.statusCode == 200) {
//console.log('succesfully logged in, session:', data.session);
var session = data.session;
// Get the session information and store it in a cookie in the header
var args = {
headers: {
// Set the cookie from the session information
cookie: session.name + '=' + session.value,
"Content-Type": "application/json"
},
data: {
// I copied this from the tutorial
"fields": {
"project": {
"key": "REQ"
},
"summary": "REST ye merry gentlemen.",
"description": "Creating of an issue using project keys and issue type names using the REST API",
"issuetype": {
"name": "Request"
}
}
}
};
// Make the request return the search results, passing the header information including the cookie.
client.post("https://jira.mydomain.com/rest/api/2/issue/createmeta", args, function(searchResult, response) {
console.log('status code:', response.statusCode);
console.log('search result:', searchResult);
});
} else {
throw "Login failed :(";
}
});
I am expecting the Jira ticket of type REQ to be created with the details I added in the fields section.
I believe you are using the incorrect REST API; what you're currently doing is doing a POST to Get create issue meta which requires a GET method, hence, you're getting a 405. If you want to create an issue, kindly use Create issue (POST /rest/api/2/issue) instead.

ionic 2: http get request not working (proxy added)

I'm using Http from #angular/http to send GET requests, but the server is not receiving the request. The generated urls are correct because when I log them and open them in browser (I've tried all of Chrome, Firefox and Safari), the server does receive these requests.
This is how I am doing this:
let logButtonUrl = this.urlGenerator.generateTiramisuUrlTemp(this.servletPath,
argMap);
console.log("logButtonUrl:"+logButtonUrl);
return this.http.get(logButtonUrl).map(this.writeSuccess);
Function writeSuccess:
private writeSuccess(res: Response) {
let body = res.json();
let rows_affected = body.data[0].rowsAffected;
if (rows_affected == "1") {
return true;
} else {
return false;
}
}
I got no error message in browser console, so it's probably not because of the CORS issue discussed here:
http://blog.ionic.io/handling-cors-issues-in-ionic/
I also tried using a proxy. I added this in ionic.config.json:
{
"path": "/backendTemp",
proxyUrl": "http://128.237.217.70:8080" /*the ip address of the target server*/
}
And replace the ip address in my generated urls with "/backendTemp". Still not working.
Any suggestions/thoughts on this? Thanks a lot!
Use the $http (https://docs.angularjs.org/api/ng/service/$http):
.controller('RequestCtrl', function ($http) {
$http({
method: 'GET',
url: 'http://128.237.217.70:8080/backendTemp'
}).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});

Microsoft Graph API One Drive Unable to read JSON request payload

I receive the following error when I make an PUT API CALL to upload a document to OneDrive using Microsoft Graph API. It was working earlier, it has stopped working suddenly.
{\r\n \"error\": {\r\n \"code\": \"BadRequest\",\r\n
\"message\": \"Unable to read JSON request payload. Please ensure
Content-Type header is set and payload is of valid JSON format.\",\r\n
\"innerError\": {\r\n \"request-id\":
\"133ac360-740d-4823-9a93-1090616d925b\",\r\n \"date\":
\"2016-04-11T06:24:59\"\r\n }\r\n }\r\n}
The code which I am executing is
using (var client = new HttpClient())
{
string url = https://graph.microsoft.com/v1.0/me/drive/root:/Test.xslx:/content
using (var request = new HttpRequestMessage(HttpMethod.Put, url))
{
string headerAcceptTest = "application/json";
MediaTypeWithQualityHeaderValue headerAccept = new MediaTypeWithQualityHeaderValue(headerAcceptTest);
request.Headers.Accept.Add(headerAccept);
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
request.Content = new ByteArrayContent(data);
request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
using (var response = await client.SendAsync(request))
{
if (response.StatusCode == HttpStatusCode.Created)
{
string responseContentAsString = await response.Content.ReadAsStringAsync();
}
}
}
}
Any clue where am I going wrong?
There was an issue with a new build that was rolled out over the weekend, and we have now reverted it. The issue should now be resolved.
I saw a change in behavior of the One Drive API on uploading a file to One Drive.( https://dev.onedrive.com/items/upload_put.htm) , this API call fails with error.
Sample Request :
PUT https://graph.microsoft.com/v1.0/me/drive/items/root/children/732f64cc-0719-4a24-abe8-6fd39cb96403.txt/content?%40name.conflictBehavior=replace
Response
{
"error": {
"code": "BadRequest",
"message": "Unable to read JSON request payload. Please ensure Content-Type header is set and payload is of valid JSON format.",
"innerError": {
"request-id": "7e734f93-3033-4bb4-a433-c5d9c400f46e",
"date": "2016-04-11T02:33:35"
}
}
}
Actually it was working fine until 8th April 2016, The Documentation says its text/plain content type , why is this expecting application/json