nino
nino

Reputation: 861

OAuth2 Access token in console application

I am trying to build a C# dotnetcore console application to interact with an api that uses OAuth2 for authorization. I haven't quite figured out how I can use this for a C# console application or even a library that does not intend to have a user signing in. Is this even possible?

What i got so far is the following:

    private static string _auth_url = "https://idp.bexio.com/authorize";
    private static string _token_url = "https://idp.bexio.com/token";
    private static string _callback_url = "https://www.myurl.com";

    private static string _scope = "monitoring_show";
    private static string _client_id = "myid";
    private static string _client_secret = "mysecret";
    static void Main(string[] args)
    {
        //request token
        var restclient = new RestClient(_auth_url);
        RestRequest request = new RestRequest("request/oauth") {Method = Method.POST};
        request.AddHeader("Accept", "application/json");
        request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
        request.AddParameter("client_id", _client_id);
        request.AddParameter("client_secret", _client_secret);
        request.AddParameter("grant_type", "client_credentials");
        var tResponse = restclient.Execute(request);
        var responseJson = tResponse.Content;
    }  

I can't figure out how I can get the authorize token though and give all the information that I need. Can someone show me what I am missing?

https://docs.bexio.com/#section/Authentication/Authorization-Code-Flow

Upvotes: 6

Views: 9956

Answers (1)

MvdD
MvdD

Reputation: 23436

You are trying to use the client credentials flow, which makes sense for a console application without a user authenticating.

However, it looks like Bexio only supports the authorization code flow. This depends on browser redirection to authenticate the user and return an authorization code. Then in the subsequent token call, you pass in client_id=<your client id>, grant_type=authorization_code and code=<your code>.

The only way to work around this is to build a web application that acts as an OAuth2 client for the authorize part, displays the returned authorization code instead of exchanging it for a token. Have the user copy/paste that code as an input parameter to the console application, which then uses the client credentials in the token call.

Or you'd need to build the authorize part of the authorization code flow into the console application at HTTP level. But this is very fragile, since any change on the authorization server side will likely break the console application.

Upvotes: 3

Related Questions