How can i use Metamask to make transactions? - flutter

import 'package:http/http.dart'; //You can also import the browser version
import 'package:web3dart/web3dart.dart';
var apiUrl = "http://localhost:7545"; //Replace with your API
var httpClient = Client();
var ethClient = Web3Client(apiUrl, httpClient);
var credentials = ethClient.credentialsFromPrivateKey("0x...");
// You can now call rpc methods. This one will query the amount of Ether you own
EtherAmount balance = ethClient.getBalance(credentials.address);
print(balance.getValueInUnit(EtherUnit.ether));
This is the code from web3dart package in flutter. I want to replace the apiUrl with some kinds of url from the Metamask mobile app itself(connected via walletConnect package). Any help guys?

You can use this method for connect to rpc final credentials = EthPrivateKey.fromHex(privatekey); because the other is deprecated.
print("Accediendo al servidor blockchain...");
var rpcUrl = "HTTP://127.0.0.1:8545";
const String privatekey = "2812d889332dce9256c385355839102910ae8cc1c16c6e1212174d1dc91d9738";
final client = Web3Client(rpcUrl, Client());
final credentials = EthPrivateKey.fromHex(privatekey);
final address = credentials.address;
print(address.hexEip55);

Use this package for Flutter. LINK: https://pub.dev/packages/web3dart
var apiUrl = "http://localhost:7545"; //Replace with your API
var httpClient = new Client();
var ethClient = Web3Client(apiUrl, httpClient);
EthPrivateKey credentials = await ethClient.credentialsFromPrivateKey("0x...........");
EthereumAddress address=credentials.address;
print("ADDRESS FORM PRIVATE KEY : "+address.hex);

Related

How to get request and response from Web Api and save it to the database

I have a method in the Controller class below:
[HttpGet]
[ResponseType(typeof(RsContractCustomer))]
[Route("api/Contract/GetCustomerData/{cardModificationId}")]
public async Task<IHttpActionResult> GetCustomerData([FromUri] int cardModificationId)
{
var jsonIgnoreNullValues = JsonConvert.SerializeObject(await _bs.GetCustomer(cardModificationId), Newtonsoft.Json.Formatting.Indented, new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore
});
JObject jObject = JObject.Parse(jsonIgnoreNullValues);
return Ok(jObject); //await _bs.GetCustomerData(id));
}
Now I want to get HttpResponseMessage and save particular part into database. What I should to add in these code or implement middleware to get this?
HttpReponseMessage is received in the client side (Middleware and controllers are on the server side).
In the client project you can write something like that:
HttpClient client = new HttpClient();
HttpResponseMessage response = await client.GetAsync("http://localhost:8080/api/contract/getcustomerdata/1");
var customer = await response.Content.ReadAsAsync<RsContractCustomer>();
// Save to DB

flutter/dart connect to Azure via mqtts

I am trying to connect to our MQTT server on Azure.
I use MQTTBox as our testbed, and it is successfully connecting to
protocol: mqtts
host: .azure-devices.net/$iothub/websocket
user: .azure-devices.net/testdevice/?api-version=2018-06-30
password: 'SharedAccessSignature sr=.azure-devices.net%2Fdevices%2Ftestdevice&sig=xxxxxxx'
I tried the mqtt_client library, which was an issue with "$" sign in the server endpoint and throws ""SocketException: Failed host lookup: 'mqttQueue.azure-devices.net/$iothub/websocket' (OS Error: No address associated with hostname, errno = 7)"
final client = MqttServerClient('<hubname>.azure-devices.net/\$iothub/websocket', '');
client.port = 8883;
client.secure = true;
final connMess = MqttConnectMessage()
.authenticateAs('<hubname>.azure-devices.net/testdevice/?api-version=2018-06-30',
'SharedAccessSignature sr=<hubname>.azure-devices.net%2Fdevices%2Ftestdevice&sig=xxxxxxx')
.withClientIdentifier('testdevice')
.withWillTopic('devices/testdevice/messages/events/') // If you set this you must set a will message
.withWillMessage('My Will message')
.startClean() // Non persistent session for testing
.withWillQos(MqttQos.atLeastOnce);
client.connectionMessage = connMess;
try {
await client.connect();
}
I also tried unsuccessfully
final client = MqttServerClient('HostName=<hubname>.azure-devices.net;DeviceId=testDevice;SharedAccessKey=m....Y=','')
Any working example to Azure in dart/flutter is appreciated, as I fail to map the Azure given parameters to the parameters in the library.
final client = MqttServerClient('<hubname>.azure-devices.net', '');
client.useWebSocket = false;
client.port = 8883;
client.autoReconnect = true;
client.keepAlivePeriod = 3600;
final String user = '<hubname>.azure-devices.net/<your device id>';
late String password; // <== password string is obtained elsewhere
final connMess = MqttConnectMessage()
.withClientIdentifier(clientIdentifier)
.startClean();
client.connectionMessage = connMess;
client.connect(username, password);

Is there a way to register a data asset in Azure Data Catalog via api without user-login?

