C#: Download Release Asset from Github - c#

I want to download release asset zipball´s in a C# application for further use.
I´m using Octokit to get all release informations from the repo, including the respective browserdownload_url.
After some research it seemed to me, that you cant download this release asset zip´s via octokit, so trying with httpclient as suggested by some SO posts, that were asking these questions.
The release zip´s are on a Github Enterprise Repository, so they require Authentication.
And that is probably my issue, i cant make the authentication work with the httpClient...
The request always responds with Code 404
(which is the regular behaviour if you try by putting the url into the regular browser without logging in)
My actual implementation looks like this
public void DownloadRelease(string dlUrl, string targetPath)
{
var githubToken = "aaaaaaaaaaabbbbbbbbbcccccccccdddddddddd"; //Token created in the github developer settings with all available rights
//dlUrl = https://github.server.de/organization/project/releases/download/v1.2.34/release.zip
using (var client = new System.Net.Http.HttpClient())
{
var credentials = string.Format(System.Globalization.CultureInfo.InvariantCulture, "{0}:", githubToken);
credentials = Convert.ToBase64String(System.Text.Encoding.ASCII.GetBytes(credentials));
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", credentials);
//client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", githubToken);
var contents = client.GetByteArrayAsync(dlUrl).Result;
System.IO.File.WriteAllBytes(targetPath, contents);
}
}
Update:
At the End we followed the way of using the curl way:
https://docs.github.com/en/enterprise-server#3.0/rest/reference/repos#download-a-repository-archive-zip
And one more mistake on my end: There were releases without downloadable Asset IDs which i didnt catch in the code.

