[SalesForce] How to issue/send access token from apex page to connected app

We have implemented 2 OAuth flows between our app and SF where SF is auth provider – Web Server and Username and Password

Now we have use case where user is signed on SF and has to invoke our ASMX API.
Is it possible to write in SF APEX page – generate for me access token for current session and environment and to send that automatically (in message header) when I call our API ? If not what is the best approach, I would like still to keep SF as Oauth provider, do not want to provide/issue access tokens from my side in this communication.

Best Answer

Sometime back, I was trying to connect 2 saleforce org via Oauth/Rest API. I think I did something similar. On Salesforce org(Source) act as auth provider. I created connected app in Target org to finally get the Oauth Token. providing small code base for that:

String reqbody = 'grant_type=password&client_id='+clientId+'&client_secret='+clientSecret+'&username='+username+'&password='+password;
// All of these u'll get once you set up connected app

    Http h = new Http();
    HttpRequest req = new HttpRequest();
    req.setBody(reqbody);
    req.setMethod('POST');
    req.setEndpoint('https://login.salesforce.com/services/oauth2/token');//Note if my domain is set up use the proper domain name else use login.salesforce.com for prod or developer or test.salesforce.com for sandbox instance

    HttpResponse res = h.send(req);
    OAuth2 objAuthenticationInfo = (OAuth2)JSON.deserialize(res.getbody(), OAuth2.class);
    //RequestWrapper reqst=new RequestWrapper();

    if(objAuthenticationInfo.access_token!=null) // your check for access token

    { for any further Rest API call, I was using this, which I think you needed: 
      **req1.setHeader('Authorization','Bearer '+objAuthenticationInfo.access_token);** 
      --------your further code------ }

Let me know in case you've any doubt over this :