2

I want to programmatically get access token for the current user after logging in. I've figured out how to get a token using client credentials but I couldn't figure out how to get one on behalf of the user.

Here's what I tried to get using client credentials:

var client = new TokenClient("http://localhost:34240/connect/token", "client", "secret", AuthenticationStyle.PostValues);
var token = client.RequestClientCredentialsAsync(scope: "api").GetAwaiter().GetResult();

Do I need to use acr_values to add subject value to the request? If yes, how do I add it to the returned access token?

Or do I need to use code grant type instead? If yes, how do I request an authorization code programmatically?

Or is there another way that I'm missing?

I'd appreciate any help. I've checked IdentityServer samples but couldn't see anything about this.

dstr
  • 8,362
  • 12
  • 66
  • 106
  • How is the user logging in? Through IdentityServer? I would suspect then that you have the idToken. With this token you can request access tokens as if from this user. – Schwarzie2478 Jun 06 '18 at 22:34
  • Perhaps refreshtokens is what you are looking for? http://docs.identityserver.io/en/release/topics/refresh_tokens.html – Schwarzie2478 Jun 06 '18 at 22:34
  • 1
    Logging in from Desktop application: https://github.com/IdentityModel/IdentityModel.OidcClient2 – Schwarzie2478 Jun 06 '18 at 22:36

1 Answers1

1

Have a look at the Resource owner password grant examples. Basically you are doing almost the same, like you are currently doing, but instead of client credentials grant, you need to setup your client to use ResourceOwnerPassword, and then the code that you've shown, changes to:

var client = new TokenClient("http://localhost:34240/connect/token", "client", "secret", AuthenticationStyle.PostValues);

var token = client.RequestResourceOwnerPasswordAsync("<username>", "<password>", scope: "api").GetAwaiter().GetResult();

By this you are getting a token on behalf of the user. But have in mind:

The spec recommends using the resource owner password grant only for “trusted” (or legacy) applications. Generally speaking you are typically far better off using one of the interactive OpenID Connect flows when you want to authenticate a user and request access tokens.

m3n7alsnak3
  • 3,026
  • 1
  • 15
  • 24
  • Thank you. I'm aware of the resource owner password flow but at the time of needing the token the user will be already logged in so I rather not authenticate again. I'm looking for a solution where I can get a token with user id/username info. – dstr May 30 '18 at 07:16