How to get Auth Token of Azure to create azure resources programmatically - javascript

I want to create azure resources but I am having an issue while generating the token credential for creating such resources.
The following is the way to create azure postgres SQL but I need to Pass the credentials
But I don't know how to generate that token programitaillcay.
I need help for this.
const msRestAzure = require('ms-rest-azure');
const PostgreSQLManagementClient = require('azure-arm-postgresql');
const subscriptionID = '<subscription id>';
const resourceGroup = '<resource group name>';
const serverName = '<server name>'; // must be globally unique
msRestAzure.interactiveLogin().then((credentials) => {
let client = new PostgreSQLManagementClient(credentials, subscriptionID);
return client.servers.createOrUpdate(resourceGroup, serverName, {
location: 'eastus',
properties: {
createMode: 'Default',
administratorLogin: 'postgres',
administratorLoginPassword: 'F00Bar!!'
}
});
}).then((server) => {
console.log('Server:');
console.dir(server, {depth: null, colors: true});
}).catch((err) => {
console.log('An error ocurred');
console.dir(err, {depth: null, colors: true});
});
Does anyone know how to generate it? and using what? It's a signed token I guess using Client Id and tenant ID But how to generate it.
There's no documentation provided to generate it programitially. Is there any way?

interactiveLogin() will provide a link and a code that will allow the user to authenticate from a browser.
When using the Node.js SDK programmatically, there are 2 methods.
1)You could use your username and password to authenticate with the API using your Azure account. It's not recommended because it requires a very high degree of trust in the application, and carries risks which are not present in other flows.
const Azure = require('azure');
const MsRest = require('ms-rest-azure');
MsRest.loginWithUsernamePassword(process.env.AZURE_USERNAME, process.env.AZURE_PASSWORD, (err, credentials) => {
if (err) throw err;
let client = new PostgreSQLManagementClient(credentials, subscriptionID);
// ...
});
2)You may want to use service principal authentication rather than providing your account credentials. It is based on service principal without user account. First, create service principal in Azure portal.
const Azure = require('azure');
const MsRest = require('ms-rest-azure');
MsRest.loginWithServicePrincipalSecret(
'clientId/appId',
'client-secret',
'tenantId',
(err, credentials) => {
if (err) throw err
let client = new PostgreSQLManagementClient(credentials, subscriptionID);
// ...
}
);
For more detail about JavaScript authentication samples using ms-rest-azure library, see here.
Update:
If using service principal, try to add Azure OSSRDBMS Database application permission. Navigate to Azure AD > your app > API permission. And remember to grant admin consent for your tenant.

Related

The request is not valid for the application's 'userAudience' configuration

Tried to login via microsoft provider but after providing my email in the popup I m getting following error:
error_description=The request is not valid for the application's 'userAudience' configuration. In order to use /common/ endpoint, the application must not be configured with 'Consumer' as the user audience. The userAudience should be configured with 'All' to use /common/ endpoint.
I m not sure where exactly I need to set it as consumer. Here is my code
const provider = new OAuthProvider("microsoft.com");
signInWithPopup(auth, provider)
.then((result) => {
console.log("doLogin then section");
// User is signed in.
// IdP data available in result.additionalUserInfo.profile.
// Get the OAuth access token and ID Token
const credential = OAuthProvider.credentialFromResult(result);
const accessToken = credential.accessToken;
const idToken = credential.idToken;
})
.catch((error) => {
console.log("doLogin", error);
});
it's common error
Create a new App Registration with supported account type as "All Microsoft account users" works with any errors.

Initialise Azure Application Client in TypeScript

