I trying to Automate the User Level Token Creation/Generation process (REST/Authorization Grant Code) using Apache OAuth Client 2.0 Library in Java. And below is the Code that a
OAuthAuthzResponse oar = OAuthAuthzResponse.oauthCodeAuthzResponse(request);
String code = oar.getCode();
I think that the above code should be written in the implementation of the redirect URI endpoint, not in the client code.
It would be of help to understand the Authorization Code Flow correctly. An authorization code is issued from the authorization endpoint of the authorization server and it is delivered to the location which is pointed to by the redirect URI. That is, the authorization code is NOT delivered to the client application directly.
When an authorization server issues an authorization code, it sends an HTTP response like below back to the client's web browser.
HTTP/1.1 302 Found
Location: {Redirect URI}
?code={Authorization Code} // - Always included
&state={Arbitrary String} // - Included if the authorization
// request included 'state'.
302 Found
triggers the web browser to go to the location pointed to by the Location
header. Therefore, you have to implement the location to receive the authorization code, and the implementation has to pass the authorization code to the client application in some way or other.
Also note that an authorization page (HTML) is displayed between (a) an authorization request (= a request to the authorization endpoint) and (b) a token request (= a request to the token endpoint) and the page requires end-user interaction. See "1. Authorization Code Flow" in "Diagrams And Movies Of All The OAuth 2.0 Flows" for details.