Authenticate Firestore without Firebase JSON File? - firebase

I am building an application that connects to a Database from Firestore, and when looking into the documentation the way they recommend for authentication into firestor is using the Firebase JSON file, for example this my adapter's constructor code:
public UserDataAdapter()
{
Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS","//file_path");
_firestoreDb = FirestoreDb.Create("databaseName") ?? throw new ArgumentNullException(nameof(FirestoreDb));
}
This is the source I am using: https://cloud.google.com/dotnet/docs/reference/Google.Cloud.Firestore/latest.
So is there a way that I could authenticate Firestore without using the JSON file?
In the past I used the library for Firebase Authentication called FirebaseAuthentication.net and it uses something like this:
var auth = new FirebaseAuthProvider(new FirebaseConfig(_firebaseSettings.ApiKey));
In where the ApiKey is the firebase secret, I am trying to do something like that

You can do something like this.
var GoogleSecretJson = builder.Configuration["GoogleSecretJson"];
var credential = GoogleCredential.FromJson(GoogleSecretJson).CreateScoped();
var firestoreClientBuilder = new FirestoreClientBuilder
{
ChannelCredentials = credential.ToChannelCredentials()
};
var client = firestoreClientBuilder.Build();
var db = FirestoreDb.Create("firestore-db", client: client);
You can set the GoogleSecretJson value from JSON file content.

Related

Retrieve logged user info from microsoft graph in a framework .net environment