New to Typescript and still getting used to Microsoft Azure so please excuse the basic question.
I have created an Enterprise Application which should be able to log into the Graph API and read a user profile. I have the client id/secret , tenant id but I need to know how to initialise this client within TypeScript.
Am i supposed to initialise a GraphClient or is there a a generic Client I can use?
A link to a tutorial/example or documentation on how to do this would be amazing.
For context I want to be able to write one function to initialise the client and subsequently write the query- all the docs talk about multiple files which I cannot utilise because I am writing this as a third party integration.
I have found this but it seems very complex and I can't really follow it.
Is there a typescript equivalent of
client_credential = ClientSecretCredential(tenant_id, client_id, client_secret)
client = GraphClient(credential=self.client_credential,
scopes=['https://graph.microsoft.com/.default']
)
This is the way I've managed to do it. I'm bounded by using an extremely old version of the microsoft graph module unfortunately.
const qs = require('qs');
const MicrosoftGraphClient = require('#microsoft/microsoft-graph-client#1.0.0');
const axios = require('axios#0.27.2');
const getToken = async () => {
try{
const response = await axios.post(
`https://login.microsoftonline.com/${tenantId}/oauth2/v2.0/token`,
qs.stringify(
{
client_id : clientId,
client_secret: clientSecret,
scope: 'https://graph.microsoft.com/.default',
grant_type: 'client_credentials'
}
))
let tokenSet = response.data;
return tokenSet.access_token;
} catch (error){
console.log(error)
};
}
var client = MicrosoftGraphClient.Client.init({
authProvider: async (done) => {
const token = await getToken()
done(null, token);
}
});

How to get user parameters using Amazon Cognito hosted Web UI

Recently I was using the Sign-up and Sign-in template similar this one developed by Vladimir Budilov.
But now, I've been modifying my application to use the hosted UI developed by Amazon. So my application redirects to the hosted UI, all the authentication is made there and they send me the authentication token, more os less as explained in this tutorial.
Summarizing, I call the hosted UI and do login:
https://my_domain/login?response_type=token&client_id=my_client_id&redirect_uri=https://www.example.com
I'm redirected to:
https://www.example.com/#id_token=123456789tokens123456789&expires_in=3600&token_type=Bearer
So, I have now the token_id but I can't get the current user or user parameters from this. Could anyone help me with informations or some directions?
I've tried the methods in Amazon developer guide .
It works well when I was using Vladimir Budilov's template but trying to use the token_id, I'm not succeeding. Thanks in advance for your time and help.
var data = {
UserPoolId : '...', // Your user pool id here
ClientId : '...' // Your client id here
};
var userPool = new AmazonCognitoIdentity.CognitoUserPool(data);
var cognitoUser = userPool.getCurrentUser();
if (cognitoUser != null) {
cognitoUser.getSession(function(err, session) {
if (err) {
alert(err);
return;
}
console.log('session validity: ' + session.isValid());
AWS.config.credentials = new AWS.CognitoIdentityCredentials({
IdentityPoolId : '...' // your identity pool id here
Logins : {
// Change the key below according to the specific region your user pool is in.
'cognito-idp.<region>.amazonaws.com/<YOUR_USER_POOL_ID>' : session.getIdToken().getJwtToken()
}
});
// Instantiate aws sdk service objects now that the credentials have been updated.
// example: var s3 = new AWS.S3();
});
}
The attributes you configure to be added as claims are already available inside the id_token with base64 encoding (Since its a JWT token).
You can decode the token and access these attributes both at Client Side using Javascript and on Server.
For more info refer the StackOverflow question How to decode JWT tokens in JavaScript.
Note: If you need to trust these attributes for a backend operation, make sure you verify the JWT signature before trusting the attributes.
Here's a specific example of how to parse the callback parameters and set up a user session. This could be initiated in onLoad of your page.
import { CognitoAuth } from 'amazon-cognito-auth-js';
const authData = {
ClientId : '<TODO: add ClientId>', // Your client id here
AppWebDomain : '<TODO: add App Web Domain>',
TokenScopesArray : ['<TODO: add scope array>'], // e.g.['phone', 'email', 'profile','openid', 'aws.cognito.signin.user.admin'],
RedirectUriSignIn : '<TODO: add redirect url when signed in>',
RedirectUriSignOut : '<TODO: add redirect url when signed out>',
IdentityProvider : '<TODO: add identity provider you want to specify>', // e.g. 'Facebook',
UserPoolId : '<TODO: add UserPoolId>', // Your user pool id here
AdvancedSecurityDataCollectionFlag : '<TODO: boolean value indicating whether you want to enable advanced security data collection>', // e.g. true
Storage: '<TODO the storage object>' // OPTIONAL e.g. new CookieStorage(), to use the specified storage provided
};
const auth = new CognitoAuth(authData);
auth.userhandler = {
onSuccess: function(result) {
alert("Sign in success");
showSignedIn(result);
},
onFailure: function(err) {
alert("Error!");
}
};
const curUrl = window.location.href;
auth.parseCognitoWebResponse(curUrl);
Now you're "signed in" as far as the Cognito JS client is concerned, and you can use getCurrentUser(), getSession(), etc. `See "Use case 2" here for more context/details.

