Unable to get IAM security credentials from EC2 Instance Metadata Service error when using Aws Sdk in UWP - wpf

I'm working with Aws Sdk and I'm trying to implement a login UI using UWP. I followed this online tutorial (which is for WPF) and I tried to make it works for the Universal Windows Platform as well.
The core part of the source code is the following (please note that is 90% similar to the one posted in the tutorial. The "only difference" is that I used
InitiateAuthAsync
instead of
AdminInitiateAuthAsync
<!-- language: lang-cs -->
private readonly AmazonCognitoIdentityProviderClient _client;
private readonly string _clientId = "32fsoifj93fjsiispat";
public MainPage()
{
this.InitializeComponent();
var amazonCognitoIdentityProviderConfig = new AmazonCognitoIdentityProviderConfig();
amazonCognitoIdentityProviderConfig.ServiceURL = "https://cognito-idp.eu-central-1.amazonaws.com/";
_client = new AmazonCognitoIdentityProviderClient(amazonCognitoIdentityProviderConfig);
}
private async Task<bool> CheckPasswordAsync(string userName, string password)
{
try
{
List<HttpHeader> httpHeaders = new List<HttpHeader>();
HttpHeader httpHeader = new HttpHeader
{
HeaderName = "X-Amz-Target",
HeaderValue = "AWSCognitoIdentityProviderService.InitiateAuth"
};
httpHeaders.Add(httpHeader);
httpHeader = new HttpHeader
{
HeaderName = "Content-Type",
HeaderValue = "application/x-amz-json-1.1"
};
httpHeaders.Add(httpHeader);
var authReq = new InitiateAuthRequest()
{
ClientId = _clientId,
AuthFlow = AuthFlowType.USER_PASSWORD_AUTH,
};
authReq.AuthParameters.Add("USERNAME", userName);
authReq.AuthParameters.Add("PASSWORD", password);
var authResp = await _client.InitiateAuthAsync(authReq);
return true;
}
catch (Exception ex)
{
return false;
}
}
Please consider that it is working properly with WPF framework. I'm able to get the TokenId and RefreshToken.
But if I try to copy and paste the same code in UWP I get the exception:
'Unable to get IAM security credentials from EC2 Instance Metadata Service.'
And if I try to investigate with Fiddler I get the following error:
[Fiddler] The connection to '169.254.169.254' failed. Error: NetworkUnreachable (0x2743). System.Net.Sockets.SocketException A socket operation was attempted to an unreachable network 169.254.169.254:80
I really can't understand why it tries to connect to the '169.254.169.254' address. Googling around I found other people experiencing the same issue (for example here). Do you have any idea?

Related

Creates a default database in Firestore using Google.Apis.Appengine.v1 in C# library

I wanted to create cloud firestore database programmatically using c#, but I am getting error when I run the code. How would I fix permission related issue I am facing? Below is the code and error
private static AppengineService _appEngineService;
public static void IntializeAppEngine() {
GoogleCredential credential = GoogleCredential.GetApplicationDefault();
if (CloudManager.Credential.IsCreateScopedRequired)
{
credential = CloudManager.Credential.CreateScoped(
AppengineService.Scope.CloudPlatform);
}
_appEngineService = new AppengineService(
new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = CloudManager.ApplicationName
});
}
public static void AddCloudFirestore() {
IntializeAppEngine();
var body = new Application {
LocationId = "us-east1",
Id = "projects/" + CloudManager.ProjectId
};
var res = _appEngineService.Apps.Create(body).Execute();
}
Error:
Unhandled exception. The service appengine has thrown an exception.
HttpStatusCode is Forbidden.
Google.Apis.Requests.RequestError
The caller does not have permission [403]
Errors [
Message[The caller does not have permission] Location[ - ] Reason[forbidden] Domain[global]
]
Google.GoogleApiException: The service appengine has thrown an exception. HttpStatusCode is Forbidden. The caller does not have permission
at Google.Apis.Requests.ClientServiceRequest`1.ParseResponse(HttpResponseMessage response)
at Google.Apis.Requests.ClientServiceRequest`1.Execute()
at CloudResourceManager.FirebaseManagement.AddCloudFirestore()
Instead of Appengine, Cloud Firestore REST API can be used as Sarah suggested.
In c# Google.Apis.Firestore.v1 can be used to create cloud firestore.

