bad http authentication header format auth0 asp.net - asp.net

I am using auth0 with ASP.NET for roles and permission implementation. I want to fetch all users details by using auth0 api. Below is my code,
Code 1:
var apiClient = new ManagementApiClient("Bearer <<Token>>", new Uri("<<URL>>"));
var allClients = await apiClient.Clients.GetAllAsync();
Code 2:
var client = new ManagementApiClient("Authorization: Bearer <<Token>>", new Uri("<<URL>>"));
IPagedList<User> users = await client.Users.GetAllAsync();
Above both code giving me error:
"bad http authentication header format auth0 asp.net"
tried same token and url in postman, And it's returning result,
Where I need to change to make it work?

According to the usage documentation for the ManagementApiClient class, the constructor receives just the token, so you should be calling it like:
new ManagementApiClient("<<Token>>", new Uri("<<URL>>"));
It will then automatically include that token in an HTTP Authorization header using the Bearer scheme.

Related

Recaptcha verification failed - SITE_MISMATCH

I've been trying to send a verification code to a phone via the Google Identity Toolkit API, I have all the right keys generated via Google Cloud Console and the ReCaptcha V3 token generated by the web app (See in code) but I still get an error when trying to send a request to the account:sendVerificationCode endpoint of the API. Maybe someone can help the community who has encountered this error too and me.
Important: I'm calling the endpoint from a valid URL added in the Google Cloud Console. It is an Authorized Domain.
Framework: Ionic + Angular
Language: Typescript
Environment Variables:
googleapisurl: "https://identitytoolkit.googleapis.com/v1/accounts:sendVerificationCode"
Error:
Code to get the ReCaptcha V3 token (ng-recapcha library):
this.recaptchaToken = await firstValueFrom(this.recapchaV3Service.execute('importantAction'));
Code to send the HTTP request using Angular HTTP Client:
let map: Map<string, string> = new Map<string, string>();
map.set("phoneNumber", this.phoneNumber);
map.set("recaptchaToken", this.recaptchaToken);
let jsonObject = {};
map.forEach((value, key) => {
jsonObject[key] = value
});
let url: URL = new URL(environment.googleapisurl);
url.searchParams.append("key", environment.googlecloudapikey);
await firstValueFrom(this.httpClient.post(url.toString(), JSON.stringify(jsonObject))).then(response => {
console.log(response);
this.presentAlert();
});
Note: Trying from Postman gets the same error.

How to write method in ASP.net to get the token from OAuthAPI

Getting Access token from OAuth and passing it in the header for each of the request.
I have api at: https://login.microsoftonline.com/48b0431c-82f6-4ad2-a023-ac96dbf5614e/oauth2/token
And in Postman can see the access token getting returned.
I am trying to call this APIM api in my existing 4.5 .NET application. And wrote the following:
Dim client = InitializeTokenClient()
Using content As New StringContent(String.Empty)
Dim response = client.PostAsync($"48b0431c-82f6-4ad2-a023-ac96dbf5614e/oauth2/token", content).Result
If (response.StatusCode = HttpStatusCode.OK) Then
response.
End If
Return response
End Using
I am not sure how to access the access_token from the response object and also how would I be passing the access token to make subsequent APIM api calls?
You can take the access_token from the response by deserializing the response:
Add a reference to System.Web.Extensions and add Imports System.Web.Script.Serialization to the top of your file. Then the following code will get the access_token:
Dim j As Object = New JavaScriptSerializer().Deserialize(Of Object)(response)
Dim accessToken = j("access_token")
You can then use the token when calling the API by adding an Authorization header with the value Bearer <token>.

DropboxServiceProvider api with .Net

Trying to use Spring Net Social Dropbox
OAuthToken oauthToken = dropboxServiceProvider.OAuthOperations.FetchRequestTokenAsync(callBackUrl, null).Result;
Console.WriteLine("Done");
OAuth1Parameters parameters = new OAuth1Parameters();
parameters.Add("locale", CultureInfo.CurrentUICulture.IetfLanguageTag); // for a localized version of the authorization website
string authenticateUrl = dropboxServiceProvider.OAuthOperations.BuildAuthorizeUrl(oauthToken.Value, parameters);
Console.WriteLine("Redirect user for authorization");
Process.Start(authenticateUrl);
After redirecting user to authenticate him with dropbox how to get the request access token as I am the request would be going to call back url.
Can I create new instance of OAuthToken and new instance of dropboxserviceprovider and use it to get the access token.
AuthorizedRequestToken requestToken = new AuthorizedRequestToken(oauthToken, null);
OAuthToken oauthAccessToken = dropboxServiceProvider.OAuthOperations.ExchangeForAccessTokenAsync(requestToken, null).Result;
Console.WriteLine("Done");
/* API */
Console.WriteLine(oauthAccessToken.Value);
Console.WriteLine(oauthAccessToken.Secret);
IDropbox dropbox = dropboxServiceProvider.GetApi(oauthAccessToken.Value, oauthAccessToken.Secret);
You can store the access token in the session.
You can create a DropboxServiceProvider any time you need, what's important is the oauth access token.
Take a look to the MVC quickstart provided in the package.