Feathers JS authentication with no email

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'));
}
}));

Using AWS Cognito can I resolve the authenticated IdentityId given a disabled unauthenticated IdentityId?

I have a JavaScript web application that supports Cognito unauthenticated identities. I'm trying to figure out how to identify the linked authenticated IdentityId for a DISABLED unauthenticated IdentityId.
First unauthenticated users are issued an IdentityId via AWS.config.credentials.get. Internally CognitoIdentityCredentials is using getId to generate a new unauthenticated IdentityId.
let unathenticatedIdentityId;
const AWS = require('aws-sdk');
AWS.config.region = region;
AWS.config.credentials = new AWS.CognitoIdentityCredentials({
IdentityPoolId
});
AWS.config.credentials.get(err => {
unathenticatedIdentityId = AWS.config.credentials.identityId;
});
Then our user authenticates to a Cognito User Pool via amazon-cognito-identity-js and the unauthenticated IdentityId changes to the authenticated IdentityId associated with their Cognito Login. The unauthenticated IdentityId is automatically marked DISABLED and is linked internally to the authenticated IdentityId.
let authenticatedIdentityId;
const { CognitoUserPool, CognitoUser, AuthenticationDetails } = require('amazon-cognito-identity-js');
const Pool = new CognitoUserPool({
UserPoolId,
ClientId,
});
const authDetails = new AuthenticationDetails({
Username,
Password,
});
const user = new CognitoUser({
Pool,
Username,
});
user.authenticateUser(authDetails, {
onSuccess: (session) => {
AWS.config.credentials.params.Logins = {
[PoolProviderName]: session.idToken.jwtToken,
};
AWS.config.credentials.expired = true;
AWS.config.credentials.refresh(err => {
authenticatedIdentityId = AWS.config.credentials.identityId;
});
},
});
I have the value for unathenticatedIdentityId and authenticatedIdentityId but I do not see a way in the AWS Cognito API's to resolve that the DISABLED unauthenticatedIdentityId has been linked to the authenticatedIdentityId. Conversely I do not see a way to identify what IdentityIds have been linked to the authenticatedIdentityId. The describeIdentity API will tell me that unauthenticatedIdentityId is DISABLED and that it has no Logins, but it does not point to the linked authenticatedIdentityId.
How can I, with only the value of the linked/DISABLED unauthenticatedIdentityId, resolve the value authenticatedIdentityId?
I have an app that uses AWS Cognito to obtain an identity id and then possibly authenticate it. The situation is a client uses the app first as unauthenticated (guest) and then logs in using Facebook, making him/herself as authenticated, and AWS preserves the given identity ID for the authenticated user, because he is a new user. Now, the problem comes, when you log out of the app and someone else wants to use this app as unauthenticated or even authenticated. Cognito will error out saying that the access to the identity ID is forbidden, because it has already been linked to the previous user's Facebook account.
The Cognito mobile SDKs have a way built in to handle this. They cache the identity id when using it, which is causing the issue you are seeing. When you log out, you'll want to clear that cache. I'm not sure which SDK you're using, but in iOS it's AWSCognitoIdentityProvider.clear() and CognitoCachingCredentialsProvider.clear() in Android. Similarly, if you're using Cognito Sync, there's a method in that client that will wipe the cached id and sync data.
Also have a look at https://aws.amazon.com/blogs/mobile/understanding-amazon-cognito-authentication/
Hope you are also following https://aws.amazon.com/blogs/mobile/using-the-amazon-cognito-credentials-provider/

Categories

Resources