Based on the documentation (https://docs.github.com/en/enterprise-server#2.22/rest/overview/other-authentication-methods#via-oauth-and-personal-access-tokens) my best guess is, that your crendentials are wrong.
The docs say, the format should be username:token, yet you are only using token followed by a colon : - that doesn't look right to me, either.
So essentially you need to refactor your credentials variable a bit:
var credentials = $"{username}:{githubToken}";

Related

Convert a Kerberos based WindowsIdentity into a Base64 string

If I have the following code:
var token = System.Security.Principal.WindowsIdentity.GetCurrent();
I get a WindowsIdentity that is Kerberos based. I need to make a call with a header like this:
Authorize: Negotiate <Kerberos Token Here>
Is there a way to convert that token object into a Base64 string?
As the maintainer of the Kerberos.NET as mentioned in the other answer, you can always go that route. However, if you want SSO using the currently signed in Windows identity you have to go through Windows' SSPI stack.
Many .NET clients already support this natively using Windows Integrated auth, its just a matter of finding the correct knobs. It's unclear what client you're using so I can't offer any suggestions beyond that.
However if this is a custom client you have to call into SSPI directly. There's a handful of really good answers for explaining how to do that such as: Client-server authentication - using SSPI?.
The aforementioned Kerberos.NET library does have a small wrapper around SSPI: https://github.com/dotnet/Kerberos.NET/blob/develop/Kerberos.NET/Win32/SspiContext.cs
It's pretty trivial:
using (var context = new SspiContext($"host/yourremoteserver.com", "Negotiate"))
{
var tokenBytes = context.RequestToken();
var header = "Negotiate " + Convert.ToBase64String(tokenBytes);
...
}
I could not get this to work, but I was able to get a token using the excellent Kerberos.NET NuGet package. With that I was able to get it like this:
var client = new KerberosClient();
var kerbCred = new KerberosPasswordCredential("UserName", "p#ssword", "domain");
await client.Authenticate(kerbCred);
Console.WriteLine(client.UserPrincipalName);
var ticket = await client.GetServiceTicket("http/ServerThatWantsTheKerberosTicket.domain.net");
return Convert.ToBase64String(ticket.EncodeGssApi().ToArray());
As an aside, I needed help figuring out what the SPN value was for the GetServiceTicket and the project maintainer was fantastically helpful (and fast!).

Use google credentials to login into UWP C# app

I'm trying to make a login for a UWP app that I'm developing for a client that has a #<theircompay>.com email that uses G Suite. It doesn't have to access any user data, they just want it as an authentication so that only people that have a company email can access the app.
It would be great if they could login from within the app without having to use a web browser, and even better if it could remember them so they wouldn't have to login every single time.
I've been looking at OAuth 2.0 and several other solutions google has but can't really understand which one to use and much less how.
I looked into this answer but it doesn't seem like a good idea to ship your certificate file with your app.
So basically if this can be done, what (if any) certificates or credentials do I need to get from Google, and how would I handle them and the login through my C# code?
Edit
The app is 100% client side, no server backend
Taking a look at Google's GitHub it seems that .Net API is still not ready for UWP (however if you traverse the issues you will find that they are working on it, so it's probably a matter of time when official version is ready and this answer would be obsolete).
As I think getting simple accessToken (optionaly refresing it) to basic profile info should be sufficient for this case. Basing on available samples from Google I've build a small project (source at GitHub), that can help you.
So first of all you have to define your app at Google's developer console and obtain ClientID and ClientSecret. Once you have this you can get to coding. To obtain accessToken I will use a WebAuthenticationBroker:
string authString = "https://accounts.google.com/o/oauth2/auth?client_id=" + ClientID;
authString += "&scope=profile";
authString += $"&redirect_uri={RedirectURI}";
authString += $"&state={state}";
authString += $"&code_challenge={code_challenge}";
authString += $"&code_challenge_method={code_challenge_method}";
authString += "&response_type=code";
var receivedData = await WebAuthenticationBroker.AuthenticateAsync(WebAuthenticationOptions.UseTitle, new Uri(authString), new Uri(ApprovalEndpoint));
switch (receivedData.ResponseStatus)
{
case WebAuthenticationStatus.Success:
await GetAccessToken(receivedData.ResponseData.Substring(receivedData.ResponseData.IndexOf(' ') + 1), state, code_verifier);
return true;
case WebAuthenticationStatus.ErrorHttp:
Debug.WriteLine($"HTTP error: {receivedData.ResponseErrorDetail}");
return false;
case WebAuthenticationStatus.UserCancel:
default:
return false;
}
If everything goes all right and user puts correct credentials, you will have to ask Google for tokens (I assume that you only want the user to put credentials once). For this purpose you have the method GetAccessToken:
// Parses URI params into a dictionary - ref: http://stackoverflow.com/a/11957114/72176
Dictionary<string, string> queryStringParams = data.Split('&').ToDictionary(c => c.Split('=')[0], c => Uri.UnescapeDataString(c.Split('=')[1]));
StringContent content = new StringContent($"code={queryStringParams["code"]}&client_secret={ClientSecret}&redirect_uri={Uri.EscapeDataString(RedirectURI)}&client_id={ClientID}&code_verifier={codeVerifier}&grant_type=authorization_code",
Encoding.UTF8, "application/x-www-form-urlencoded");
HttpResponseMessage response = await httpClient.PostAsync(TokenEndpoint, content);
string responseString = await response.Content.ReadAsStringAsync();
if (!response.IsSuccessStatusCode)
{
Debug.WriteLine("Authorization code exchange failed.");
return;
}
JsonObject tokens = JsonObject.Parse(responseString);
accessToken = tokens.GetNamedString("access_token");
foreach (var item in vault.RetrieveAll().Where((x) => x.Resource == TokenTypes.AccessToken.ToString() || x.Resource == TokenTypes.RefreshToken.ToString())) vault.Remove(item);
vault.Add(new PasswordCredential(TokenTypes.AccessToken.ToString(), "MyApp", accessToken));
vault.Add(new PasswordCredential(TokenTypes.RefreshToken.ToString(), "MyApp", tokens.GetNamedString("refresh_token")));
TokenLastAccess = DateTimeOffset.UtcNow;
Once you have the tokens (I'm saving them in PasswordVault for safety), you can later then use them to authenticate without asking the user for his credentials. Note that accessToken has limited lifetime, therefore you use refreshToken to obtain a new one:
if (DateTimeOffset.UtcNow < TokenLastAccess.AddSeconds(3600))
{
// is authorized - no need to Sign In
return true;
}
else
{
string token = GetTokenFromVault(TokenTypes.RefreshToken);
if (!string.IsNullOrWhiteSpace(token))
{
StringContent content = new StringContent($"client_secret={ClientSecret}&refresh_token={token}&client_id={ClientID}&grant_type=refresh_token",
Encoding.UTF8, "application/x-www-form-urlencoded");
HttpResponseMessage response = await httpClient.PostAsync(TokenEndpoint, content);
string responseString = await response.Content.ReadAsStringAsync();
if (response.IsSuccessStatusCode)
{
JsonObject tokens = JsonObject.Parse(responseString);
accessToken = tokens.GetNamedString("access_token");
foreach (var item in vault.RetrieveAll().Where((x) => x.Resource == TokenTypes.AccessToken.ToString())) vault.Remove(item);
vault.Add(new PasswordCredential(TokenTypes.AccessToken.ToString(), "MyApp", accessToken));
TokenLastAccess = DateTimeOffset.UtcNow;
return true;
}
}
}
The code above is only a sample (with some shortcuts) and as mentioned above - a working version with some more error handling you will find at my GitHub. Please also note, that I haven't spend much time on this and it will surely need some more work to handle all the cases and possible problems. Though hopefully will help you to start.
Answer from Roamsz is great but didnt work for me because I found some conflicts or at least with the latest build 17134 as target, it doesn't work. Here are the problem, in his Github sample, he is using returnurl as urn:ietf:wg:oauth:2.0:oob . this is the type of url, you can't use with web application type when you create new "Create OAuth client ID" in the google or firebase console. you must use "Ios" as shown below. because web application requires http or https urls as return url.
from google doc
According to his sample he is using Client secret to obtain access token, this is not possible if you create Ios as type. because Android and Ios arent using client secret. It is perfectly described over here
client_secret The client secret obtained from the API Console. This
value is not needed for clients registered as Android, iOS, or Chrome
applications.
So you must use type as Ios, No Client Secret needed and return url is urn:ietf:wg:oauth:2.0:oob or urn:ietf:wg:oauth:2.0:oob:auto difference is that auto closes browser and returns back to the app. other one, code needs to be copied manually. I prefer to use urn:ietf:wg:oauth:2.0:oob:auto
Regarding code: please follow his github code. Just remove the Client Secret from the Access Token Request.
EDIT: it looks like I was right that even offical sample is not working after UWP version 15063, somebody created an issue on their github
https://github.com/Microsoft/Windows-universal-samples/issues/642
I'm using pretty straightforward code with Google.Apis.Oauth2.v2 Nuget package. Note, that I'm using v.1.25.0.859 of that package. I tried to update to the lastest version (1.37.0.1404), but this surprisingly doesn't work with UWP. At the same time v. 1.25.0.859 works just fine.
So, unless there's a better option, I would recommend to use a bit old, but working version of Nuget package.
This is my code:
credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
new Uri("ms-appx:///Assets/User/Auth/google_client_secrets.json"),
new[] { "profile", "email" },
"me",
CancellationToken.None);
await GoogleWebAuthorizationBroker.ReauthorizeAsync(credential, CancellationToken.None);
Then you can retrieve access token from: credential.Token.AccessToken.