ASP.Net Web API - Authorization header blank

I am having to re-write an existing REST API using .NET (originally written with Ruby). From the client's perspective, it has to work exactly the same way as the old API - i.e. the client code mustn't need to change. The current API requires Basic Authentication. So to call the old API, the following works perfectly:-
var wc = new System.Net.WebClient();
var myCache = new CredentialCache();
myCache.Add(new Uri(url), "Basic", new NetworkCredential("XXX", "XXX"));
wc.Credentials = myCache;
var returnBytes = wc.DownloadData("http://xxxx");
(I have had to ommit the real URL / username / password etc for security reasons).
Now I am writing the new API using ASP.Net Web API with MVC4. I have a weird problem and cannot find anybody else with exactly the same problem. In order to support Basic Authentication, I have followed the guidelines here:
http://sixgun.wordpress.com/2012/02/29/asp-net-web-api-basic-authentication/
One thing, I put the code to "hook in the handler" in the Global.asax.cs file in the Application_Start() event (that wasn't explained so I guessed).
Anyway, if I call my API (which I have deployed in IIS) using the above code, the Authorization header is always null, and the above fails with 401 Unauthorized. However, if I manually set the header using this code, it works fine - i.e. the Authorization header now exists and I am able to Authenticate the user.
private void SetBasicAuthHeader(WebClient request, String userName, String userPassword)
{
string authInfo = userName + ":" + userPassword;
authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));
request.Headers["Authorization"] = "Basic " + authInfo;
}
.......
var wc = new System.Net.WebClient();
SetBasicAuthHeader(request, "XXXX", "XXXX");
var returnBytes = wc.DownloadData("http://xxxx");
Although that works, it's no good to me because existing users of the existing API are not going to be manually setting the header.
Reading up on how Basic Authentication works, the initial request is meant to be anonymous, then the client is returned 401, then the client is meant to try again. However if I put a break point in my code, it will never hit the code again in Antony's example. I was expecting my breakpoint to be hit twice.
Any ideas how I can get this to work?
You're expecting the right behavior. System.Net.WebClient does not automatically include the Authorization headers upon initial request. It only sends them when properly challenged by a response, which to my knowledge is a 401 status code and a proper WWW-Authenticate header. See here and here for further info.
I'm assuming your basic authentication handler is not returning the WWW-Authenticate header and as such WebClient never even attempts to send the credentials on a second request. You should be able to watch this in Fiddler or a similar tool.
If your handler did something like this, you should witness the WebClient approach working:
//if is not authenticated or Authorization header is null
return base.SendAsync(request, cancellationToken).ContinueWith(task =>
{
var response = task.Result;
response.StatusCode = HttpStatusCode.Unauthorized;
response.Headers.Add("WWW-Authenticate", "Basic realm=\"www.whatever.com\"");
return response;
});
//else (is authenticated)
return base.SendAsync(request, cancellationToken);
As you noticed, if you include the Authorization headers on every request (like you did in your alternative approach) then your handler already works as is. So it may be sufficient - it just isn't for WebClient and other clients that operate in the same way.

Extend forms authentication to use a custom http header for ticket

I have a wcf webhttp service which uses forms authentication to authenticate users. This works fine if the ticket comes in the cookie collection or in the url.
But now I want to send the string of the forms auth ticket in a custom http header and change the forms auth module to check for that header instead of the cookie.
I think it should be easy to extend forms auth to achive this, but could not find any resources of how to. Can you point me in the right direction ?
here's how my authentication flow would work,
A client calls the authenticate method with the username and pwd
Service returns the encrypted ticket string
Client send the received ticket string in a http header with every subsequent request
Service checks for auth header and validates the auth ticket
FormAuthentication module is not extendible, but you could write your own authentication.
It is very simple:
Authentication(2):
var formsTicket = new FormsAuthenticationTicket(
1, login, DateTime.Now, DateTime.Now.AddYears(1), persistent, String.Empty);
var encryptedFormsTicket = FormsAuthentication.Encrypt(formsTicket);
//return encryptedFormsTicket string to client
Service call with attached ticket(4):
var ticket = FormsAuthentication.Decrypt(encryptedFormsTicket)
//extract authentication info from ticket: ticket.Name
I am not sure this is the way to go (elegance-wise), but what about adding an event in global.asax.cs for Application BeginRequest and taking the string from the header and injecting a cookie into the Request yourself (Forms authentication should then pick that up).
Something like:
protected void Application_BeginRequest()
{
// Your code here to read request header into cookieText variable
string cookieText = ReadCookieFromHeader();
var cookieData = FormsAuthentication.Decrypt(cookieText);
if (!cookieData.Expired)
{
HttpContext.Current.Request.Cookies.Add(new HttpCookie(cookieData.Name, cookieText));
}
}
DISCLAIMER: Please note that I didn't test this, just throwing a possible approach your way!

Resources