Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass back parameters in ASP.NET Web API GrantResourceOwnerCredentials

I am trying to pass back some parameters from ASP.NET Web API after the user has logged in.

I am basing my work on this nice tutorial: http://bitoftech.net/2014/06/01/token-based-authentication-asp-net-web-api-2-owin-asp-net-identity/

I can see on the demo page that he sends back userName for example.

I create my own provider that inherits from OAuthAuthorizationServerProvider And this is what I do:

public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{ 
    ....

    var identity = new ClaimsIdentity(context.Options.AuthenticationType);
    identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
    identity.AddClaim(new Claim("role", user.Role));

    var props = new AuthenticationProperties(new Dictionary<string, string>
    {
        { 
            "userName", user.UserName
        },
        { 
            "role", user.Role
        }
    });

    var ticket = new AuthenticationTicket(identity, props);
    context.Validated(ticket);
}

This is how I hook it up:

var OAuthBearerOptions = new OAuthBearerAuthenticationOptions();
var OAuthServerOptions = new OAuthAuthorizationServerOptions()
{
    AllowInsecureHttp = true,
    TokenEndpointPath = new PathString("/token"),
    AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
    Provider = new SimpleAuthorizationServerProvider()
};

// Token Generation
app.UseOAuthAuthorizationServer(OAuthServerOptions);

As I understand it, the AuthenticationProperties dictionary should be passed back in the JSON response to the client. But for some reason I don't get my additional parameters back. This is what I get:

{"access_token":"G4S1PXdNbtAHLFBo......","token_type":"bearer","expires_in":86399}

I have spent alot of time trying to figure this one out, can anyone see that I am missing?

like image 546
Joel Fransson Avatar asked Aug 11 '14 09:08

Joel Fransson


1 Answers

I found my issue. It seems as if I misunderstood the properties dictionary.

I added this method:

public override Task TokenEndpoint(OAuthTokenEndpointContext context)
{
    foreach (KeyValuePair<string, string> property in context.Properties.Dictionary)
    {
        context.AdditionalResponseParameters.Add(property.Key, property.Value);
    }

    return Task.FromResult<object>(null);
}

It basically takes the entries in the dictionary and adds it to the response. My mistake was to assume that would be done automatically for me.

like image 63
Joel Fransson Avatar answered Sep 28 '22 04:09

Joel Fransson