I have seen people use auth. providers that has client secret and id of connected app and authenticated using named credentials. The named credentials stores the oauth refresh token but I am not getting why this flow is needed or what do we gain here.
All suggestions appreciated.
Best Answer
From the Named Credentials documentation, an important summary:
Named Credentials insulate your code from specific endpoint URLs and from authentication details, and also provide secure storage for secret authentication parameters. The latter is a capability that is otherwise only possible by using a Protected Custom Setting in a managed package, which not every org has the capacity or inclination to do. Otherwise, you're stuck with storing highly sensitive authentication parameters, such as OAuth refresh tokens, in locations where anyone with View Setup and Configuration permission can get at them. Named Credentials makes that security problem go away.
Put shortly, they abstract away a lot of complex, difficult, and risky (from a security standpoint) implementation details so that your code doesn't have to handle them, and they improve the maintainability and security of your outbound connections.