IdentityServer4 icon indicating copy to clipboard operation
IdentityServer4 copied to clipboard

Need sample on how to implement simple Extension Grant flow

Open monubamb opened this issue 7 years ago • 10 comments

Need sample on how to implement simple Extension Grant flow.

I could not find any good sample. When i used the one shown on here it does not work http://docs.identityserver.io/en/latest/topics/extension_grants.html

When i included the DelegationGrantValidator in my code, even the working api are now throwing 401 error.

Any help is much appreciated.

monubamb avatar Sep 25 '19 15:09 monubamb

it does not work

is not enough information. The sample does work for me.

leastprivilege avatar Sep 25 '19 15:09 leastprivilege

Thanks @leastprivilege . What i meant was i tried to follow the steps in the doc - http://docs.identityserver.io/en/latest/topics/extension_grants.html step by step.. I could not get it to work. I could not find any code sample for it on github. The link here is not valid anymore http://docs.identityserver.io/en/dev/topics/extension_grants.html

Here is what i did. I used the Quickstart sample for HybridFlowAuthenticationwithApiAccess and that worked fantastic.

Next thing i added one more API into the solution to use for the extension grant. Configured it with the IdentityServer properly with the right scope (api2).

Created a new class in the Identity Server with DelegationGrantValidator:IExtensionGrantValidator private readonly ITokenValidator _validator;

    public DelegationGrantValidator(ITokenValidator validator)
    {
        _validator = validator;
    }

    public string GrantType => "delegation";

    public async Task ValidateAsync(ExtensionGrantValidationContext context)
    {
        var userToken = context.Request.Raw.Get("token");

        if (string.IsNullOrEmpty(userToken))
        {
            context.Result = new GrantValidationResult(TokenRequestErrors.InvalidGrant);
            return;
        }

        var result = await _validator.ValidateAccessTokenAsync(userToken);
        if (result.IsError)
        {
            context.Result = new GrantValidationResult(TokenRequestErrors.InvalidGrant);
            return;
        }

        // get user's identity
        var sub = result.Claims.FirstOrDefault(c => c.Type == "sub").Value;

        context.Result = new GrantValidationResult(sub, GrantType);
        return;
    }
}

configured it inside Startup class inside the identity server using builder.AddExtensionGrantValidator(); Commented below line which i had before // services.AddScoped<IExtensionGrantValidator, DelegationGrantValidator>();

Next up went to the API1 project and wrote this code to make a call to the identityserver to get exchange token for api2.

var content = new FormUrlEncodedContent( new List<KeyValuePair<string, string>> { new KeyValuePair<string, string>("grant_type", "delegation"), new KeyValuePair<string, string>("scope", "api2"), new KeyValuePair<string, string>("token", accessToken1), new KeyValuePair<string, string>("client_id", "ap1.client"), new KeyValuePair<string, string>("client_secret", "secret") } );

        try
        {
            HttpResponseMessage response = await new HttpClient().PostAsync(new Uri("http://localhost:5000/connect/token"), content);
            return response;

        }

When i run the project now, even api1 call from Mvcclient fails with 401. Code gets inside the constructor 2 times before returning 401. this is the normal flow from mvcclient to api1 which is busted as well now. .I am sure i am doing something wrong here.. Any help is much appreciated.

public DelegationGrantValidator(ITokenValidator validator) { _validator = validator; }

monubamb avatar Sep 25 '19 17:09 monubamb

I tried using the IdentityModel client and made some progress as i am getting some error now..

TokenClientOptions tokenoptions = new TokenClientOptions
        {
            ClientId = "ap1.client",
            ClientSecret = "secret",
            Address = "http://localhost:5000/connect/token"
        };

        var client = new TokenClient(new HttpClient(), tokenoptions);
        var dict = new Dictionary<string, string>
        {
            { "scope", "api2" },
            { "token", accessToken1 }
        };
        var tokenresponse = await client.RequestTokenAsync("delegation",dict);
        return tokenresponse;

i am getting Invalid Client error. image

The documentation is not current also. That is another problem. The TokenClient does not have "RequestCustomGrantAsync" API as documented here.. Therefore i used the REquestTokenASync dont know if that is even the right one..

image

i had added the client info in identityserver code as per the documentation new Client { ClientId = "api1.client", ClientName ="api1", ClientSecrets = new List { new Secret("secret".Sha256()) },

                AllowedGrantTypes = { "delegation" },

               AllowedScopes =
                {
                  "api2"
                }
            },

monubamb avatar Sep 25 '19 22:09 monubamb

Here is the fiddler trace.

image

monubamb avatar Sep 26 '19 00:09 monubamb

So now check your server logs to see why you get an invalid_client.

leastprivilege avatar Sep 26 '19 04:09 leastprivilege

I was able to get it working. Client Invalid was invalid. Thank you @leastprivilege

I have one additional question. I can only see 'sub' in the new token returned from the GrantValidationResult(). I dont see additional claims. I would need them when passing this token to the API2 for further authorization. What is the way to implement that?

Any sample would be great.

monubamb avatar Sep 26 '19 23:09 monubamb

as always - you need a profile service to put claims into tokens.

leastprivilege avatar Sep 27 '19 05:09 leastprivilege

Thanks @leastprivilege . I made progress on that.

But i am stuck now this issue. I converted all the calls to HTTPS and am TRYING TO RUN it inside of a Linux container on Windows. But the call from my mvcclient to identityserver is failing with this error. mvclient.com_1 | System.InvalidOperationException: IDX20803: Unable to obtain configuration from: 'https://identityserver.com:5004/.well-known/openid-configuration'. ---> System.IO.IOException: IDX20804: Unable to retrieve document from: 'https://identityserver.com:5004/.well-known/openid-configuration'. ---> System.Net.Http.HttpRequestException: Connection refused --->

I added IdentityServerOptions var builder = services.AddIdentityServer(options =>{options.IssuerUri = "https://identityserver.com:5004";}) but that did not help.

I am running using docker-compose for those 2 containers. Pinging from mvcclient container to identityserver container works fine..

Something else is going on.. Any help is much appreciated. Hitting a deadline here..

monubamb avatar Oct 01 '19 01:10 monubamb

Sorry . can't help you with networking issues. I am glad the code is working.

leastprivilege avatar Oct 09 '19 06:10 leastprivilege

This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.

lock[bot] avatar Jan 10 '20 16:01 lock[bot]