Currently setting up a testing framework using Cypress for our NextJS application. We handle authentication using the nextjs-auth0 library as recommended.
Using this library poses a problem authenticating when under test as we need to exercise the protected routes via logging in our test account etc. For obvious reasons, I do not want to login to the application via the Auth0 UI which is triggered when using the /api/auth/login, callback etc etc, although this does work as expected.
There doesn't seem to be a great deal of information on this. I have managed to retrieve the accessToken for the user through the <domain>/oauth/token endpoint but I am struggling to understand how I go about creating a session, encrypting this, and persisting it as the appSession.0 cookie.
I found this library cypress-nextjs-auth0 which claims to do what I need but when trying to use it I get errors due to it being unmaintained and last updated a few years ago.
I attempted to use the source code to implement by own solution but as I mentioned above I am struggling with encrypting the session - in the library they use this function to encrypt the session but their version of jose seems old as the latest version doesn't have these methods (see their implementation below):
const hkdf = require('futoin-hkdf');
const { JWK, JWE } = require('jose');
const BYTE_LENGTH = 32;
const ENCRYPTION_INFO = 'JWE CEK';
const options = { hash: 'SHA-256' };
const deriveKey = secret =>
hkdf(secret, BYTE_LENGTH, { info: ENCRYPTION_INFO, ...options });
module.exports = function encrypt(arg) {
const { secret, ...thingToEncrypt } = arg;
const key = JWK.asKey(deriveKey(secret));
const epochNow = (Date.now() / 1000) | 0;
return Promise.resolve(
JWE.encrypt(JSON.stringify(thingToEncrypt), key, {
alg: 'dir',
enc: 'A256GCM',
uat: epochNow,
iat: epochNow,
exp: epochNow + 7 * 24 * 60 * 60,
}),
);
};
Ideally, I would need to take the data from the access_token and store encrypted the session in the cookies, however I am unsure how I can achieve this.
Has anyone had an experience configuring authentication using auth0 to integrate with the nextjs-auth0 implementation when using Cypress or other testing frameworks which would be applicable as the solution would be universal, and if so what was your implementation?
TIA
Related
I am trying to fetch git azure devops api to get information about repositories and branches in js.
In order to achieve that, I made a little application with the following code :
$(document).ready(function() {
var personalToken = btoa(':'+'<personnalAccessToken>');
fetch('https://dev.azure.com/<company>/<project>/_apis/git/repositories?api-version=5.1', {
method: 'GET',
headers: {
'Content-Type': 'application/json'
'Authorization': 'Basic '+ personalToken
}
}).then(function(response) {
return response.json();
}).then(function(repositories) {
console.log("There are "+repositories.count+" repositories");
}).catch(function(error) {
console.log('Fetch error: ' + error.message);
});
This code is working great but as you can see there is my personnalAccessToken writen directly inside the code... which is really bad...
When I am using git in command line, I don't have to specify any credential information because I use git credential manager for windows. Which means my personnalAccessToken is already stored, cached and automatically used everytime I use a git command, like clone, etc.
So, I would like my js code to use the same thing, I would like it to use my stored credentials automatically to fetch the api without being required to set my personnalAccessToken in code.
I have already searched for hours but can't find out if it is possible.
I have already searched for hours but can't find out if it is
possible.
Sorry but as I know it's impossible. The way you're calling the Rest API is similar to use Invoke-RestMethod to call rest api in Powershell.
In both these two scenarios, the process will try to fetch PAT for authentication in current session/context and it won't even try to search the cache in Git Credential Manager.
You should distinguish the difference between accessing Azure Devops service via Rest API and by Code:
Rest API:
POST https://dev.azure.com/{organization}/{project}/{team}/_apis/wit/wiql?api-version=5.1
Request Body:
{
"query": "Select [System.Id], [System.Title], [System.State] From WorkItems Where [System.WorkItemType] = 'Task' AND [State] <> 'Closed' AND [State] <> 'Removed' order by [Microsoft.VSTS.Common.Priority] asc, [System.CreatedDate] desc"
}
Corresponding Code in C#:
VssConnection connection = new VssConnection(new Uri(azureDevOpsOrganizationUrl), new VssClientCredentials());
//create http client and query for resutls
WorkItemTrackingHttpClient witClient = connection.GetClient<WorkItemTrackingHttpClient>();
Wiql query = new Wiql() { Query = "SELECT [Id], [Title], [State] FROM workitems WHERE [Work Item Type] = 'Bug' AND [Assigned To] = #Me" };
WorkItemQueryResult queryResults = witClient.QueryByWiqlAsync(query).Result;
Maybe you can consider using a limited PAT, limit its scope to Code only:
I know there exists other Authentication mechanism
:
For Interactive JavaScript project: ADALJS and Microsoft-supported Client Libraries.
You can give it a try but I'm not sure if it works for you since you're not using real Code way to access the Azure Devops Service... Hope it makes some help :)
If you have the script set up in an Azure Runbook you can set it as an encrypted variable there and have it pull it from there before running rather than having it directly written into the code.
$encryptedPatVarName = "ADO_PAT"
$adoPat = Get-AutomationVariable -Name $encryptedPatVarName
$adoPatToken = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$($adoPat)"))
$adoHeader = #{authorization = "Basic $adoPatToken"}
The above is the Powershell version of it. I have seen some people do it with other
So, as the title suggests, I'm looking for a way to integrate my own custom authentication service into the parse server, which is installed inside a docker container. This authentication is basically an OpenID implementation of KeyCloak.
The point is that I don't (and it would be best for my architecture not to) have parse server served with express on my local machine.
What I've been trying so far, was to search the internet, read the issues, read the parse server documents for JavaScript and the guide and other stuff to find out, how can I achieve it.
It seems that it doesn't matter what I do, at the end of each test, I get a 252 This authentication method is unsupported error! (this happens even if I use facebook, oauth, oauth2, etc).
So right now, the docker-compose service looks like this:
parse-server:
image: parseplatform/parse-server
ports:
- "${SERVER_PORT}:1337"
restart: "always"
volumes:
- ./server/parse/custom-auth:/parse-server/custom-auth
depends_on:
- mongodb
links:
- mongodb:mongo
environment:
- PARSE_SERVER_APPLICATION_ID=${APP_ID}
- PARSE_SERVER_MASTER_KEY=${MASTER_KEY}
- PARSE_SERVER_DATABASE_URI=mongodb://mongo:${MONGO_PORT}/dev
- PARSE_SERVER_START_LIVE_QUERY_SERVER=1
- PARSE_SERVER_LIVE_QUERY={"classNames":${LIVE_QUERY_CLASSES}}
- PARSE_SERVER_MOUNT_GRAPHQL=${GQL_API}
- PARSE_SERVER_MOUNT_PLAYGROUND=${GQL_PLAYGROUND}
- PARSE_SERVER_AUTH_PROVIDERS={"swwwan-mail-auth":{"module":"/parse-server/custom-auth/swwwan-mail-auth/index.js"}}
and the login/signup part:
export const loginWithParse = async (account: IUserColumnTypes) => {
if (account.username === null || account.password === null) {
throw "validation failed";
}
// #ts-ignore
const loggedIn = await Parse.User.logInWith("swwwan.mail-auth", {
authData: {
id: "",
access_token: "",
},
});
console.log({ loggedIn });
//return await Parse.User.logIn(account.username, account.password);
};
another alternative for login/signup:
export const loginWithParse = async (account: IUserColumnTypes) => {
if (account.username === null || account.password === null) {
throw "validation failed";
}
const u = new Parse.User();
u._linkWith("swwwan-mail-auth", {
authData: {
id: "tester",
access_token: "sample_access_token",
},
})
.then(res => console.log(res))
.catch(e => console.log(e));
//return await Parse.User.logIn(account.username, account.password);
};
UPDATE: by using the second alternative, I actually get the error:
error: Parse error: Invalid key name: authData.swwwan-mail-auth.id {"code":105,"stack":"Error: Invalid key name: authData.swwwan-mail-auth.id
Is there a way to make it work? probably I'm missing something here.
tnx :)
note that the 'dangle' in the link functions will be deprecated in the forthcoming 2.9 release of the Parse JS SDK
Sorry that the documentation isn't better yet. Will be getting some more work
What you're attempting is doable!
Your final error is giving one big clue: the name of your adapter can't have any characters that aren't valid for a javascript identifier. In this case, the - is causing a problem since when we save it in the database, the adapter name is used as a key.
The unit tests are often the best documentation and you may find them helpful in this case.
See:
the declaration of a custom adapter
Configuring the server to load the adapter (you're doing this right)
using the adapter
Im looking for an authentication system where the user submits to an enpoint and a jwt is generated at this endpoint, im not sure how to implement this, my client side application does not make use of email address or stored information, it is in fact a dApp. I just need an endpoint that will calculate a value from a supplied seed phrase and a password if the processing of these values goes well ( and it nearly always will unless someone sends junk to the endpoint) then a jwt will be issued.. so far the out of box functionality with feathers cli means that i need to use local strategy and need an email address, I cant find any demos out there on this.. anyone got any pointers ? so far my auth is pretty default
const authentication = require('#feathersjs/authentication');
const jwt = require('#feathersjs/authentication-jwt');
const local = require('#feathersjs/authentication-local');
module.exports = function (app) {
const config = app.get('authentication');
// Set up authentication with the secret
app.configure(authentication(config));
app.configure(jwt());
app.configure(local());
// The `authentication` service is used to create a JWT.
// The before `create` hook registers strategies that can be used
// to create a new valid JWT (e.g. local or oauth2)
app.service('authentication').hooks({
before: {
create: [
authentication.hooks.authenticate(config.strategies)
],
remove: [
authentication.hooks.authenticate('jwt')
]
}
});
};
and heres my service:
// Initializes the `aerAuth` service on path `/userauthendpoint`
const createService = require('feathers-memory');
const hooks = require('./userauthendpoint.hooks');
module.exports = function (app) {
const paginate = app.get('paginate');
const options = {
name: 'userauthendpoint',
paginate
};
// Initialize our service with any options it requires
app.use('/userauthendpoint', createService(options) );
// Get our initialized service so that we can register hooks and filters
const service = app.service('userauthendpoint');
service.hooks(hooks);
};
I am relatively new to feathers but not to building auth systems (in PHP)
The Custom authentication strategy guide and the feathers-authentication-custom plugin probably allow to do what you are looking for.
It also depends on how you want to implement this. You can either use the custom strategy for every service (as in the case of the API key which has to be sent in the header with every request) or just before the /authentication service to allow creating a JWT (the issue here is that it needs to reference a userId or other entityId that exists in the database which you don't have).
The easiest way would be to go with the first options and a custom header (X-DAP-PASSWORD) which could look like this:
const custom = require('feathers-authentication-custom');
app.configure(authentication(settings));
app.configure(custom((req, done) => {
const password = req.headers['x-dap-password'];
if(checkPassword(req.app.get('seedPassphrase'), password)) {
// implement your own custom logic for loading and verifying the user
done(null, user);
} else {
done(new Error('Invalid passphrase'));
}
}));
I just start create a live chat app with Twilio.
I have downloaded the twilio-csharp library from twilio.com/docs/csharp/install and started with a sample console application.
code example from Twilio:
// Download the twilio-csharp library from twilio.com/docs/csharp/install
using System;
using Twilio.IpMessaging;
class Example {
static void Main (string[] args) {
// Find your Account Sid and Auth Token at twilio.com/user/account
const string accountSid = "accountSid";
const string authToken = "authToken";
const string serviceSid = "serviceSid";
const string channelSid = "channelSid";
// List all Messages
var client = new IpMessagingClient(accountSid, authToken);
MessageResult result = client.ListMessages(serviceSid, channelSid);
Console.WriteLine(result);
}
}
But this code doesn't work in my case, I got always an errors "type or namespace could not be found".
I have these like reference:
I tried tutorial of IP Messaging , it works. But in the tutorial, they used Javascript SDK to initialize the IP messaging client
tc.accessManager = new Twilio.AccessManager(tokenResponse.token);
tc.messagingClient = new Twilio.IPMessaging.Client(tc.accessManager);
So I just don't understand how can I use this C# library to send an IP Messaging, or maybe I can just control my IP Messaging applications from the client side?
I unstand why I got this error.
I just follow the steps of installation on twilio-csharp library gitHub. But this project's README is only for SMS project. If we want to use Library for IpMessaging, we must also import another Library, Twilio.IpMessaging.
So What I got know like reference and the project IP Messaging works.
Hope this will help the others.
I have a javascript windows store app that is authenticathing with AAD via Microsoft.Preview.WindowsAzure.ActiveDirectory.Authentication library. It works against an ASP.NET WebAPI hosted in Azure. It works fine, it prompst the user to login (windows login service), once logged the user can work and is not asked to log in again. The problem I have found is that when the user does not use the app for a time, I´m not sure but I Think is between 20 and 30 minutes, the app gets iddle. It does not respond to user querys. I think comunication with webApi is lost, I'm not sure if the token acquired by the app is expired or Azure itself cuts the connection.
This is how I'm getting the token
var authcontext = new aal.AuthenticationContext(audience);
aal.DefaultTokenCache().clear();
return authcontext.acquireTokenAsync(resource, clientID, redirectUri.absoluteUri, "", null).then(function (result) {
if (aal.AuthenticationStatus.succeeded == result.status) {
accessToken = result.accessToken;
return true;
}
}
and the webApi call
var uri = new Windows.Foundation.Uri(apiUrl + apiName);
var httpClient = new Windows.Web.Http.HttpClient();
httpClient.defaultRequestHeaders.authorization =
new Windows.Web.Http.Headers.HttpCredentialsHeaderValue("Bearer", accessToken);
return httpClient.getAsync(uri).then(function (response) {
if (response.isSuccessStatusCode == true)
return response.content.readAsStringAsync().then(function (responseText) {
var array = JSON.parse(responseText);
return array;
});
else
{
var md = new Windows.UI.Popups.MessageDialog(response, "Error");
md.showAsync();
}
});
I`ve tried adding
<sessionTokenRequirement lifetime="96:00:00" /> and <cookieHandler persistentSessionLifetime="60.0:0:0" requireSsl="true" /> in the web.config but still getting the error.
I am trying unsuccesfully adding ADAL new releases to the project because I read something about refresh tokens, I'm working on it but don´t find any example for windows store apps.
Any clue about the cause of the problem and how to solve it??
Thanks for your time.
The library version you are using is ancient and not supported. Also, cookies play no part in the api communications.
I recommend switching to the latest stable ADAL. Windows Store sample using ADAL: https://github.com/AzureADSamples/NativeClient-WindowsStore