How to remove a users manager in AzureAD using Microsoft.Azure.ActiveDirectory.GraphClient

I'm using the Microsoft.Azure.ActiveDirectory.GraphClient (Version 2.1.0) to write an app for Azure AD user management. I'm able to set the Manager of a user but have no idea how to clear the field.
Unfortunately the sample project provided on GitHub do not contain this function either.
I managed to clear the "manager" field using the code below. It is not using the Microsoft.Azure.ActiveDirectory.GraphClient library but gets the job done.
var token = <get your adal token here>
var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", token);
var url = "https://graph.windows.net/<tenant domain>/users/<userid>/$links/manager?api-version=1.6"
var resp = httpClient.DeleteAsync(url).Result;
if (!resp.IsSuccessStatusCode)
{
// log / throw exception etc.
}
You need to perform a DELETE HTTP request to https://graph.microsoft.com/v1.0/users/<user_email>/manager/$ref (make sure to replace the <user_email> in the URL.
A successful call will receive 204 response code and empty string as the response body.
This method is currently missing from the Microsoft Graph API docs but should be added in the future. (see here)
Also you should start using Microsoft Graph (graph.microsoft.com) instead of Azure AD Graph (graph.windows.net) as the latter is becoming obsolete. (See here)
//Assign and remove user's manager
// User.Manager = newUser as DirectoryObject;
User.Manager = null;

Why the same Access Token works for Media but doesn't work for Feed?

