Ali
Ali

Reputation: 1235

OWIN add extra parameters in Response

I am writing an API end point in ASP.NET using Owin, it is working fine and now I wan to make some changes.

First thing I wan tot do is to add a new grant type , for example I wan to use grant_type=xyz and currently it is Password.

Second thing is that I wan to add extra parameters to the response body, for example currently it has "access_token", "token_type" and "expires_in" and I want to add "organization_name" and "Developer.email"

enter image description here

I am trying to add a middle ware but don't know how to add parameters in response.

I have also tried this code in GrantResourceOwnerCredentials method but output is wrong JSON.

var jsonString = "{\"foo\":1,\"bar\":false}";
byte[] data = Encoding.UTF8.GetBytes(jsonString);
context.Response.ContentType = "application/json";
context.Response.Body.WriteAsync(data, 0, data.Length);

enter image description here

Upvotes: 0

Views: 2609

Answers (1)

Abdul Rehman Sayed
Abdul Rehman Sayed

Reputation: 6672

Note : this answers half of your question regarding sending custom data in response.

you can use a custom OAuthAuthorizationServerProvider & manipulate the response like this.

 public override Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            return Task.Factory.StartNew(() =>
            {
                var userName = context.UserName;
                var password = context.Password;
                var userService = new UserService();
                var user = userService.Validate(userName, password);
                if (user != null)
                {
                    var claims = new List<Claim>()
            {
                new Claim(ClaimTypes.Sid, Convert.ToString(user.Id)),
                new Claim(ClaimTypes.Name, user.Name),
                new Claim(ClaimTypes.Email, user.Email),
                };

                    var data = new Dictionary<string, string>
            {
                { "userName", user.Name },
                 { "ExtraPara","ExtraData"},
                 { "developer","Abdul"}
            };
                    var properties = new AuthenticationProperties(data);

                    ClaimsIdentity oAuthIdentity = new ClaimsIdentity(claims,
                        Startup.OAuthOptions.AuthenticationType);

                    var ticket = new AuthenticationTicket(oAuthIdentity, properties);
                    context.Validated(ticket);
                }
                else
                {
                    context.SetError("invalid_grant", "Either email or password is incorrect");
                }

            });
        }

Upvotes: 0

Related Questions