How to get Basic Authentication Information in a Firefox Extension? - firefox

I'm coding a Firefox extension and want to get Basic Authentication information for a website (or for the current document).
How can I get Basic Authentication Information in a Firefox Extension?

Here is some sample code for using nsIHttpAuthManager:
Instantiate the component:
var proxyAuthenticationComponent = Components.classes["#mozilla.org/network/http-auth-manager;1"].getService(Components.interfaces.nsIHttpAuthManager);
Set the information:
proxyAuthenticationComponent.setAuthIdentity('http','192.168.0.1',80,"basic","Some Realm","","","username","password");
Get the information:
var domain = {}; //Will contain {value: ""}
var username = {}; //Will contain {value: "username"}
var password = {}; //Will contain {value: "password"}
proxyAuthenticationComponent.getAuthIdentity('http','192.168.0.1',80,"basic","Some Realm","",domain,username,password);
I used this in a Thunderbird extension.
Hope this help.

I couldn't find an exact answer and don't have time to experiment now, but it seems that the only way is to manually examine headers using NsIHttpChannel.
EDIT:
Ok, I've found nsIHttpAuthManager:
This service provides access to cached HTTP authentication user credentials (domain, username, password) for sites visited during the current browser session.
Looks like exactly what you need.

Related

ASP.NET Core 6 non Default Identity UI based Authentication with email/sms based TFA

I have to port a website which has a TFA authentication via sms/email to asp.net 6. The client doesn’t want to use an authenticator app. The application has some specialities such as the language of the user in the URL path as the first component.
In this post I searched a way to introduce the language part and was, although in a very ugly manner, successful.
However I'm also quite unhappy to use the default UI in general for this application, since I have to manually deactivate all the things that are not required but are included in the library. It feels extremely untidy to have such a huge framework of pages active for so little of required functionality. The only things I need are
Login with a username and password
Optionally checking a tfa email/sms code if the user has configured its account for this.
The configuration of the user's profile is done in another application and should not be included in this application (hence all the default identity ui stuff has to be deactivated).
I tried to create the authentication logic manually via controller actions and not installing the default ui at all. For the login with username and password, this was fairly easy.
However, setting up the TFA part seems quite tedious and dangerous (from a security perspective). I have not found any documentation what resources have to be registered and how to setup the authentication system.
Is searching out all the required dependencies and creating the code from the Microsoft source code of default identity UI the only way?
Or is there a template solution to accomplish the desired goal?
Since there seems no such information available, I gathered the necessary code from the ms source code. Maybe it helps someone:
Registration
Copied out of the ms source code, here the required registrations:
builder.Services.AddIdentityCore<MyUserType>().AddDefaultTokenProviders();
builder.Services.TryAddScoped<ITwoFactorSecurityStampValidator, TwoFactorSecurityStampValidator<MyUserType>>();
builder.Services.TryAddScoped<ISecurityStampValidator, SecurityStampValidator<MyUserType>>();
builder.Services.AddAuthentication(options => {
options.DefaultAuthenticateScheme = IdentityConstants.ApplicationScheme;
options.DefaultChallengeScheme = IdentityConstants.ApplicationScheme;
// options.DefaultSignInScheme = IdentityConstants.ExternalScheme;
})
.AddCookie(IdentityConstants.ApplicationScheme, o =>
{
o.LoginPath = [your login path];
o.LogoutPath = [your logout path];
})
//.AddCookie(IdentityConstants.ExternalScheme, o =>
//{
// o.Cookie.Name = IdentityConstants.ExternalScheme;
// o.ExpireTimeSpan = TimeSpan.FromMinutes(5);
//})
.AddCookie(IdentityConstants.TwoFactorRememberMeScheme, o =>
{
o.Cookie.Name = IdentityConstants.TwoFactorRememberMeScheme;
o.Events = new CookieAuthenticationEvents
{
OnValidatePrincipal = SecurityStampValidator.ValidateAsync<ITwoFactorSecurityStampValidator>
};
})
.AddCookie(IdentityConstants.TwoFactorUserIdScheme, o =>
{
o.Cookie.Name = IdentityConstants.TwoFactorUserIdScheme;
o.ExpireTimeSpan = TimeSpan.FromMinutes(5);
});
The registration for the external authentication is commented out, maybe someone wants to use that also, therefore i have not directly removed it from the code. The login path can be set accordingly to your login-action. See my other post about how to extend the login url to introduce language and other path components.
Controller-code
The controller's action code and views can then derived from the original default identity ui code. The AddDefaultTokenProviders call is required to have the email token provider registered.
Result
In this way, the default ui and all its abundant functionality is no more in the project and one can selectively decide, what parts to integrate.

