cancel
Showing results for 
Search instead for 
Did you mean: 
Reply
DerekH_AU
Frequent Visitor

Generic Oauth 2 connector not refreshing access or refresh tokens

Hi all,

 

I am building a custom connector to make a couple of calls into the MYOB AccountRight API (https://developer.myob.com/api/accountright/api-overview/authentication/) and everything works, except that Power Automate doesn't seem to be refreshing the access/refresh token (and it did last time I looked at this a couple of months ago). The access token expires after 20 minutes and the refresh token after 7 days. I manually fix the connection, but within 20 minutes, it no longer connects and requires fixing again. 

 

I have noted as well that the custom connector security screen shows all the values except the Refresh URL, which is empty but mandatory. Even if I update the connection details to include the refresh URL, it doesn't have any impact and the value is cleared after updating the connector.

 

The connection details are:

ID Provider: Generic Oauth 2

Client ID: xnxx6js6mv2krartysp9ddkt

Authorization URL: https://secure.myob.com/oauth2/account/authorize

Token URL: https://secure.myob.com/oauth2/v1/authorize 

Refresh URL should be: https://secure.myob.com/oauth2/v1/authorize

Scope: CompanyFile

Redirect URL: https://global.consent.azure-apim.net/redirect

 

When the custom connector isn't connected, it shows the error below. I am not sure if it is an issue or being returned by the API or somewhere in Power Automate, or if it is a symptom of another issue.

 

 

Failed to refresh access token for service: oauth2. Correlation Id=0fd144f6-e2bd-4b3a-8a7d-c2748a8767c2, UTC TimeStamp=11/4/2020 2:17:43 AM, Error: OAuth 2 access token refresh failed. Client ID and secret sent in form body.. Response status code=InternalServerError. Response body:

 

 

Server Error in '/' Application.


The required anti-forgery cookie "__RequestVerificationToken" is not present.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Web.Mvc.HttpAntiForgeryException: The required anti-forgery cookie "__RequestVerificationToken" is not present.

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.


Stack Trace:

 [HttpAntiForgeryException (0x80004005): The required anti-forgery cookie "__RequestVerificationToken" is not present.] System.Web.Helpers.AntiXsrf.TokenValidator.ValidateTokens(HttpContextBase httpContext, IIdentity identity, AntiForgeryToken sessionToken, AntiForgeryToken fieldToken) +666 System.Web.Helpers.AntiXsrf.AntiForgeryWorker.Validate(HttpContextBase httpContext) +163 System.Web.Mvc.ControllerActionInvoker.InvokeAuthorizationFilters(ControllerContext controllerContext, IList`1 filters, ActionDescriptor actionDescriptor) +156 System.Web.Mvc.Async.<>c__DisplayClass25.<BeginInvokeAction>b__1e(AsyncCallback asyncCallback, Object asyncState) +859 System.Web.Mvc.Async.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +146 System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback, Object state, BeginInvokeDelegate beginDelegate, EndInvokeDelegate`1 endDelegate, Object tag, Int32 timeout) +75 System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback, Object state, BeginInvokeDelegate beginDelegate, EndInvokeDelegate`1 endDelegate, Object tag) +28 System.Web.Mvc.Async.AsyncControllerActionInvoker.BeginInvokeAction(ControllerContext controllerContext, String actionName, AsyncCallback callback, Object state) +1295 System.Web.Mvc.<>c__DisplayClass1d.<BeginExecuteCore>b__17(AsyncCallback asyncCallback, Object asyncState) +50 System.Web.Mvc.Async.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +146 System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback, Object state, BeginInvokeDelegate beginDelegate, EndInvokeDelegate`1 endDelegate, Object tag, Int32 timeout) +75 System.Web.Mvc.Controller.BeginExecuteCore(AsyncCallback callback, Object state) +532 System.Web.Mvc.Async.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +146 System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback, Object state, BeginInvokeDelegate beginDelegate, EndInvokeDelegate`1 endDelegate, Object tag, Int32 timeout) +75 System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback, Object state, BeginInvokeDelegate beginDelegate, EndInvokeDelegate endDelegate, Object tag) +28 System.Web.Mvc.Controller.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state) +387 System.Web.Mvc.<>c__DisplayClass8.<BeginProcessRequest>b__2(AsyncCallback asyncCallback, Object asyncState) +144 System.Web.Mvc.Async.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +146 System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback, Object state, BeginInvokeDelegate beginDelegate, EndInvokeDelegate`1 endDelegate, Object tag, Int32 timeout) +75 System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback, Object state, BeginInvokeDelegate beginDelegate, EndInvokeDelegate endDelegate, Object tag) +28 System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) +320 System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +2066 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +868 

 


Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.36660

