I am studying the client-oauth2 npm package. The code sample from the link in the preceding sentence includes the word user. What does user refer to? Is user a built in type? Or does the developer need to create their own user model class? If so, please give a good example of how to create and integrate a user model class. Any links to documentation about user or code samples for user for this package would also be greatly appreciated.
Here is a code snipped from the link above which includes the word user:
app.get('/auth/github/callback', function (req, res) {
githubAuth.code.getToken(req.url)
.then(function (user) {
console.log(user) //=> { accessToken: '...', tokenType: 'bearer', ... }
// Refresh the current users access token.
user.refresh().then(function (updatedUser) {
console.log(updatedUser === user) //=> true
})
// Sign API requests on behalf of the current user.
user.sign({
method: 'get',
url: 'http://example.com'
})
// We should store the token into a database.
return res.send(user.accessToken)
})
}
The following methods and properties seem to be required of a user object:
user.refresh()
user.sign({method: 'get',
url: 'http://example.com'})
user.accessToken
It seems obvious that user.accessToken stores the user's OAuth2 access token in memory. But what specifically do the refresh() and sign(...) methods do? And what code should be used to implement them, if they are not built-in types?
Related
I am building a back-office app that requires users to sign in.
I have 2 external APIs:
API A : to manage user accounts and sessions
API B : to perform CRUD actions on another database (unrelated to users database)
The problem is that I don't want users to be able to perform calls to API B if their session is not valid. So I added some API endpoints in Next (under pages/api) that do the following actions:
verifying the validity of the session against API A
if session is valid: continue to step 3, if not: redirect to page /login
make the call to API B
Everything works fine if the session is valid but it fails if the session is not valid.
I have tried
res.redirect(307, '/login').end()
and
res.writeHead(307, { Location: '/login' }).end()
but it didn't work. It fails even by specifying the whole path (http://localhost:3000/login). What I don't understand is that I am successfully redirected to my /login page if I make the request directly from the browser (GET http://localhost:3000/api/data). It doesn't work when I make the request with Axios inside a React component.
Any idea how I can fix this?
As #juliomalves and #yqlim explained, I had to make the redirect manually based on the response of the API.
Faced same problem solve using below code:
Api
res.status(200).json({ success: "success" }) //add at last of the api to give response
page
import Router from 'next/router'
let res = await fetch('api', {
method: 'POST', // or 'PUT'
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
})
if (res.status == 200) {
Router.push('/location')
}
Answer is correct as #Jules Grenier sayes,but provided an example
You do not need .end(). Have you tried res.redirect(307, '/login')?
In Next.js v12 and v13, the following works for me.
// /api/example.js
const handler = async function (req, res) {
// custom logic
if (failed)
return res.redirect(307, '/login')
}
export default handler;
The API request must be initiated by a <form>.
redirect will not work with <fetch>
I'm trying to build a bot that sends proactive user recommendations regularly. They look similar to this one:
I have it all working in terms of user data coming from the backend, but I also want to add some additional things coming from the Graph API - one of which is the profile picture.
I've setup an Azure Bot Channel, got the Graph auth sample running, but I still can't figure how to mix the proactive messages with the OAuthPrompt dialog.
If I make the user sign in upon app registration, can I reliably get the graph token and use it in my proactive message handler? Note that these messages are going to be sent on a weekly basis. I'm afraid that the token is going to expire.
Has anyone done something similar?
If you just need the bot to make a call to Graph and retrieve user data, you can use Application Permissions to do this without having the user log in. First, you will need to enable the permissions in Azure Active Directory>App registrations>API permissions. The particular ones you need here is User.Read.All (or User.ReadWrite.All if you might want it to have write access for other use cases). There are also separate permissions for Group and Contact if you need that.
For the bot, you first need to get the token. There's a whole reference article here (which includes the app permissions as described above). The client ID and secret are the values for your application. So in javascript I do something like
var identityUrl = `https://login.microsoftonline.com/${tenantId}/oauth2/v2.0/token`;
var formData = `client_id=${clientId}&scope=https%3A%2F%2Fgraph.microsoft.com%2F.default&client_secret=${clientSecret}&grant_type=client_credentials`
try {
var idResponse = await request({
url: identityUrl,
method: 'POST',
headers: {'Content-Type': 'application/x-www-urlencoded;charset=UTF-8'},
form: formData
});
var token = JSON.parse(idResponse).access_token;
} catch (err) {
await step.context.sendActivity(`Sorry, something went wrong. Please try again later.`);
console.log(err.message);
return step.endDialog();
}
I've got a lot going on where I'm making an actual call to graph, but my http call looks like this:
var userResponse = await request({
url: usersUrl + queryString,
method: 'GET',
headers: {'Authorization':`Bearer ${token}`, 'ConsistencyLevel':'eventual'}
});
userResponse = JSON.parse(userResponse);
Now in your case you're calling the Get Photo endpoint, which I haven't done, but should be basically the same as the above. Here is a link for the Get photo documentation. So now, you bot should be able to authenticate and grab the picture before sending the proactive message, without any need for the user to ever give any credentials.
I’m trying to create a function to get a login token from Auth0 for a user for so I don’t have to use the login test before every test scenario (which isn’t working anyway), but rather I want to have a stored token and use that to authenticate the user so I can test the application.
I’m not a developer (or even a developer in Test). I’m a QA who is trying to learn enough Javascript in order to use Cypress to create test scenarios for our new internal risk assessment application.
We have a list of users for our new app which will all be verified through Auth0. All the users are internal to our company and are based on our emails which are linked to Microsoft accounts.
Below is my login test that presses the login button, which is then redirected to Auth0 and then enters my email address to verify the login. This is successful except for the fact that it doesn’t actually load the application.
```
describe('My Login Test', function (){
it('Visit Risk App Landing Page', function (){
const typedText = 'adam.allford#landmark.co.uk'
cy.visit('https://bvt-riskassessment.lmkcloud.net')
cy.get('button').click()
cy.get('input.auth0-lock-input').first()
.type(typedText)
.should('have.value', typedText)
cy.get('button').click()
cy.url().should('eq','http://bvt-riskassessment.lmkcloud.net/workflow')
})
})
```
I had a reply on a Gitter forum from someone who had a similar issue and used what is displayed below (or similar) to try and login. I edited it with relevant details for what I need and put this in the command.js with a loginuser.json (containing username and password) in the shown loacation, and then included the beforeEach in a test scenario.
```
Cypress.Commands.add('login', (userType, options = {}) =>
{cy.readFile(`cypress/fixtures/loginUser.json`).then((json) => {
const { email, password } = json
const dataToSend = {
email,
password,
}
cy.request({
url: `https://lmcorp.eu.auth0.com/userinfo`,
method: 'POST',
body: dataToSend,
form: true
}).then((response) => {
const { status, body } = response
expect(status).to.eq(200)
expect(body).to.have.property('success', 1)
cy.visit(url)
})
})
//and use it like :
beforeEach(() => { login('url') })
```
… and then included the beforeEach in a test scenario.
```
describe('My First Test', function (){
it('Visit Risk App Landing Page', function (){
beforeEach(() => { login('https://lmcorp.eu.auth0.com/')})
cy.visit('http://localhost:3000/workflow')
cy.contains('Site Solutions Combined Assessments')
cy.contains('To Do')
cy.contains('Assessing')
cy.contains('Reviewing')
cy.contains('Done')
cy.get('button').click()
cy.contains('Assessments')
cy.contains('Site Solutions Combined')
cy.contains('Flood')
cy.contains('Whatever Next')
})
})
```
But I get the following message on the command console.
![alt]https://i.imgur.com/cJljZzm.png
I’m completely stuck and don’t know where to go from here. My question is: I want to create a feature that will call our Auth0 url and get a login authentication token, which can be used to allow access the application for every test scenario. Can I change what I have here to make that work, or does anyone have any suggestions on how to create a new feature to get an Auth0 token?
I am using Skype Web SDK to get a user's contact list in the following manner.
Skype.initialize({
apiKey: 'a42fcebd-5b43-4b89-a065-74450fb91255',
}, function (api) {
var Application = api.application;
var client = new Application();
client.signInManager.signIn({
username: sip,
password: pwd
})
This works fine when I provide the username(sip) and password. However, when I reload the page, I have to provide the credentials again because the app re-initializes. Is there a way to maintain the user's sessions for a while after the initial login so that the page refreshes wouldn't need ask for credentials again?
I have looked through the samples and docuementation that Microsoft has and couldn't find a way. I've also tried to store the client object in the localStorage after the initialization and sign in, but when I tried to reuse the object from localStorage to get the contact list, it did not work.
http://officedev.github.io/skype-docs/Skype/WebSDK/model/api/interfaces/jcafe.signinmanager.html#signin last example explains that you can store oauth token and use it as unexpired token.
To connect to an existing app's event channel, specify id of that app:
sm.signIn({
username: "user1#company.com",
password: "password1",
id: "273867-234235-45346345634-345"
});
To sign in to Skype for Business Online using OAuth while handling the
logic of retrieving OAuth tokens yourself:
sm.signIn({
client_id: '123-456',
origins: [ 'https://webdir.online.lync.com/AutoDiscover/AutoDiscoverservice.svc/root' ],
cors: true,
get_oauth_token: function(resource) {
// Return a valid unexpired token for the specified resource if you already have one.
// Else, return a promise and resolve it once you have obtained a token.
return 'Bearer eyJ0e...';
}
});
I need to use a refresh_token (which I have stored) to obtain a new id_token from Auth0.
In version 9 of Auth0 Lock, there was a method to do this (as documented here):
lock.getClient().refreshToken(refresh_token, function (err, delegationResult) {
// Get here the new JWT via delegationResult.id_token
});
In Lock 10, getClient() no longer exists, and this page suggests that you can instantiate your own instance of auth0.js. How do I do this?
I tried this:
return new auth0.WebAuth({
domain: '...',
clientID: '...'
});
but this object doesn't seem to have any useful methods on it. Again the old Auth0.js v7 library looks clear:
auth0.refreshToken(refresh_token, function (err, delegationResult) {
// Get here the new delegationResult.id_token
});
How can this be achieved with auth0.js v8?
As pointed out, renewAuth seems to be the new way to do this. However, it's also possible to make a manual HTTP call to the Auth0 api in order to get a new id token using a refresh token:
POST {yourAuth0Domain}/delegation
{
client_id: "...",
grant_type: "urn:ietf:params:oauth:grant-type:jwt-bearer",
refresh_token: "...",
scope: "openid app_metadata"
}
According to the available documentation the way to obtain a new token using Auth0.js v8 is to use the renewAuth method.
The renewAuth method allows you to acquire a new token from Auth0 for a user who is already authenticated against the hosted login page.