How to call an external API in truclient protocol of loadrunner

I am recording a script using truclient protocol.In my script ,i need to externally call an API which generates the Password. The password is fetched using the co-relation,which is used as an input for Login.
I am however unable to call the external API using the true client protocol.
Could anybody please suggest how to call an external API in true client protocol.
Have you tried the evaluate JavaScript step? You can post the message to the server and get the generated password during the runtime. XHR and fetch API should be supported in Chrome and Firefox, TCIE should support XHR.
Sure. Please check the detail steps:
Drag and drop an evaluate JS step from TruClient
Open the script editor
Add these code, make sure use the sync XHR to ensure the password is returned before the end step started:
var xhr = new XMLHttpRequest();
xhr.open("POST", '/server', false);
//Send the proper header information along with the request
xhr.setRequestHeader("xxx", "value");
xhr.send();
if (this.status === 200) {
// Request finished. Do processing here.
}
var password = xhr.response;
Change the login password step from plain text to JS and use
ArgsContext.password
to reference the previous received password.
If you have another questions please let me know. How to use the argument context you could reference this link.
BTW. the window and document object of the page can be referenced with AUT.window, AUT.document in TruClient.
Please check the help document from here.

Does Google offer API access to the mobile friendly test?

Is there an API that allows access to Google's Mobile Friendly Test which can be seen at https://www.google.com/webmasters/tools/mobile-friendly/?
If you can't find one by googling, it probably doesn't exist.
A hacky solution would be to create a process with PhantomJS that inputs the url, submits it, and dirty-checks the dom for results.
PhantomJS is a headless WebKit scriptable with a JavaScript API.
However, if you abuse this, there is a chance that google will blacklist your ip address. Light use should be fine. Also be aware that google can change their dom structure or class names at any time, so don't be surprised if your tool suddenly breaks.
Here is some rough, untested code...
var url = 'https://www.google.com/webmasters/tools/mobile-friendly/';
page.open(url, function (status) {
// set the url
document.querySelector('input.jfk-textinput').value = "http://thesite.com";
document.querySelector('form').submit();
// check for results once in a while
setInterval(function(){
var results = getResults(); // TODO create getResults
if(results){
//TODO save the results
phantom.exit();
}
}, 1000);
});
There is an option in pagespeed api
https://www.googleapis.com/pagespeedonline/v3beta1/mobileReady?url={url}&key={api key}
key can be obtained form google cloud platform.
Acquire a PageSpeed Insights API KEY in https://console.developers.google.com/apis/api/pagespeedonline-json.googleapis.com/overview?project=citric-program-395&hl=pt-br&duration=P30D and create a credentials, follow the google's instructions.
In C# (6.0) and .NET 4.5.2, I did some like this:
(add in your project a reference for Newtonsoft.Json.)
String yourURL = "https://www.google.com.br";
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("https://www.googleapis.com");
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
var response = client.GetAsync($"/pagespeedonline/v3beta1/mobileReady?url={yourURL }&key=AIzaSyArsacdp79HPFfRZRvXaiLEjCD1LtDm3ww").Result;
string json = response.Content.ReadAsStringAsync().Result;
JObject obj = JObject.Parse(json);
bool isMobileFriendly = obj.Value<JObject>("ruleGroups").Value<JObject>("USABILITY").Value<bool>("pass");
There is an API (Beta) for the Mobile Friendly-Test. (Release Date: 31.01.2017).
The API test outputs has three statuses:
MOBILE_FRIENDLY_TEST_RESULT_UNSPECIFIED Internal error when running this test. Please try running the test again.
MOBILE_FRIENDLY The page is mobile friendly.
3.NOT_MOBILE_FRIENDLY The page is not mobile friendly.
Here are more informations: https://developers.google.com/webmaster-tools/search-console-api/reference/rest/v1/urlTestingTools.mobileFriendlyTest/run

Google Drive SDK 1.8.1 RedirectURL