Trying to make OneDrive connector in Windows Form app

I am making a WinForm application using C#. When i try to connect OneDrive using SharePoint Client Object Model it gives me an error of "Value cannot be null".
Please guide me where i am making mistake. I need guidance on this.
private void GetClientContext()
{
using (ClientContext clientContext = new ClientContext("https://techiesworld-my.sharepoint.com/"))
{
SecureString passWord = new SecureString();
//passtxt.Text = passWord.ToString();
//foreach (char c in passtxt.Text.ToCharArray()) passWord.AppendChar(c);
clientContext.Credentials = new SharePointOnlineCredentials(accountxt.Text, passWord);
Web web = clientContext.Web;
clientContext.Load(web);
clientContext.ExecuteQuery();
MessageBox.Show(web.Title);
}
I am getting exception on clientContext.ExecuteQuery() function.

Why do I get ClassCastException using HttpURLConnection in AppEngine?

I try to call an external web service (not mine) from my GWT application working with App Engine.
I know it's impossible to do it from the client due to the SOP (Same Origin Policy) and RequestBuilder is not a solution on the server. I followed the tutorial on the web site and using java.net as well
Here is the client
AsyncCallback<CustomObject> callback = new AsyncCallback<CustomObjectCustomObject>() {
#Override
public void onFailure(Throwable caught) {
caught.printStackTrace();
}
#Override
public void onSuccess(CustomObject result) {
// code omitted
}
};
service.callMethod(aString, callback);
And this is the server
try {
String xmlRequest = "xmlToSend";
URL url = new URL("https://www.externalWebService.com");
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("POST");
conn.setAllowUserInteraction(false);
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type","application/soap+xml");
conn.setRequestProperty( "Content-length", Integer.toString(xmlRequest.length()));
conn.setRequestProperty("charset", "utf-8");
conn.setConnectTimeout(10000);
OutputStream rawOutStream = conn.getOutputStream();
PrintWriter pw = new PrintWriter(rawOutStream);
pw.print(xmlRequest);
pw.flush();
pw.close();
if(conn.getResponseCode() != 200){
// Something...
}
I keep having the same error at conn.getResponseCode() :
java.lang.ClassCastException: com.google.appengine.repackaged.org.apache.http.message.BasicHttpRequest cannot be cast to com.google.appengine.repackaged.org.apache.http.client.methods.HttpUriRequest
Without making a real request, the remote service works well : it's able to serialize and return objects to the client. The issue is not linked to the communication between the client and the server, it's more like AppEngine doesn't support HttpURLConnection. But it should on the server (isn't it?)
Any thoughts would be hightly appreciated! Thanks in advance
Your problem has nothing to do with GWT: as long as you are running on the server, you can use any 'normal' Java and it will work unless AppEngine has restrictions.
It seems you have imported the repackaged version of Apache HttpClient in your class. You should not do that: download your own HttpClient .jar, add it to the dependencies and use that one.
AppEngine also has some issues with HttpClient. There's an adapter available here that fixes most of the issues.
Thanks #Marcelo, you were right!
Here is the solution I found.
I added httpcore.jar and httpclient.jar to my build path and wrote the code below for the server (the client is the same) :
String xmlRequest = "xmlToSend";
CloseableHttpClient httpclient = HttpClients.custom().build();
//RequestConfig requestConfig = RequestConfig.custom()
// .setConnectionRequestTimeout(10000)
// .build();
try {
ByteArrayOutputStream out = new ByteArrayOutputStream();
Writer writer = new OutputStreamWriter(out);
writer.write(xmlToSend);
writer.flush();
writer.close();
HttpPost request = new HttpPost("https://www.externalWebService.com/path");
request.setEntity(new ByteArrayEntity(out.toByteArray()));
//request.setConfig(requestConfig);
CloseableHttpResponse response = httpclient.execute(request);
if(response.getStatusLine().getStatusCode() == 200){
// retrieve content with a BufferReader
// from response.getEntity().getContent()
...
}
The code works and is up to date.
Edit
Here is the rest of the solution when using a proxy. Mine only deals with NTCredentials but otherwise UsernamePasswordCredentials can be used instead.
HttpHost proxy = new HttpHost("addresse.proxy.com", port);
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(
new AuthScope(proxy),
new NTCredentials(System.getProperty("user.name") + ":" + password));
RequestConfig requestConfig = RequestConfig.custom()
.setProxy(proxy)
.build();
CloseableHttpClient httpclient = HttpClients.custom()
.setDefaultCredentialsProvider(credsProvider)
.setDefaultRequestConfig(requestConfig)
.build();
Thanks again for your help, I really appreciated!

Exporting data to Google Spreadsheet from Google App Engine (Java version)

I am getting no where now. When I Google around to find a sample of "Exporting data to Google Spreadsheet from Google App Engine", I see a lot of Google Conversion API, Google Conversion API, Google Spreadsheet API and Google Docs API tutorials. But then they all deprecated from Google when I check at the Google site??? So, what is the most updated right now so I can make use of it?
=====
Okay now I use the Google Drive SDK via OAuth2 to create text file. But I have problem with this:
this is the error:
java.lang.NullPointerException at
java.net.URI$Parser.parse(URI.java:3004) at
java.net.URI.(URI.java:577) at
com.google.api.client.http.GenericUrl.(GenericUrl.java:100) at
com.google.api.client.googleapis.media.MediaHttpUploader.upload(MediaHttpUploader.java:269)
at
com.google.api.services.drive.Drive$Files$Insert.executeUnparsed(Drive.java:309)
at
com.google.api.services.drive.Drive$Files$Insert.execute(Drive.java:331)
at
com.company.dashboard.service.DriveService.initDoc(DriveService.java:84)
this is the code:
private GoogleCredential buildGoogleCredential(Credential credential) {
try {
logger.warning(oauth2Service.getClientCredential().toString());
GoogleCredential googleCredential = new GoogleCredential.Builder()
.setClientSecrets(oauth2Service.getClientCredential())
.setTransport(new NetHttpTransport())
.setJsonFactory(new JacksonFactory()).build();
googleCredential.setAccessToken(credential.getAccessToken());
googleCredential.setRefreshToken(credential.getRefreshToken());
return googleCredential;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private Drive buildService(GoogleCredential credential) {
return new Drive.Builder(new NetHttpTransport(), new JacksonFactory(), credential).build();
}
public void initDoc(HttpServletRequest req)
throws Exception {
User user = UserServiceFactory.getUserService().getCurrentUser();
Credential credential = oauth2Service.getStoredCredential(
user.getUserId(),
(CredentialStore)req.getSession().getServletContext().getAttribute(OAuth2Constant.GOOG_CREDENTIAL_STORE));
if (credential != null) {
logger.warning("Using access token: " + credential.getAccessToken());
try {
GoogleCredential googleCredential = buildGoogleCredential(credential);
Drive service = buildService(googleCredential);
if (service == null) {
logger.warning("very bad!");
}
File body = new File();
body.setTitle("My document");
body.setDescription("A test document");
body.setMimeType("text/plain");
java.io.File fileContent = new java.io.File("document.txt");
FileContent mediaContent = new FileContent("text/plain", fileContent);
service.files().insert(body, mediaContent).execute();
//File file = service.files().insert(body, mediaContent).execute();
//System.out.println("File ID: " + file.getId());
} catch (HttpResponseException e) {
if (e.getStatusCode() == 401) {
logger.warning(e.getMessage());
// Credentials have been revoked.
// TODO: Redirect the user to the authorization URL.
throw new UnsupportedOperationException();
}
} catch (IOException e) {
System.out.println("An error occurred: " + e);
}
}
oauth2Service.getClientCredential() returns (xxx = client id and client secret code, not shown in here)
{"web":{"client_id":"xxx.apps.googleusercontent.com","client_secret":"xxx"}}
This is my scope:
final static List<String> SCOPES = Arrays.asList("https://www.googleapis.com/auth/userinfo.profile",
"https://www.googleapis.com/auth/userinfo.email",
"https://www.googleapis.com/auth/drive",
"https://www.googleapis.com/auth/docs",
"https://www.googleapis.com/auth/drive.file");
final static String AUTH_RESOURCE_LOC = "/client_secrets.json";
final static String OATH_CALLBACK = "http://localhost:8888/oauth2callback";
This line
service.files().insert(body, mediaContent).execute();
throws NullPointerException. Any idea what had gone wrong???
P/S: Credential = com.google.api.client.auth.oauth2.Credential. I have my OAuth2 everything works good. I can retrieve user info without problem but not the Drive API. service is not null as you see I put it the log as "very bad" and it is not shown. No 401 exception is thrown means my Oauth2 is good with the scopes.
=======
DARN!!!! Finally solved the issue!!! My code was totally correct! Just I enabled the wrong API! It should be Drive API instead of Drive SDK API :/
You can generate a csv file from GAE and upload it using the Drive API with ?convert=true to have it automatically converted to a Google spreadsheet:
https://developers.google.com/drive/v2/reference/files/insert

Inheritance security rules violated while overriding member in Silverlight

I am working on a web application in silverlight. I have overloaded the WebClient.GetWebRequest method as given below:-
public class WebClientWithCookies : WebClient
{
[SecurityCritical]
protected override WebRequest GetWebRequest(Uri address)
{
string cookieContent = HtmlPage.Document.Cookies;
WebRequest request = base.GetWebRequest(address);
HttpWebRequest webRequest = request as HttpWebRequest;
if (webRequest != null && cookieContent != null && cookieContent != string.Empty)
{
CookieContainer cookieContainer = new CookieContainer();
cookieContainer.Add(address, new Cookie() { Value = HtmlPage.Document.Cookies });
webRequest.CookieContainer = cookieContainer;
}
return request;
}
}
But I am getting the following exception:
System.TypeInitializationException was unhandled by user code
Message=The type initializer for 'SigmaWC.Utility.RestCommunicator'
threw an exception. TypeName=SigmaWC.Utility.RestCommunicator
StackTrace:
at SigmaWC.Utility.RestCommunicator..ctor()
at SigmaWC.App..ctor() InnerException: System.TypeLoadException
Message=Inheritance security rules violated while overriding member: 'SigmaWC.Utility.WebClientWithCookies..ctor()'. Security
accessibility of the overriding method must match the security
accessibility of the method being overriden.
StackTrace:
at SigmaWC.Utility.RestCommunicator..cctor()
InnerException:
Can anyone help in how to elevate the security settings in silverlight.
Documentation about this is scarce to say the least. However, there are a couple of resources which are useful:
MSDN Indicates that you cannot use framework members with a SecurityCriticalAttribute.
Types and members that have the SecurityCriticalAttribute cannot be used by Silverlight application code. Security-critical types and members can be used only by trusted code in the .NET Framework for Silverlight class library.
In the case of WebClient, the GetWebRequest method does not have this attribute, however the constructor does.
This MSDN Security blog Implies that if the default constructor has any Security attribute, the class cannot be used for inheritance in a Silverlight client.
Further to that, the aforementioned MSDN blog implies that Security attributes are ignored in Silverlight assemblies which are not part of the core framework. This may however only apply to Assembly level attributes.
Anyway, to cut a long story short. You cannot derive from WebClient because of the SecuritySafeAttribute on the constructor.
To illustrate the point, this also causes an exception at runtime:
public class MyWebClient : WebClient
{
}
The alternative is to roll your own WebClient. It takes a little work, but the following example does work with the following handler:
public class MyHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
context.Response.Write("Hello World");
foreach (Cookie cookie in context.Response.Cookies)
{
//Cookies from the client - there will be 1 in this case
}
}
...
public class MyWebClient
{
public MyWebClient()
{
}
public void InvokeWebRequest(Uri address)
{
//Set the cookie you want to use.
string cookieContent = "I like cookies";
// Register a http client - without this the following webRequest.CookieContainer setter will throw an exception
WebRequest.RegisterPrefix("http://", WebRequestCreator.ClientHttp);
//This bit you know, but dont forget to set Name on your new Cookie.
HttpWebRequest webRequest = WebRequest.Create(address.AbsoluteUri) as HttpWebRequest;
if (webRequest != null && !String.IsNullOrWhiteSpace(cookieContent))
{
webRequest.CookieContainer = new CookieContainer();
webRequest.CookieContainer.Add(address, new Cookie() { Value = cookieContent, Name = "MyCookie" });
}
//Invoke the async GetResponse method.
webRequest.BeginGetResponse(o =>
{
HttpWebResponse response = (HttpWebResponse)webRequest.EndGetResponse(o);
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
//Read the result
string result = reader.ReadToEnd();
}
foreach (Cookie cookie in response.Cookies)
{
//The cookies returned from the server.
}
}, null);
}
}

Resources