My app gets a token and can make api calls to the ADC like searching. But the request for registration of new asset fails, because the field "LastRegisterdBy" must not be null/empty and has to correspond to current user.
However the token does not contain any user information (AccessToken().Result.UserInfo.DisplayableId is null).
I mostly followed the get started get-started project MS provides (https://github.com/Azure-Samples/data-catalog-dotnet-get-started/blob/master/Program.cs)
But i use
AcquireTokenAsync(resourceUri, clientCredential).ConfigureAwait(false)
instead of
AcquireTokenAsync(resourceUri, clientId, new Uri(redirectUri), new PlatformParameters(PromptBehavior.Always)).
This so nobody has to enter his credentials. The goal is to run the code in ssis package, which will execute on a weekly basis to catch any updates in the data automatically.
This is the outline of my code:
class Program
{
static string clientIDFromAzureAppRegistration = "";
static string clientSecret = "";
static AuthenticationResult authResult = null;
static string catalogName = "catalog";
static void Main(string[] args)
{
var authResult = AccessToken();
string upn = authResult.Result.UserInfo.DisplayableId;
var id = RegisterDataAsset(authResult, SampleJson("test", upn));
}
static async Task<AuthenticationResult> AccessToken()
{
if (authResult == null)
{
//Resource Uri for Data Catalog API
string resourceUri = "https://api.azuredatacatalog.com";
//To learn how to register a client app and get a Client ID, see https://msdn.microsoft.com/en-us/library/azure/mt403303.aspx#clientID
string clientId = clientIDFromAzureAppRegistration;
string clientS = clientSecret;
// Create an instance of AuthenticationContext to acquire an Azure access token
var authority = "https://login.microsoftonline.com/52497ec2-0945-4f55-8021-79766363dd96";
var authContext = new AuthenticationContext(authority);
var clientCredential = new ClientCredential(clientId, clientS);
// Call AcquireToken to get an Azure token from Azure Active Directory token issuance endpoint
// AcquireToken takes a Client Id that Azure AD creates when you register your client app.
authResult = await authContext.AcquireTokenAsync(resourceUri, clientCredential).ConfigureAwait(false);
}
return authResult;
}
static string RegisterDataAsset(Task<AuthenticationResult> authResult, string json){
...
}
static HttpWebResponse SetRequestAndGetResponse(HttpWebRequest request, Task<AuthenticationResult> authResult, string payload = null){
...
}
static string SampleJson(string name, string upn){
...}
With upn = authResult.Result.UserInfo.DisplayableId; i get:
{"error":{"code":"InvalidPropertyValue","message":"Invalid input value for one of the properties. Path: 'properties.lastRegisteredBy.upn'. Details: Value cannot be null, empty or consists entirely of whitespaces."}}
Wit upn = "test#user":
{"error":{"code":"InvalidLastRegisteredBy","message":"LastRegisteredBy is different from the current user."}}
I found the solution, its quite simple:
The user-name of the app is: clientIDFromAzureAppRegistration + "#" + tenantId.

How to Access using Xamarin.Forms local Web API with Emulator for Visual Studio?

I've created .NET Framework API which contains authentication, I launch the Web API using Jetbrains Rider and I run my Xamarin.Forms application using Visual Studio and I can't access any data from my Web API nor post any.
The Webservice class:
private readonly HttpClient _client;
public AccountService()
{
_client = new HttpClient
{
MaxResponseContentBufferSize = 256000
};
}
public async Task RegisterAsync(string email, string password, string confirmPassword)
{
var url = "http://169.254.80.80:61348/api/Account/Register";
var model = new RegisterBindingModel()
{
Email = email,
Password = password,
ConfirmPassword = confirmPassword
};
var json = JsonConvert.SerializeObject(model);
HttpContent content = new StringContent(json);
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
var response = await _client.PostAsync(url, content);
}
The initiation of the registration
private async void Register()
{
try
{
using (UserDialogs.Instance.Loading())
{
await _accountServices.RegisterAsync
(Email, Password, ConfirmPassword);
}
UserDialogs.Instance.Alert("Register Successful");
await _navigation.PushAsync(new LoginPage());
}
catch
{
UserDialogs.Instance.Alert("Something wrong happened, Try again");
}
}
I've tried to access the localhost through Emulator using these IPs:
10.0.3.2
10.0.2.2
169.254.80.80
And I've tried my default gateways and my local IP address with and without ports, in regardless using postman i can work with my api flawlessly.
I don't get errors but the connection status code is not successful and I don't get any data and the newly registered account won't be posted to the api.
EDIT:
As for the answers I've changed my method to this:
public async Task<string> RegisterAsync(string email, string password, string confirmPassword)
{
var client = new HttpClient()
{
BaseAddress = new Uri("http://169.254.80.80:61348/")
};
var postData = new List<KeyValuePair<string, string>>();
var nvc = new List<KeyValuePair<string, string>>();
nvc.Add(new KeyValuePair<string, string>("email", email));
nvc.Add(new KeyValuePair<string, string>("password", password));
nvc.Add(new KeyValuePair<string, string>("confirmPassword", confirmPassword));
var req = new HttpRequestMessage(HttpMethod.Post, "api/Account/Register") { Content = new FormUrlEncodedContent(nvc) };
var res = await client.SendAsync(req);
if (res.IsSuccessStatusCode)
{
string result = await res.Content.ReadAsStringAsync();
string test = JsonConvert.DeserializeObject<string>(result);
return test;
}
return null;
}
and i call the web api using postman like this:
http://localhost:61348/api/Account/Register
I always prefer Newtonsoft Json.NET to carry out web request here is the code I have implemented in my case and it works great for me.
public static async Task<string> ResgisterUser(string email, string password, string confirmPassword)
{
var client = new HttpClient(new NativeMessageHandler());
client.BaseAddress = new Uri("http://192.168.101.119:8475/");
var postData = new List<KeyValuePair<string, string>>();
var nvc = new List<KeyValuePair<string, string>>();
nvc.Add(new KeyValuePair<string, string>("email", email));
nvc.Add(new KeyValuePair<string, string>("password", password));
nvc.Add(new KeyValuePair<string, string>("confirmPassword",confirmPassword));
var req = new HttpRequestMessage(HttpMethod.Post, "api/Vendor/Register") { Content = new FormUrlEncodedContent(nvc) };
var res = await client.SendAsync(req);
if (res.IsSuccessStatusCode)
{
string result = await res.Content.ReadAsStringAsync();
string test= JsonConvert.DeserializeObject<string>(result);
return test;
}
}
Hope it works for you.

Generating a JWT token using AuthenticateAsync

I am trying to login using ClaimsPrincipal and then fetch a JWT in .net core 2.0. With my current code, I get the error from the result of the SignInAsync function:
"No IAuthenticationSignInHandler is configured to handle sign in for the scheme: Bearer"
Here is the controller I am currently using:
[Route("Login/{username}")]
public async Task<IActionResult> Login(string username)
{
var userClaims = new List<Claim>
{
new Claim(ClaimTypes.Name, username)
};
var principal = new ClaimsPrincipal(new ClaimsIdentity(userClaims));
var sign = HttpContext.SignInAsync(principal);
await sign;
var res = await HttpContext.AuthenticateAsync();
var token = await HttpContext.GetTokenAsync("access_token");
return Json(token);
}
The login portion was tested and works well with cookies. However when I use the following code with JwtBearerDefaults.AuthenticationScheme in my startup.cs:
services.AddAuthentication(config => {
config.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
config.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(config =>
{
config.TokenValidationParameters = Token.tokenValidationParameters;
config.RequireHttpsMetadata = false;
config.SaveToken = true;
});
I get the error from the result of the SignInAsync function:
"No IAuthenticationSignInHandler is configured to handle sign in for the scheme: Bearer"
My Token class was created with the help of a code I found online (at JWT on .NET Core 2.0) and is defined as follows:
public static class Token
{
public static TokenValidationParameters tokenValidationParameters {
get
{
return new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = GetSignInKey(),
ValidateIssuer = true,
ValidIssuer = GetIssuer(),
ValidateAudience = true,
ValidAudience = GetAudience(),
ValidateLifetime = true,
ClockSkew = TimeSpan.Zero
};
}
}
static private SymmetricSecurityKey GetSignInKey()
{
const string secretKey = "very_long_very_secret_secret";
var signingKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secretKey));
return signingKey;
}
static private string GetIssuer()
{
return "issuer";
}
static private string GetAudience()
{
return "audience";
}
}
If I understand it correctly from looking at the source code for JwtBearerHandler, it does not implement IAuthenticationSignInHandler, which is why you are getting this error. Call to SignInAsync is designed to persist authentication information, such as created auth cookie which, for instance, is exactly what CookieAuthenticationHandler does. But for JWT there is no single well-known place to store the token, hence no reason to call SignInAsync at all. Instead of that, grab the token and pass it back to the browser. Assuming you are redirecting, you can tuck it into a query string. Assuming browser application is an SPA (i.e. Angular-based) and you need tokens for AJAX calls, you should store token in the SPA and send it with every API request. There are some good tutorials on how to use JWT with SPAs of different types, such as this: https://medium.com/beautiful-angular/angular-2-and-jwt-authentication-d30c21a2f24f
Keep in mind that JwtBearerHandler expects to find Authentication header with Bearer in it, so if your AJAX calls are placing token in query string, you will need to supply JwtBearerEvents.OnMessageReceived implementation that will take token from query string and put it in the header.
A signed token can be created using the JwtSecurityTokenHandler.
var handler = new JwtSecurityTokenHandler();
var jwt = handler.CreateJwtSecurityToken(new SecurityTokenDescriptor
{
Expires = DateTime.UtcNow.Add(Expiary),
Subject = new ClaimsIdentity(claims, "local"),
SigningCredentials = new SigningCredentials(SigningKey, SecurityAlgorithms.HmacSha256)
});
return handler.WriteToken(jwt);