I need to implement SSO in a .net framework web application environment. Need to authenticate and retrieve the samaccountname of the logged user.
I have a working code, but only works on a Desktop and mobile device environments, I guess because I’m using "PublicClientApplicationBuilder".
Sample working code for desktop:
string clientId = "c8a73432-9383-4e7c.....";
string tenantId = "efe4a126-2f4f-42ef.....";
var app = PublicClientApplicationBuilder.Create(clientId)
.WithTenantId(tenantId)
.WithRedirectUri(http://localhost)
.Build();
string[] scopes = new string[]
{
https://graph.microsoft.com/User.Read
};
var result = await app.AcquireTokenInteractive(scopes)
.ExecuteAsync();
var stream = result.IdToken.ToString(); // return IDtoken with samaccountname
Does anybody have a sample code working for a web app?
I have tried with "ConfidentialClientApplicationBuilder", but doesn’t work:
string clientId = "c8a73432-9383...";
string tenantId = "efe4a126-2f4f...";
string secret = "1qN8Q~4m7qD5_...";
string authorityUri = $https://login.microsoftonline.com/efe4e126-2f4f-42ef...;
var app = ConfidentialClientApplicationBuilder.Create(clientId)
.WithClientSecret(secret)
.WithAuthority(new Uri(authorityUri))
.WithRedirectUri(http://localhost)
.Build();
string[] scopes = new string[]
{
https://graph.microsoft.com/User.Read
};
var accessTokenRequest = app.AcquireTokenForClient(scopes);
var accessToken = accessTokenRequest.ExecuteAsync().Result.AccessToken;
Thx in advance!
List item
In a confidential client application, you usually have a cache per user. Therefore you will need to get the cache associated with the user and inform the application builder that you want to use it. In the same way, you might have a dynamically computed redirect URI.
could you please add below code ,
TokenCache userTokenCache = _tokenCacheProvider.SerializeCache(app.UserTokenCache,httpContext, claimsPrincipal);
please refer doc- Retrieve logged user info from microsoft graph in a framework .net environment .
if still it doesn't work, as you said it doesn't work , we would like to know what error you got?

How to Read and Write Data from Firebase Database?

I have many problems to read data from a simple Firebase DB and to store it.
It's the first time that I use it so any help will be appreciated.
The solution is Xamarin.Forms and this is the Android part, my main problem.
This is my DB Structure:
I need to read and write the "number" value stored.
I add all Firebase package like Firebase.Database and Firebase.Connection
In my Android Prj I have a class with these:
MainActivity.cs
private void InitFirebaseAuth()
{
var options = new FirebaseOptions.Builder()
.SetApplicationId("******")
.SetApiKey("*******")
.SetDatabaseUrl("******")
.Build();
if (app == null)
app = FirebaseApp.InitializeApp(this, options, "SaloneB");
}
FirebaseHelper.cs
DatabaseReference databaseReference;
FirebaseDatabase database
public void Connect()
{
database = FirebaseDatabase.GetInstance(MainActivity.app);
}
First I call Connect then I try something like this without result:
FirebaseClient firebase = new FirebaseClient("*****");
//This to retrieve value
var items = await firebase
.Child("number_of_user") //name of the table
.OnceAsync(); //retrieve the value
Items result is 0 elements
Thanks for help

IdentityServer Hybrid Flow - Access Token is null after user successful login

I'm having problems in retrieving access token of an authenticated user. below is my configuration
ASP.NET MVC 5 Client:
OpenIdConnect
IdentityServer3 libraries
ResponseType = "code id_token"
ASP.NET Core Identity Server:
IdentityServer4 libraries
Client Config: AllowedGrantTypes =
GrantTypes.HybridAndClientCredentials,
I'm trying to get the access token in my client using this:
AuthorizationCodeReceived = async n =>
{
// use the code to get the access and refresh token
var tokenClient = new TokenClient(TokenEndpoint, "clientid", "secret");
var response = await tokenClient.RequestAuthorizationCodeAsync(n.Code, n.RedirectUri);
},
I used this reference for above implementation - https://github.com/IdentityServer/IdentityServer3/issues/2457
but the properties in the response has null values. I need the access token so that the user logged in the client can access the api. Below is another way that i'm trying to retrieve the access token:
public async Task<ActionResult> CallApiUsingUserAccessToken()
{
var user = User as ClaimsPrincipal;
var accessToken = user.FindFirst("access_token").Value;
var client = new HttpClient();
client.SetBearerToken(accessToken);
var content = await client.GetStringAsync("http://localhost:6001/api/values");
ViewBag.Json = JArray.Parse(content).ToString();
return View("json");
}
however, user.FindFirst("access_token").Value; is null. I'm thinking of migrating my MVC client to Core because I've tried the IdentityServer4 version in an asp.net core but that seems to be a big migration to my part. Thank you.
[updated]
It never occured to me that the endpoints in the IdentityServer3 differs from IDS4. I did have to change var tokenClient = new TokenClient(TokenEndpoint, "client", "secret"); to var tokenClient = new TokenClient("http://localhost:9000/connect/token", "client", "secret") since TokenEndpoint in IDS3 is http://localhost:9000/core/connect/token which the endpoint "core" does not exist in IDS4. I'm able to get the access token in this line var tokenResponse = await tokenClient.RequestAuthorizationCodeAsync(n.Code, n.RedirectUri); but after authorization, i'm still getting nullreference exception to this var accessToken = user.FindFirst("access_token").Value; line of code.
Given the IdentityServer 4 documentation on
Switching to Hybrid Flow and adding API Access back
and an example client from IdentityServer3.Samples
MVC OWIN Client (Hybrid)
you should be able to setup a working environment.
To support debugging you should always do proper response handling as shown in example below and copied from example client. Add any response errors to your question.
Notifications = new OpenIdConnectAuthenticationNotifications
{
AuthorizationCodeReceived = async n =>
{
// use the code to get the access and refresh token
var tokenClient = new TokenClient(
Constants.TokenEndpoint,
"mvc.owin.hybrid",
"secret");
var tokenResponse = await tokenClient.RequestAuthorizationCodeAsync(
n.Code, n.RedirectUri);
if (tokenResponse.IsError)
{
throw new Exception(tokenResponse.Error);
}
Finally I recommend to add code for all important parts of an IdentityServer3/4 based setup - because the truth is usually burried in the details.
According to these posts, https://github.com/IdentityServer/IdentityServer3/issues/2457 & https://github.com/IdentityServer/IdentityServer3/issues/2015#issuecomment-172623173, it is a good practice to not include the access token in the claims. Hence, I followed his example, https://github.com/Mich-b/IdentityServerTMLClient/blob/master/IdentityServerTMLClient/Startup.cs, in which the access token is added in the Http Session storage.

How to properly sync Xamarin iOS Sqlite using Azure Mobile Services

In my Xamarin iOS PCL app I'm trying to insert a record into my local Sqlite table, have it synced via Azure Mobile Services, and then read it back.
Here is the code:
private IMobileServiceSyncTable<Job> jobTable;
public async Task InitializeAsync()
{
var store = new MobileServiceSQLiteStore("localdata.db");
store.DefineTable<Job> ();
await this.MobileService.SyncContext.InitializeAsync(store);
jobTable = this.MobileService.GetSyncTable<Job>();
jobTable = this.MobileService.GetSyncTable<Job>();
JObject newJob = new JObject ();
newJob.Add ("Id","job_123");
jobTable.InsertAsync (newJob);
this.MobileService.SyncContext.PushAsync();
var readResult = jobTable.ReadAsync ().Result.AsQueryable();
var resultList = from data in readResult
select data;
var resultCount = resultList.Count ();
}
So far - nothing gets synced up with my Sql Server db (which is on the recieving end of the Mobile Services), and the resultCount remain at 0
I'm sure I do something wrong here, just can't seem to nail what exactly.
-Eugene
You should use PullAsync instead of ReadAsync. Also, you need to await the call to all of your async method calls, such as InsertAsync, PushAsync, and PullAsync.
See this tutorial for a detailed example: http://azure.microsoft.com/en-us/documentation/articles/mobile-services-xamarin-ios-get-started-offline-data/

How can i verify if my google web store application is licensed using asp.net?

I'm using DotNetOpenAuth.dll in order to obtain userid, but i don't know how to send the signed OAuth request google needs:
http://code.google.com/intl/it-IT/chrome/webstore/docs/check_for_payment.html
the example shows only java code
thanks for any help
Go to http://www.dotnetopenauth.net/ and read the documentations, you should find everything you need there.
EDIT:
I'm not sure if this is the right way or not but here is some sample code in c#
var serviceProvider = new ServiceProviderDescription();
var tokenManager = new TokenManager(); //make an implementation of IConsumerTokenManager
var oauth = new WebConsumer(serviceProvider, tokenManager); //instanciate an consumer
var user = new User(); //User class contains an implementation of getFederatedIdentity()
var url = new Uri(string.Format(SERVER_URL,APP_ID,HttpUtility.HtmlEncode(user.getFederatedIdentity())));//create the url
var response = oauth.PrepareAuthorizedRequestAndSend(
new MessageReceivingEndpoint(url, HttpDeliveryMethods.AuthorizationHeaderRequest), TOKEN); //Send the request
//do what you want with the response

Resources