AadTokenProvider returns access token from old user - javascript

We are developing Microsoft Sharepoint "Widgets" using javascript(React) and aadTokenProviderFactory to acquire tokens.
import { WebPartContext } from "#microsoft/sp-webpart-base";
const getMSToken = async (context: WebPartContext) => {
const provider = await context.aadTokenProviderFactory.getTokenProvider();
const token = await provider.getToken('https://graph.microsoft.com');
return token;
}
This token is valid and everything works fine. But when switching users I receive a token from the old user.
How to solve this issue and acquire tokens for the user that is currently signed in?

Issue solved.
getToken method has 2nd parameter called useCachedToken: boolean.
const token = await provider.getToken('https://graph.microsoft.com', false);

Related

Using Bearer auth Token to get logged in user Information - ReactJS

When a user logs in, or registers an account, an auth token is stored on the local storage. Now I want to use this token to get the logged in user information to display on my app for example the username and phone number.
I can get the user information using the token on my Postman. But now how do I display it on the reactjs app?
Here is the Api
public function me(Request $request){
return $request->user();
}
For example if you want to display the user on the first render of the page:
const [user, setUser] = useState()
useEffect(() => {
const fetchUser = async (url) => {
const response = await fetch(url)
const resData = await response.json()
setUser(resData.user)
}
fetchUser(YOUR_URL)
},[])
And then use the JSX syntax inside the React component to display the user.

Firebase Auth Refresh Token?

How do I get access to the refreshed token in Firebase Auth?
I'm building a React app, and on the signin button click run Login function. This function gives me a Google API token which I use to access google drive api.
The problem is that is token expires after an hour. This post mentions:
"If you need to know when the SDK refreshes the token in order to get a new one immediately, you should instead use onIdTokenChanged to set up a callback that will be invoked every time the user's token changes."
As such I've gone ahead and set this function up. However, how do I access this new updated token so that I can pass it along to the rest of the app?
Login Function
const login = async () => {
signInWithPopup(auth, provider)
.then((result) => {
// This gives you a Google Access Token. You can use it to access the Google API.
const credential = GoogleAuthProvider.credentialFromResult(result);
const token = credential.accessToken;
}
onIdTokenChanged
onIdTokenChanged(auth, (currentUser) => {
console.log(currentUser);
setUser(currentUser);
});

Most ideal way to call firebase getIdToken

i am implementing user authentication with the help of firebase in my React project. So, I am confused over something.
I am verifying the user from firebase and then getting a token on frontend which is sent to backend via headers and verfied there once.
I read the docs and came to know that firebase token gets expired after 1 hr by default so we have to use "getIdToken" like
firebase.auth().onAuthStateChanged(async user => {
if (user) {
console.log(user, 'user123 inside firebaseAuth')
const token = await user.getIdToken()
Cookies.set('my_token', token, { domain: domain })
}
})
but how do i manage this function , do i have to call it everytime the component updates or everytime before hitting api or first time the component renders ?
The thing is i do not want this token to get expire until the user logs out himself / herself even if he is in a different component and sitting ideal for too long.
You can get the Firebase ID Token every time you are making an API call to your server:
async function callAPI() {
const user = firebase.auth().currentUser
if (user) {
const token = await user.getIdToken()
const res = await fetch("url", {
headers: {authorization: `Bearer ${token}`}
})
} else {
console.log("No user is logged in")
}
}
You could get the ID token once when the component mounts but then you'll have to deal with onIdTokenChanged to keep it updated in your state. Using the method above you'll get a valid token always.

In Next.js getServerSideProps, how can I fetch cookie from browser to identify the user

I am developing an e-commerce site. A user has selected the items. To view his cart and checkout he clicks on the cart icon in NavBar which navigates him to myCart.js page. I am using getServerSideProps to get JWT from the browser, decode it and verify the user. Code is as below:
let jwtoken;
export async function getServerSideProps(req, res) {
if (
req.headers.authorization &&
req.headers.authorization.startsWith('Bearer')
) {
jwtoken = req.headers.authorization.split(' ')[1];
} else if (req.cookies.jwt) {
jwtoken = req.cookies.jwt;
}
if (!jwtoken) {
return res.status(423).redirect('/emptyCart');
const decoded = await promisify(jwt.verify)(jwtoken, process.env.JWT_SECRET);
currentUser = await User.findById(decoded.id);
if (!currentUser)
return res.status(401).redirect('/signup');
Note: cookie is httpOnly.
I get a runtime error: 'headers not defined'
Now if I remove the code containing req.headers and use only eq.cookies.jwt > gives me another error cookies not defined.
I worked on this issue for four days and tried so many solutions offered in Stackoverflow and also from other developer portals like flavio, reddit and others.
The getServerSideProps function expects a single context parameter, which contains the req/res objects you're trying to access.
Change your getServerSideProps function to have the following signature:
export async function getServerSideProps({ req, res }) {
console.log(req.cookies); // Logs all cookies from the request
}

Can someone ELI5 how to properly do offline Google oauth2 with node.js?

In the browser, I'm doing:
let { code } = await this.auth2.grantOfflineAccess();
I then save that code in my DB.
Then on the server (node.js), I'm doing:
const { tokens } = await oauth2Client.getToken(code)
oauth2Client.setCredentials(tokens)
let { data } = await googleCalendar.calendarList.list({
auth: oauth2Client
})
The first time, tokens has a refresh_token. I save that as well. When I run this once, it works fine. When I run it again, it says the token is invalid. Somehow, I have to use the refresh_token, to get a new token, but I don't know how. Can someone please explain like I'm 5?
Thanks
You have already had the refresh token.
You want to use the API with the access token refreshed by the refresh token.
You want to achieve this using googleapis with Node.js.
If my understanding is correct, how about this answer? I think that the reason of your issue is that the authorization code can be used only one time. So it is required to retrieve the access token using the refresh token. In this answer, the access token is retrieved by the refresh token.
Modified script:
const refreshToken = "###"; // Please set your refresh token.
if (!refreshToken) { // Please modify this if statement for your situation.
const { tokens } = await oauth2Client.getToken(code);
oauth2Client.setCredentials(tokens);
} else {
oauth2Client.credentials = { refresh_token: refreshToken };
}
let { data } = await googleCalendar.calendarList.list({
auth: oauth2Client
});
Note:
This modified script supposes that oauth2Client and googleCalendar are declared.
When the refresh token is used, the authorization code is not required.
Reference:
googleapis
If I misunderstood your question and this was not the result you want, I apologize.

Categories

Resources