1 ACCEPTED SOLUTION

Accepted Solutions
DerekH_AU
Frequent Visitor

The cookie error was being reported by the connector, when making connections without my browser even being open. In any case, for now, I have recreated the connection the connector is using and so far I have had 24 hours of refreshed access tokens, making a request every 15 minutes, when the access token expires after 20 mins. For the moment, recreating the connection seems to have resolved the issue.

View solution in original post

5 REPLIES 5
shyamsu
Power Automate
Power Automate

This appears to be a client/browser side issue. We require cookies to be enabled. Can you please make sure you doing this all in one browser with cookies allowed?

DerekH_AU
Frequent Visitor

The cookie error was being reported by the connector, when making connections without my browser even being open. In any case, for now, I have recreated the connection the connector is using and so far I have had 24 hours of refreshed access tokens, making a request every 15 minutes, when the access token expires after 20 mins. For the moment, recreating the connection seems to have resolved the issue.

HEATFreight
Kudo Kingpin
Kudo Kingpin

I'm having the same issue as @DerekH_AU although I have never been able to get the refresh token to work at all.

I am building the Custom Connector by importing a Postman ver. 2.1 collection. Any tips?

Edit: oh I think I found part of the answer here

Edit2: Ok, yep I've figured it out! I exported a Postman v2.1 collection with all requests using the OAuth2 authorization method. Crucially, I left out the manual refresh token request from the collection. Postman requires you to build a manual request to keep the token refreshed because it will not do that for you even though it has that convenient "Get New Access Token" button: 

HEATFreight_0-1639234343574.png

You must leave out any manual authorization or refresh requests that you might use in Postman. These are not necessary (nor will they even work) in the custom connector. So you export a v2.1 Postman collection of just the non-authentication-related requests that you want to include in your connector. Each of these needs to have a type of "OAuth 2.0" in the Authorization tab. I followed this guide.

You import the Postman collection into the Power Automate custom connector and proceed through the >General and >Security settings. Crucially, you must save the >Security settings before moving on. I never see this mentioned in tutorials, but if you don't do it, the client ID and secret as well as the Refresh URL will not be saved and you'll have to return to finish the >Security tab before you can actually "Update connector".

The interesting thing here is that no matter what you do, the Refresh URl field will wipe itself as if it did not accept your input, but rest assured this is the expected behavior.

Next tab is >Definition. The thing to remember about >Definition is that the conversion between the Swagger Editor and the Custom Connector user interface is broken. YOU CAN NOT TRUST IT TO CONVERT THE SWAGGER CODE PROPERLY! So here is what you do, follow the guide I linked above to edit the code in the Swagger Editor, and then click "Update connector" WHILE YOU STILL HAVE SWAGGER EDITOR TOGGLED ON! I never see any guides mention this part. If you switch back to the regular interface by toggling off the Swagger Editor, there is a chance something will break. You should be safe if you don't open any of the request parameters (like Path, Query, Headers, Body or any of their sub-fields), and clicking "Update connector" toggles off the Swagger Editor anyway, but definitely if you start opening any of those request parameter fields it will start breaking your Swagger code! I do think you can toggle off Swagger Editor before clicking "Update connector" and it will still work. It's mainly just opening the request parameters that begins to break the Swagger code.

