locked
Web API Token and User Details in XML RRS feed

  • Question

  • User214251496 posted

    Hi guys,

    I took over a Web API project, it is still in very initial stages. I never worked on Web API before.

    My question is that how can I receive the data from client ‘username’, ‘password’ and ‘grant_type’ in XML? Also, how can I return the token as XML? I have found this link(https://stackoverflow.com/questions/23375815/web-api-return-oauth-token-as-xml) but don’t really understand where to add the potential solution.

    Startup Class

    public class Startup

       {

           public void Configuration(IAppBuilder app)

           {

               app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);

               var myProvider = new AuthorizationServerProvider();

               OAuthAuthorizationServerOptions options = new OAuthAuthorizationServerOptions

               {

                   AllowInsecureHttp = true,

                   TokenEndpointPath = new PathString("/token"),

                   AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(120),

                   Provider = myProvider,                

                   RefreshTokenProvider = new RefreshTokenProvider()              

     

               };

               app.UseOAuthAuthorizationServer(options);

               app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());

     

               HttpConfiguration config = new HttpConfiguration();

               WebApiConfig.Register(config);

     

           }

    }

     

    WebApiConfig Class

    public static class WebApiConfig

       {

           public static void Register(HttpConfiguration config)

           {

               // Web API configuration and services

     

               // Web API routes

               config.MapHttpAttributeRoutes();

               GlobalConfiguration.Configuration.Formatters.XmlFormatter.UseXmlSerializer = true;

     

                      

               config.Routes.MapHttpRoute(

                   name: "DefaultApi",

                   routeTemplate: "api/{controller}/{id}",

                   defaults: new { id = RouteParameter.Optional }

                        

               );

           }  

       }

    Global.asax

    public class Global : HttpApplication

       {

           void Application_Start(object sender, EventArgs e)

           {

               // Code that runs on application startup

               AreaRegistration.RegisterAllAreas();

               GlobalConfiguration.Configure(WebApiConfig.Register);

               RouteConfig.RegisterRoutes(RouteTable.Routes); 

                GlobalConfiguration.Configuration.Formatters.XmlFormatter.UseXmlSerializer = true;

               GlobalConfiguration.Configuration.Formatters.Clear();

               GlobalConfiguration.Configuration.Formatters.Add(new System.Net.Http.Formatting.XmlMediaTypeFormatter()); 

           } 

       }

     

     

    Thursday, April 12, 2018 4:03 PM

