Trying authenticate via Okta to access AWS resource using c#/.net. Found this sdk for .net https://github.com/okta/okta-auth-dotnet. Following the examples but do not know how to procced to list all AWS resources. Any help will be appreciated it. (credentials are not real and part of the example)
var client = new AuthenticationClient(new OktaClientConfiguration
{
OktaDomain = "https://{{yourOktaDomain}}",
});
var authnOptions = new AuthenticateOptions()
{
Username = $"darth.vader#imperial-senate.gov",
Password = "D1sturB1ng!",
};
var authnResponse = await authClient.AuthenticateAsync(authnOptions);
Step 1: Install the NuGet package. It will install all the dependencies too.
install package 'Okta.Auth.Sdk.2.0.3'
The code you posted should work with one change (name of the variable). Since you copied the code directly from the GitHub site.
using Okta.Auth.Sdk;
using Okta.Sdk.Abstractions.Configuration;
public static class Program
{
static void Main(string[] args)
{
var client = new AuthenticationClient(new OktaClientConfiguration
{
OktaDomain = "https://{{yourOktaDomain}}",
});
var authnOptions = new AuthenticateOptions()
{
Username = $"darth.vader#imperial-senate.gov",
Password = "D1sturB1ng!",
};
//Asynchronous programming with async and await
//var authnResponse = await client.AuthenticateAsync(authnOptions);
//Synchromous Programming - use Result - which would wait until the task had completed.
var authnResponse = client.AuthenticateAsync(authnOptions).Result;
}
}
I did verify the code. and the AuthenticationStatus was SUCCESS
Related
Because old Azure SDK for .NET is deprecated, I'm trying to migrate it to new version. I've been stucked with finding substitions for old methods and properties in new SDK. We do a snapshot of existing database and export to Storage Account.
Snippet of old approach:
var sp = new ServicePrincipalLoginInformation()
{
ClientId = clientId,
ClientSecret = clientSecret
};
var credentials = new AzureCredentials(sp, tenantId, AzureEnvironment.AzureGlobalCloud);
var azureClient = Authenticate(credentials).WithSubscription(subscriptionId);
var sqlServer = await azureClient.SqlServers.GetByIdAsync(db.SourceServerId);
var serverDbs = await sqlServer.Databases.ListAsync();
var snapshotDb = serverDbs.FirstOrDefault(i => i.Name == snapshotDbName);
if(snapshotDb is not null)
return;
snapshotDb = await azureClient.SqlServers.Databases
.Define(snapshotDbName)
.WithExistingSqlServer(sqlServer)
.WithSourceDatabase(sourceDatabaseId)
.WithMode(CreateMode.Copy)
.CreateAsync(cancellationToken);
.
.
.
var storageAccount = azureClient.StorageAccounts.GetByIdAsync(storageId);
await snapshotDb.ExportTo(storageAccount, storageContainer, outputFileName)
.WithSqlAdministratorLoginAndPassword(user, password)
.ExecuteAsync(cancellationToken);
According to documentation, I was able to get this:
var sp = new ClientSecretCredential(tenantId, clientId, clientSecret);
var azureClient = new ArmClient(sp, subscriptionId);
var ri = new ResourceIdentifier(NOT SURE WHAT SHOULD BE HERE);
var resGroup = azure.GetResourceGroupResource(ri);
var sqlServerResponse = await resGroup.GetSqlServers().GetAsync(sourceServerId);
var sqlServer = sqlServers.Value;
var serverDBs = sqlServer.GetSqlDatabases();
var snapshotDB = serverDBs.FirstOrDefault(x => x.Data.Name == db.SnapshotDbName);
What are substitution commands, which handle creating snapshot and exporting to Storage Account base on parameters used in deprecated sample? Or do I miss some Package?
We have a general guidance for using our latest version of .NET SDK against resource management.
Regarding your issue, you can refer to code below
var resourceGroup = _client.GetDefaultSubscription().GetResourceGroup(resourceGroupName).Value;
var sqlServer = resourceGroup.GetSqlServer("mySqlServerName").Value;
var sqlDB = sqlServer.GetSqlDatabase("myDbName").Value;
var exportResult= sqlDB.Export(Azure.WaitUntil.Completed, new Azure.ResourceManager.Sql.Models.DatabaseExportDefinition("storageKeyType", "storageKey", new Uri("storageUri"), "adminLogin", "adminLoginPWD")).Value;
The _client here is ArmClient object,
your code var ri = new ResourceIdentifier(NOT SURE WHAT SHOULD BE HERE); is not necessary, may I know why do you want to create a resource identifier here?
Please make sure you are using 1.1.0 version of Azure SDK for SQL libirary in .NET
We are open to any feedback regarding our new SDK, feel free to let us know your thoughts on our new SDK in this survey
Can someone help me successfully send ERC20 tokens using the Nethereum package in C# .NET?
I am able to successfully get account balances, but when I try to send, it just sits there....
I am using the Infura.io project api also with the below security:
eth_accounts
eth_call
eth_getBalance
eth_getTransactionReceipt
eth_sendRawTransaction
var client = new EthClient(new RpcUrl("https://mainnet.infura.io/v3/-MyProjectID-"));
Here is the code I am using:
--The call to the transfer method
/* transfer 100 tokens */
var transactionHashTask = client.transferTokens(coinOwnerAddress, coinOwnerPrivateKey, toAddress, contractAddress, 0);
var transactionHash = transactionHashTask.Result.ToString();
lblTransHash.Text = "Transaction hash: " + transactionHash;
--Code that contains the actual method
public async Task<string> transferTokens(string senderAddress, string privateKey, string receiverAddress, string contractAddress, UInt64 tokens)
{
var transactionMessage = new TransferFunction()
{
FromAddress = senderAddress,
To = receiverAddress,
AmountToSend = tokens
};
var transferHandler = web3.Eth.GetContractTransactionHandler<TransferFunction>();
Task<string> transactionHashTask = transferHandler.SendRequestAsync(contractAddress,transactionMessage);
return await transactionHashTask;
}
You are transferring something right? So maybe you have to send extra to account for the gas fees. But i'm no expert. Let me know if you solve this please.
The transfer function doesn't have AmountToSend parameter. It has TokenAmount. So change like below
var transactionMessage = new TransferFunction()
{
To = receiverAddress,
TokenAmount= tokens
};
Using the backend of my app, I am attempting to capture information from Microsoft Graph for a user that has been authenticated and then add that user to a database. The authentication appears to be working correctly, but the user is never added to the database. I am really stuck on this. I've studied the online documentation extensively, but have been unable to find a solution. If I could just tell if the user properties were getting populated, I could figure out what's going on, but I've been unable to do that since the code runs on the server. (I've attempted to remote debug, but have been unable to successfully set a breakpoint.) Can anyone tell me what I'm doing wrong in the code below?
class MicrosoftAccountInfo
{
public string id { get; set; }
public string displayName { get; set; }
public string mail { get; set; }
}
[MobileAppController]
public class MicrosoftAccountController : ApiController
{
MicrosoftAccountCredentials credentials;
string msRequestUrl;
MyAppContext context;
EntityDomainManager<User> domainManager;
// GET api/<controller>
public async Task<User> Get()
{
if (credentials == null)
{
credentials = await this.User.GetAppServiceIdentityAsync<MicrosoftAccountCredentials>(this.Request);
}
msRequestUrl = "https://graph.microsoft.com/v1.0/me/?$select=id,displayName,mail";
var client = new System.Net.Http.HttpClient();
var headerValue = "Bearer" + credentials.AccessToken;
client.DefaultRequestHeaders.Add("Authorization", headerValue);
var resp = await client.GetAsync(msRequestUrl);
resp.EnsureSuccessStatusCode();
var msInfo = await resp.Content.ReadAsStringAsync();
MicrosoftAccountInfo info = JsonConvert.DeserializeObject<MicrosoftAccountInfo>(msInfo);
context = new MyAppContext();
domainManager = new EntityDomainManager<User>(context, Request);
var user = context.Users.FirstOrDefault(u => u.Email == info.mail);
if (user == null)
{
user = new DataObjects.User { Email = info.mail, UserName = info.displayName, ProviderId = info.id };
await domainManager.InsertAsync(user);
}
else if (string.IsNullOrEmpty(user.ProviderId))
{
user.UserName = info.displayName;
user.ProviderId = info.id;
await context.SaveChangesAsync();
}
return user;
}
}
As to why this is failing, it is difficult to determine without an actual error message. There are simply to many variables/potential failure points involved to say for sure.
That said, you can reduce the number of potential failure points by using the Microsoft Graph .NET Client Library. There is also a NuGet package available: Install-Package Microsoft.Graph.
This library will handle composing the Microsoft Graph and deserializing the response into an object. Along with removing a risk factor, it will greatly simplify your code:
Microsoft.Graph.GraphServiceClient graphClient =
new Microsoft.Graph.GraphServiceClient(new DelegateAuthenticationProvider((requestMessage) =>
{
requestMessage.Headers.Authorization =
new System.Net.Http.Headers.AuthenticationHeaderValue("bearer", "{your-access-token}");
return Task.FromResult(0);
}));
Microsoft.Graph.User user = await graphClient.Me.Request().GetAsync();
I would also suggest implementing a monitoring solution that can trap exceptions on the server. This will help with debugging. If you're running on Azure, I strongly recommend using Application Insights. Aside from being free to get started, it is effectively a "click once, get monitoring" solution. It will handle wiring up the server and provide reporting for any exceptions it runs into.
Note that you can also use App Insights with your own servers or apps hosted on other services (i.e. AWS, RackSpace), there may however be some manual configuration required.
I am trying to create a Windows app (.Net, C#) that will get a list of files in the Box.com folder passed in. Apparently one of the steps in configuring a new Box app using JWT authorization is to create an App User with the SDK (Box.V2). I took the following code from some examples in the SDK documentation. The CreateEnterpriseUserAsync() call is failing with the error message:
BoxException: Bearer realm="Service", error="insufficient_scope", error_description="The request requires higher privileges than provided by the access token."
I'm the account admin, so I should have all rights. However, I'm using a developer account with just one seat. . . not sure if that's the limitation. I'd be grateful for any help!
The error is happening about 3/4 of the way down the sample, where indicated.
namespace Trial5
{
class Program
{
static void Main(string[] args)
{
var t = Configure();
t.Wait();
}
private static async Task Configure()
{
// Open a stream to read the Box configuration file.
using (System.IO.FileStream fs = new FileStream($"./BoxConfig.json", FileMode.Open))
{
//configure -----------------------------------------------------------------
var boxConfig = BoxConfig.CreateFromJsonFile(fs);
var boxJWT = new BoxJWTAuth(boxConfig);
//authenticate -----------------------------------------------------------------
var adminToken = boxJWT.AdminToken(); //valid for 60 minutes so should be cached and re-used
var adminClient = boxJWT.AdminClient(adminToken);
// Use the GetCurrentUserInformationAsync method to retrieve current user's information.
// Since this client uses the Service Account, this will return the Service Account's information.
var adminClientInfo = await adminClient.UsersManager.GetCurrentUserInformationAsync();
//See the login
Console.WriteLine(adminClientInfo.Login);
//create app user -----------------------------------------------------------------
//NOTE: you must set IsPlatformAccessOnly=true for an App User
var userRequest = new BoxUserRequest() { Name = "test appuser1", IsPlatformAccessOnly = true };
var appUser = await adminClient.UsersManager.CreateEnterpriseUserAsync(userRequest); // <---------------ERROR HERE
//get a user client -----------------------------------------------------------------
var userToken = boxJWT.UserToken(appUser.Id); //valid for 60 minutes so should be cached and re-used
var userClient = boxJWT.UserClient(userToken, appUser.Id);
//for example, look up the app user's details
var userClientInfo = await userClient.UsersManager.GetCurrentUserInformationAsync();
//Get folder info
var items = await userClient.FoldersManager.GetFolderItemsAsync("0", 500);
}
}
}
}
If you check "Manager Users" scope on the app console and then reauthorize your app in the enterprise admin console under "Apps", it should work.
I've got what seems to be a pretty simple problem - I'm trying to use the facebooksdk.net to publish to a users feed.
First, I install with the following command, which gets me Facebook.Client version 0.9.91-alpha:
Install-Package Facebook.Client -pre
Next, I have a LoginButton (and I'm able to successfully login)
<fbc:LoginButton x:Name="_loginButton"
SessionStateChanged="_loginButton_SessionStateChanged" Margin="0,15" />
Now, I want to post to the feed, so I use the following code, copied directly from the facebooksdk.net site for publishing:
private async void PublishStory()
{
await _loginButton.RequestNewPermissions("publish_stream");
var facebookClient = new Facebook.FacebookClient(_loginButton.CurrentSession.AccessToken);
var postParams = new
{
name = this.PostTitle,
message = _txtStatus.Text.Trim(),
description = this.PostDescription.Replace(#"""", "'"),
link = this.PostUrl,
picture = this.PostImageUrl,
actions = new {
name = this.PostAppName,
link = this.PostAppUrl,
},
};
try
{
dynamic fbPostTaskResult = await facebookClient.PostTaskAsync("/me/feed", postParams);
var result = (IDictionary<string, object>)fbPostTaskResult;
var successMessageDialog = new Windows.UI.Popups.MessageDialog("Posted Open Graph Action, id: " + (string)result["id"]);
await successMessageDialog.ShowAsync();
}
catch (Exception ex)
{
ShowLoginUI();
}
}
The problem I'm running into is that _loginButton.CurrentSession cannot be resolved. Was it removed from this version of Facebook.Client, and if so, what's the right way to do this now?
After some trial and error, I believe I've found the answer. The AccessToken is now accessible via Session.ActiveSession.CurrentAccessTokenData.AccessToken, which means the line of code should be:
var token = Session.ActiveSession.CurrentAccessTokenData.AccessToken;
var fbClient = new Facebook.FacebookClient(token);