One example is if you try using integers as default values for string types. The normal Custom Connector interface will error out if you give a string parameter an integer for a default value (say if your API requires a company ID # parameter). If you get this "integer as string" error, you can simply open the Swagger Editor and put single quotes around the affected default value integers. If you click "Update connector" while Swagger Editor is still toggled on, or at least without navigating back to the string parameter in question, the single quotes will remain intact and your default value will populate in the >Test tab and wherever you use the connector, like Power Automate. But the second you open the string parameter in the normal Custom Connector interface (i.e. Swagger Editor toggled off), **BAM** no more single quotes. After opening the string parameter which has an integer default value, toggle Swagger Editor back on again and you will see that the single quotes have disappeared from around the default value integer.

Off the top of my head, I'm not sure what other parts of the Swagger code breaks when you try editing the Custom Connector parmeters outside of the Swagger Editor, but suffice it to say something ain't right. Stick to the Swagger Editor and you should be fine.

I'm at T+1 day of QuickBooks Online API Custom Connector keeping itself refreshed. The OAuth2 authorization code flow and refresh tokens work great in Custom Connectors if you do it right. 

HEATFreight
Kudo Kingpin
Kudo Kingpin

Ah crap, I'm back again. I got the QuickBooks Online API apparently working perfectly in a custom connector, but I have another API that is returning the following error:

 

Failed to refresh access token for service: oauth2. Correlation Id=..., UTC TimeStamp=..., Error: OAuth 2 access token refresh failed. Client ID and secret sent in form body.. Response status code=BadRequest. Response body: {"error":"invalid_grant"}

 


It seems that something is happening with the refresh token request that is causing it to fail, but that happens in the background. We have no visibility into that request or the response, the OAuth2 custom connector handles that for you and it just works. Or so it did with the QBO API. This other API is more stubborn and I suspect it has something to do with the way they want their requests formatted. I'm not sure what Postman settings would affect this, but for instance these three settings in Postman's >Authorization tab seem like possible culprits:

 

Add authorization data to [Request URL] vs. [Request Headers]

 

or

 

Authorize using browser [y/n]

 

or

 

Client Authentication [Send client credentials in body] vs. [Send as Basic Auth header]

 

 

I am using the exact settings in the broken custom connector as what I used for the working QuickBooks Online custom connector, except with the base URL, auth URL, token URL, refresh URL, request URLs, client ID, and client secret all being unique to each API obviously. Other than those, everything else is exactly the same. API #2 works great for 20 minutes and then its access token expires and I get that error above^.

Any Power Platform wizards out there? @RezaDorrani @shyamsu @v-bacao-msft 

Did you ever resolved this? I am trying to connect an external api and i get the same issues. I have try to create it manually and by importing the json files. When i go and try to connect to it. i get the error

{"error":"invalid_request","error_description":"Invalid redirect_uri: https://global.consent.azure-apim.net/redirect","rfc6749_reference":"4.1.2.1, 4.2.2.1"}

Helpful resources

Announcements

Calling all User Group Leaders and Super Users! Mark Your Calendars for the next Community Ambassador Call on May 9th!

This month's Community Ambassador call is on May 9th at 9a & 3p PDT. Please keep an eye out in your private messages and Teams channels for your invitation. There are lots of exciting updates coming to the Community, and we have some exclusive opportunities to share with you! As always, we'll also review regular updates for User Groups, Super Users, and share general information about what's going on in the Community.     Be sure to register & we hope to see all of you there!

April 2024 Community Newsletter

We're pleased to share the April Community Newsletter, where we highlight the latest news, product releases, upcoming events, and the amazing work of our outstanding Community members.   If you're new to the Community, please make sure to follow the latest News & Announcements and check out the Community on LinkedIn as well! It's the best way to stay up-to-date with all the news from across Microsoft Power Platform and beyond.    COMMUNITY HIGHLIGHTS   Check out the most active community members of the last month! These hardworking members are posting regularly, answering questions, kudos, and providing top solutions in their communities. We are so thankful for each of you--keep up the great work! If you hope to see your name here next month, follow these awesome community members to see what they do!   Power AppsPower AutomateCopilot StudioPower PagesWarrenBelzDeenujialexander2523ragavanrajanLaurensMManishSolankiMattJimisonLucas001AmikcapuanodanilostephenrobertOliverRodriguestimlAndrewJManikandanSFubarmmbr1606VishnuReddy1997theMacResolutionsVishalJhaveriVictorIvanidzejsrandhawahagrua33ikExpiscornovusFGuerrero1PowerAddictgulshankhuranaANBExpiscornovusprathyooSpongYeNived_Nambiardeeksha15795apangelesGochixgrantjenkinsvasu24Mfon   LATEST NEWS   Business Applications Launch Event - On Demand In case you missed the Business Applications Launch Event, you can now catch up on all the announcements and watch the entire event on-demand inside Charles Lamanna's latest cloud blog.   This is your one stop shop for all the latest Copilot features across Power Platform and #Dynamics365, including first-hand looks at how companies such as Lenovo, Sonepar, Ford Motor Company, Omnicom and more are using these new capabilities in transformative ways. Click the image below to watch today!   Power Platform Community Conference 2024 is here! It's time to look forward to the next installment of the Power Platform Community Conference, which takes place this year on 18-20th September 2024 at the MGM Grand in Las Vegas!   Come and be inspired by Microsoft senior thought leaders and the engineers behind the #PowerPlatform, with Charles Lamanna, Sangya Singh, Ryan Cunningham, Kim Manis, Nirav Shah, Omar Aftab and Leon Welicki already confirmed to speak. You'll also be able to learn from industry experts and Microsoft MVPs who are dedicated to bridging the gap between humanity and technology. These include the likes of Lisa Crosbie, Victor Dantas, Kristine Kolodziejski, David Yack, Daniel Christian, Miguel Félix, and Mats Necker, with many more to be announced over the coming weeks.   Click here to watch our brand-new sizzle reel for #PPCC24 or click the image below to find out more about registration. See you in Vegas!       Power Up Program Announces New Video-Based Learning Hear from Principal Program Manager, Dimpi Gandhi, to discover the latest enhancements to the Microsoft #PowerUpProgram. These include a new accelerated video-based curriculum crafted with the expertise of Microsoft MVPs, Rory Neary and Charlie Phipps-Bennett. If you’d like to hear what’s coming next, click the image below to find out more!   UPCOMING EVENTS Microsoft Build - Seattle and Online - 21-23rd May 2024 Taking place on 21-23rd May 2024 both online and in Seattle, this is the perfect event to learn more about low code development, creating copilots, cloud platforms, and so much more to help you unleash the power of AI.   There's a serious wealth of talent speaking across the three days, including the likes of Satya Nadella, Amanda K. Silver, Scott Guthrie, Sarah Bird, Charles Lamanna, Miti J., Kevin Scott, Asha Sharma, Rajesh Jha, Arun Ulag, Clay Wesener, and many more.   And don't worry if you can't make it to Seattle, the event will be online and totally free to join. Click the image below to register for #MSBuild today!   European Collab Summit - Germany - 14-16th May 2024 The clock is counting down to the amazing European Collaboration Summit, which takes place in Germany May 14-16, 2024. #CollabSummit2024 is designed to provide cutting-edge insights and best practices into Power Platform, Microsoft 365, Teams, Viva, and so much more. There's a whole host of experts speakers across the three-day event, including the likes of Vesa Juvonen, Laurie Pottmeyer, Dan Holme, Mark Kashman, Dona Sarkar, Gavin Barron, Emily Mancini, Martina Grom, Ahmad Najjar, Liz Sundet, Nikki Chapple, Sara Fennah, Seb Matthews, Tobias Martin, Zoe Wilson, Fabian Williams, and many more.   Click the image below to find out more about #ECS2024 and register today!     Microsoft 365 & Power Platform Conference - Seattle - 3-7th June If you're looking to turbo boost your Power Platform skills this year, why not take a look at everything TechCon365 has to offer at the Seattle Convention Center on June 3-7, 2024.   This amazing 3-day conference (with 2 optional days of workshops) offers over 130 sessions across multiple tracks, alongside 25 workshops presented by Power Platform, Microsoft 365, Microsoft Teams, Viva, Azure, Copilot and AI experts. There's a great array of speakers, including the likes of Nirav Shah, Naomi Moneypenny, Jason Himmelstein, Heather Cook, Karuana Gatimu, Mark Kashman, Michelle Gilbert, Taiki Y., Kristi K., Nate Chamberlain, Julie Koesmarno, Daniel Glenn, Sarah Haase, Marc Windle, Amit Vasu, Joanne C Klein, Agnes Molnar, and many more.   Click the image below for more #Techcon365 intel and register today!     For more events, click the image below to visit the Microsoft Community Days website.      

Tuesday Tip | Update Your Community Profile Today!

It's time for another TUESDAY TIPS, your weekly connection with the most insightful tips and tricks that empower both newcomers and veterans in the Power Platform Community! Every Tuesday, we bring you a curated selection of the finest advice, distilled from the resources and tools in the Community. Whether you’re a seasoned member or just getting started, Tuesday Tips are the perfect compass guiding you across the dynamic landscape of the Power Platform Community.   We're excited to announce that updating your community profile has never been easier! Keeping your profile up to date is essential for staying connected and engaged with the community.   Check out the following Support Articles with these topics: Accessing Your Community ProfileRetrieving Your Profile URLUpdating Your Community Profile Time ZoneChanging Your Community Profile Picture (Avatar)Setting Your Date Display Preferences Click on your community link for more information: Power Apps, Power Automate, Power Pages, Copilot Studio   Thank you for being an active part of our community. Your contributions make a difference! Best Regards, The Community Management Team

Hear what's next for the Power Up Program

Hear from Principal Program Manager, Dimpi Gandhi, to discover the latest enhancements to the Microsoft #PowerUpProgram, including a new accelerated video-based curriculum crafted with the expertise of Microsoft MVPs, Rory Neary and Charlie Phipps-Bennett. If you’d like to hear what’s coming next, click the link below to sign up today! https://aka.ms/PowerUp  

Super User of the Month | Ahmed Salih

We're thrilled to announce that Ahmed Salih is our Super User of the Month for April 2024. Ahmed has been one of our most active Super Users this year--in fact, he kicked off the year in our Community with this great video reminder of why being a Super User has been so important to him!   Ahmed is the Senior Power Platform Architect at Saint Jude's Children's Research Hospital in Memphis. He's been a Super User for two seasons and is also a Microsoft MVP! He's celebrating his 3rd year being active in the Community--and he's received more than 500 kudos while authoring nearly 300 solutions. Ahmed's contributions to the Super User in Training program has been invaluable, with his most recent session with SUIT highlighting an incredible amount of best practices and tips that have helped him achieve his success.   Ahmed's infectious enthusiasm and boundless energy are a key reason why so many Community members appreciate how he brings his personality--and expertise--to every interaction. With all the solutions he provides, his willingness to help the Community learn more about Power Platform, and his sheer joy in life, we are pleased to celebrate Ahmed and all his contributions! You can find him in the Community and on LinkedIn. Congratulations, Ahmed--thank you for being a SUPER user!

Tuesday Tip: Getting Started with Private Messages & Macros

Welcome to TUESDAY TIPS, your weekly connection with the most insightful tips and tricks that empower both newcomers and veterans in the Power Platform Community! Every Tuesday, we bring you a curated selection of the finest advice, distilled from the resources and tools in the Community. Whether you’re a seasoned member or just getting started, Tuesday Tips are the perfect compass guiding you across the dynamic landscape of the Power Platform Community.   As our community family expands each week, we revisit our essential tools, tips, and tricks to ensure you’re well-versed in the community’s pulse. Keep an eye on the News & Announcements for your weekly Tuesday Tips—you never know what you may learn!   This Week's Tip: Private Messaging & Macros in Power Apps Community   Do you want to enhance your communication in the Community and streamline your interactions? One of the best ways to do this is to ensure you are using Private Messaging--and the ever-handy macros that are available to you as a Community member!   Our Knowledge Base article about private messaging and macros is the best place to find out more. Check it out today and discover some key tips and tricks when it comes to messages and macros:   Private Messaging: Learn how to enable private messages in your community profile and ensure you’re connected with other community membersMacros Explained: Discover the convenience of macros—prewritten text snippets that save time when posting in forums or sending private messagesCreating Macros: Follow simple steps to create your own macros for efficient communication within the Power Apps CommunityUsage Guide: Understand how to apply macros in posts and private messages, enhancing your interaction with the Community For detailed instructions and more information, visit the full page in your community today:Power Apps: Enabling Private Messaging & How to Use Macros (Power Apps)Power Automate: Enabling Private Messaging & How to Use Macros (Power Automate)  Copilot Studio: Enabling Private Messaging &How to Use Macros (Copilot Studio) Power Pages: Enabling Private Messaging & How to Use Macros (Power Pages)

Users online (6,303)