Is there any way to provide RedirectURL then using GoogleWebAuthorizationBroker?
Here is the sample code in C#:
Task<UserCredential> credential = GoogleWebAuthorizationBroker.AuthorizeAsync(secrets, scopes, GoogleDataStore.User, cancellationToken, dataStore);
Or we have to use different approach?
I have an "installed application" that runs on a user's desktop, not a website. By default, when I create an "installed application" project in the API console, the redirect URI seems to be set to local host by default.
What ends up happening is that after the authentication sequence the user gets redirected to localhost and receives a browser error. I would like to prevent this from happening by providing my own redirect URI: urn:ietf:wg:oauth:2.0:oob:auto
This seems to be possible using Python version of the Google Client API, but I find it difficult to find any reference to this with .NET.
Take a look in the implementation of PromptCodeReceiver, as you can see it contains the redirect uri.
You can implement your own ICodeReceiver with your prefer redirect uri, and call it from a WebBroker which should be similar to GoogleWebAuthorizationBroker.
I think it would be great to understand why can't you just use PrompotCodeReceiver or LocalServerCodeReceiver.
And be aware that we just released a new library last week, so you should update it to 1.9.0.
UPDATE (more details, Nov 25th 2014):
You can create your own ICodeReceiver. You will have to do the following:
* The code was never tested... sorry.
public class MyNewCodeReceiver : ICodeReceiver
{
public string RedirectUri
{
get { return YOU_REDIRECT_URI; }
}
public Task<AuthorizationCodeResponseUrl> ReceiveCodeAsync(
AuthorizationCodeRequestUrl url,
CancellationToken taskCancellationToken)
{
// YOUR CODE HERE FOR RECEIVING CODE FROM THE URL.
// TAKE A LOOK AT THE FOLLOWING:
// PromptCodeReceiver AND LocalServerCodeReceiver
// FOR EXAMPLES.
}
}
PromptCodeReceiver
and LocalServerCodeReceiver.
Then you will have to do the following
(instead of using the GoogleWebAuthorizationBroker.AuthorizeAsync method):
var initializer = new GoogleAuthorizationCodeFlow.Initializer
{
ClientSecrets = secrets,
Scopes = scopes,
DataStore = new FileDataStore("Google.Apis.Auth");
};
await new AuthorizationCodeInstalledApp(
new GoogleAuthorizationCodeFlow(initializer),
new MyNewCodeReceiver())
.AuthorizeAsync(user, taskCancellationToken);
In addition:
I'll be happy to understand further why you need to set a different redirect uri, so we will be able to improve the library accordingly.
When I create an installed application the current PromptCodeReceiver and LocalServerCodeReceiver work for me, so I'm not sure what's the problem with your code.

Force google to show account chooser and consent screen

I am able to use both prompt=consent and prompt=select_account individually, but Google doesn't seem to allow me to combine them. I tried the prompt=consent+select_account as suggested in an answer of Force google account chooser, but that fails with the error: "Invalid prompt: consent+select_account".
The doc (https://developers.google.com/accounts/docs/OAuth2Login) says "A space-delimited list", so I tried consent select_account but that fails with: "The requested URL was not found on this server."
I also tried combining prompt=select_account and approval_prompt=force, but Google doesn't like that either.
Anyone else have luck with combining consent screen and account chooser?
Update:
This is my JavaScript method creating URL for getting contacts from gmail
$scope.importGmailContacts = function() {
provider = 'gmail';
$scope.importing_from_gmail = true;
window.open(protocol + "://" + host + ":" + port + "/contacts/gmail", "_blank",
"toolbar=yes, scrollbars=yes, resizable=yes, top=0, left=0, width=600, height=600, prompt='select_account+consent', approval_prompt=force");
}
I have tried setting prompt and approval_prompt both collectively and individually but it does not seems to work. Refer to this question.
You need add: access_type=online&prompt=select_account+consent:
private static final String AUTHORIZE_URL
= "https://accounts.google.com/o/oauth2/auth?"
+ "response_type=code&access_type=online&prompt=select_account+consent"
+ "&client_id=xxx&redirect_uri=xxx";
private static final String SCOPED_AUTHORIZE_URL = AUTHORIZE_URL + "&scope=xxx";
..
I just tried this and it DID work when space-delimited:
options[:prompt] = 'select_account consent'
https://accounts.google.com/o/oauth2/auth?client_id=XXXX&redirect_uri=urn:ietf:wg:oauth:2.0:oob&scope=https://www.googleapis.com/auth/analytics.readonly&response_type=code&prompt=select_account+consent&approval_prompt=force
Results in the error
That’s an error.
Error: invalid_request
Conflict params: approval_prompt and prompt
Prompt and approval_prompt parameters can not be used together.
prompt Optional. A space-delimited, case-sensitive list of prompts to present the user. If you don't specify this parameter, the user will be prompted only the first time your app requests access. Possible values are:
none Do not display any authentication or consent screens. Must not be specified with other values.
consent Prompt the user for consent.
select_account Prompt the user to select an account.
If memory serves approval_prompt is the older way of doing it and google added Prompt sometime in 2012. I cant actually find any documentation on approval_prompt anymore but if memory serves it was the same as doing prompt=consent it just requested access again.

Resources