All replies

  • User36583972 posted

    Hi tmukhtar,

    My question is that how can I receive the data from client ‘username’, ‘password’ and ‘grant_type’ in XML? Also, how can I return the token as XML?

    I cannot understand your question clearly. You want to receive the data from Web API and use the ‘username’, ‘password’ to verify authorization?

    You can refer the following article to authorize your Web API( Individual Accounts and access token).

    Secure a Web API with Individual Accounts and Local Login in ASP.NET Web API 2.2


    Best Regards,

    Yong Lu

    Friday, April 13, 2018 8:04 AM
  • User214251496 posted

    Hi Yohann,

    Thanks for you reply.

    I am trying to receive 'username', 'password' and 'grant_type' in XML format and send the response back in XML.  At the moment, I am getting JSON response:

    {    "access_token": "q1xt7bWZ0KWSSGt3MFdSjQ20rua736H1-EKcTegUEQVQPZfqUdu_Nvit8SwLffidwb9cbEdvPjW4Fzj1ytnIXYwHeq2XxEkbux-KoPJLGtZ13U1Ig_uA2jlOUSjDdqiwtFNEMDul3oa3SF0FkZ_UM4OnLY2jxXy-06FvW8xB54Rbg01tsC542S2XCu9TBFQ-4bkkanoRoghgwODrVKyArbUxtBV3g43sH70jPeU436KbyPweriLt169qQA_J9JGne1EKxUvSav703o1e2pwCq0ebr_xMZ8MSOMZ53w-9WfY",
        "token_type": "bearer",
        "expires_in": 7199,
        "refresh_token": "2ba02790-d405-4e8e-9995-408592c0c1b6"
    }

    1. I would like to have above response in XML
    2. At the moment, I'm sending username, password and grant_type in Body but I would to have them in body but in XML format. e.g below

    <UserDetails>

            <username>testuser </username>

            <password>testpassword</password>

             <grant_type>password </grant_type>

    <UserDetails>

    I hope it is making sense now.

    Thanks in advance.

    Friday, April 13, 2018 8:31 AM
  • User214251496 posted

    I have made the changes as suggested here

    Now Startup looks like this, hopefully it will helpful for someone else

    public void Configuration(IAppBuilder app)

    {

    app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);

    var myProvider = new AuthorizationServerProvider();

    OAuthAuthorizationServerOptions options = new OAuthAuthorizationServerOptions

    {

    AllowInsecureHttp = true,

    TokenEndpointPath = new PathString("/token"),

    AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(120),

    Provider = myProvider,

    RefreshTokenProvider = new RefreshTokenProvider()

    };

    app.Use(async (context, next) =>

    {

    if (context.Request != null &&

    context.Request.Headers != null &&

    context.Request.Headers.ContainsKey("Accept") &&

    context.Request.Headers.Get("Accept").Contains("xml"))

    {

    //Set a reference to the original body stream

    using (var stream = context.Response.Body)

    {

    //New up and set the response body as a memory stream which implements the ability to read and set length

    using (var buffer = new System.IO.MemoryStream())

    {

    context.Response.Body = buffer;

    //Allow other middlewares to process

    await next.Invoke();

    //On the way out, reset the buffer and read the response body into a string

    buffer.Seek(0, System.IO.SeekOrigin.Begin);

    using (var reader = new System.IO.StreamReader(buffer))

    {

    string responsebody = await reader.ReadToEndAsync();

    //Using our responsebody string, parse out the XML and add a declaration

    var xmlVersion = Newtonsoft.Json.JsonConvert.DeserializeXNode(responsebody, "oauth");

    xmlVersion.Declaration = new System.Xml.Linq.XDeclaration("1.0", "UTF-8", "yes");

    //Convert the XML to a byte array

    var bytes = System.Text.Encoding.UTF8.GetBytes(xmlVersion.Declaration + xmlVersion.ToString());

    //Clear the buffer bits and write out our new byte array

    buffer.SetLength(0);

    buffer.Write(bytes, 0, bytes.Length);

    buffer.Seek(0, System.IO.SeekOrigin.Begin);

    //Set the content length to the new buffer length and the type to an xml type

    context.Response.ContentLength = buffer.Length;

    context.Response.ContentType = "application/xml;charset=UTF-8";

    //Copy our memory stream buffer to the output stream for the client application

    await buffer.CopyToAsync(stream);

    }

    }

    }

    }

    else

    await next.Invoke();

    });

    app.UseOAuthAuthorizationServer(options);

    app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());

    HttpConfiguration config = new HttpConfiguration();

    WebApiConfig.Register(config);

     

    }

    Friday, April 13, 2018 3:00 PM
  • User214251496 posted

    Hi,

    I am still struggling to send the token request in XML. Can someone please help me to send the request parameters in XML format e.g.

    <username>userid</username>
    <password>userpassword</password>
    <grant_type>password</grant_type>

    Many thanks.

    Tuesday, April 17, 2018 8:30 AM
  • User36583972 posted

    Hi tmukhtar,

    I am still struggling to send the token request in XML. Can someone please help me to send the request parameters in XML format e.g.

    In ASP.NET Web API, it provides media-type formatters for both JSON and XML. The framework inserts these formatters into the pipeline by default. Clients can request either JSON or XML in the Accept header of the HTTP request.

    This XML Media-Type Formatter article describes the XML formatters in ASP.NET Web API.
    https://docs.microsoft.com/en-us/aspnet/web-api/overview/formats-and-model-binding/json-and-xml-serialization#xml-media-type-formatter


    Best Regards,

    Yong Lu

    Wednesday, April 18, 2018 9:42 AM