I'm using InstaSharp to get all medias from my account. This code works without any error:
var user = new InstaSharp.Endpoints.Media.Authenticated(config, authInfo);
var media = user.Popular();
Now if I do the same with Users:
var user = new InstaSharp.Endpoints.Users.Authenticated(config, authInfo);
var feed = user.Feed("self");
This returns:
OAuthParameterException: The access_token provided is invalid.
Why the same access token works in one place but doesn't work in another?
Note: I'm passing all scopes (basic, comments, likes, relationships) while getting the access token.I have also tried with default (basic) and it didn't work either.
Note2: Since I'm trying this in a ConsoleApplication, the way I'm getting the access token is, generate the link, copy/paste to the browser, confirm the authorization and get it from url. I'm not sure it makes any difference but it's worth noting...
I figure out the problem. It seems that the generated link was requesting code, not access_token.So that's why it was invalid.
And I realized that I was using older version of InstaSharp even though I downloaded it from it's website. First, I installed the latest version via NuGet. Then, I get the access token and the media like this:
var config = new InstagramConfig(clientId, clientSecret);
var AuthLink = OAuth.AuthLink(config.OAuthUri + "/authorize",
config.ClientId,
config.RedirectUri,
scopes,
OAuth.ResponseType.Code);
var authInfo = new OAuth(config);
// get the code from the link then pass it to RequestToken
var response = await authInfo.RequestToken(code);
var user = new Users(config, response);
var media = await user.RecentSelf(count: 30);
And all worked very well.

Simple C# Evernote API OAuth example or guide?

Anybody know where I can find a simple example C# code example? Apparently really tough to find.
I'm just starting out, got my Developer key.
Initial (really noob question/presumption) - -Can (should/must) my solution be a web service client? No new libraries I need to install in .Net right?
Basically, as a test, I want to be able to securely present a single note from a private notebook in html similar to what the Everfort export in html looks like on a outside WebSite.
Many Thanks in Advance!
You should start by downloading our API ZIP from http://www.evernote.com/about/developer/api/. You'll find C# client sample code in /sample/csharp. This sample code demonstrates using the Evernote API from a desktop application that authenticates using username and password.
I am not sure if you ever got this working, but I was playing around with Evernote, OpenAuth and C# this morning and managed to get it all working. I have put together a blog post / library explaining the experience and outlining how to do it with MVC here - http://www.shaunmccarthy.com/evernote-oauth-csharp/ - it uses the AsyncOAuth library: https://github.com/neuecc/AsyncOAuth
I wrote a wrapper around AsyncOAuth that you might find useful here: https://github.com/shaunmccarthy/AsyncOAuth.Evernote.Simple
One prickly thing to be aware of - the Evernote Endpoints (/oauth and /OAuth.action) are case sensitive
// Download the library from https://github.com/shaunmccarthy/AsyncOAuth.Evernote.Simple
// Configure the Authorizer with the URL of the Evernote service,
// your key, and your secret.
var EvernoteAuthorizer = new EvernoteAuthorizer(
"https://sandbox.evernote.com",
"slyrp-1234", // Not my real id / secret :)
"7acafe123456badb123");
// First of all, get a request token from Evernote - this causes a
// webrequest from your server to Evernote.
// The callBackUrl is the URL you want the user to return to once
// they validate the app
var requestToken = EvernoteAuthorizer.GetRequestToken(callBackUrl);
// Persist this token, as we are going to redirect the user to
// Evernote to Authorize this app
Session["RequestToken"] = requestToken;
// Generate the Evernote URL that we will redirect the user to in
// order to
var callForwardUrl = EvernoteAuthorizer.BuildAuthorizeUrl(requestToken);
// Redirect the user (e.g. MVC)
return Redirect(callForwardUrl);
// ... Once the user authroizes the app, they get redirected to callBackUrl
// where we parse the request parameter oauth_validator and finally get
// our credentials
// null = they didn't authorize us
var credentials = EvernoteAuthorizer.ParseAccessToken(
Request.QueryString["oauth_verifier"],
Session["RequestToken"] as RequestToken);
// Example of how to use the credential with Evernote SDK
var noteStoreUrl = EvernoteCredentials.NotebookUrl;
var noteStoreTransport = new THttpClient(new Uri(noteStoreUrl));
var noteStoreProtocol = new TBinaryProtocol(noteStoreTransport);
var noteStore = new NoteStore.Client(noteStoreProtocol);
List<Notebook> notebooks = client.listNotebooks(EvernoteCredentials.AuthToken);
http://weblogs.asp.net/psteele/archive/2010/08/06/edamlibrary-evernote-library-for-c.aspx might help. As the author states it just bundles some and fixes some. Haven't tried it myself but thought I'd mention for a possibly easier way to get started. Possibly.
This might help too...found it using the Way Back Machine since the original blog site was offline.
https://www.evernote.com/pub/bluecockatoo/Evernote_API#b=bb2451c9-b5ff-49bb-9686-2144d984c6ba&n=c30bc4eb-cca4-4a36-ad44-1e255eeb26dd
The original blog post: http://web.archive.org/web/20090203134615/http://macrolinz.com/macrolinz/index.php/2008/12/
Scroll down and find the post from December 26 - "Get it while it's hot..."

Categories