Example: Authentication on the REST Service

The following assembly references are required:

  • mscorlib
  • System
  • System.Core
  • System.Net.Http
  • System.Net.Http.Formatting
  • System.Web

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
using System;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
 
namespace Examples.CSharp.Rest
{
    /// <summary>   A REST example. </summary>
    public static partial class RestExample
    {
        /// <summary>   Example of login. </summary>
        /// <remarks>   Shows how to login. </remarks>
        /// <exception cref="InvalidOperationException">    Thrown when the requested operation is
        ///                                                 invalid. </exception>
        /// <param name="company">      The company. </param>
        /// <param name="account">      The user name. </param>
        /// <param name="password">     The password. </param>
        /// <returns>   The authentication token. </returns>
        public static string Login(string company, string account, string password)
        {
            // Create LoginCredentials object.
            var credentials = new LoginCredentials
            {
                Company = company,
                Account = account,
                Password = password,
            };
 
            HttpResponseMessage response;
 
            // Create service client instance.
            using (var serviceClient = new HttpClient { BaseAddress = new Uri("https://rmi-services.tecalliance.net") })
            {
                // Set the media type for the response either JSON ("application/json") or XML ("application/xml")
                // If not set the default response will be "application/json".
                serviceClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
 
                // Set the user agent to a value that indentifies your client application. If your client application is also
                // a web application the user agent of the original request could be passed to identify the user's browser
                // e.g. new ProductInfoHeaderValue(HttpContext.Current.Request.UserAgent).
                serviceClient.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue("Examples.Csharp.Rest", "1.0"));
 
                // Set the origin to a value that indentifies your client application. If your client application is also
                // a web application the user agent of the original request could be passed (HttpContext.Current.Request.UserAgent)
                // to identify the user's browser.
                serviceClient.DefaultRequestHeaders.Add("Origin", "http://origin.example");
 
                // Call service via POST. If method PostAsJsonAsync is missing: Add a reference to System.Net.Http.Formatting.dll (https://stackoverflow.com/a/19158658)
                response = serviceClient.PostAsJsonAsync("/auth/login", credentials).Result;
            }
 
            using (response)
            {
                // Check the status code.
                if (response.IsSuccessStatusCode)
                {
                    Console.WriteLine("Logged in.");
 
                    // Get the authentication token and store it to authenticate further requests
                    return response.Headers.GetValues("X-AuthToken").FirstOrDefault();
                }
 
                // handle the error if necessary.
                switch (response.StatusCode)
                {
                    case HttpStatusCode.Unauthorized: // 401
                        Console.WriteLine("Not Authenticated!");
                        break;
                    case HttpStatusCode.InternalServerError: // 500
                        Console.WriteLine("An error occured!");
                        break;
                    default:
                        Console.WriteLine("Unexpected response!");
                        break;
                }
 
                return null;
            }
        }
    }
 
    /// <summary>
    /// Class <see cref="LoginCredentials"/> contains the access parameters which are needed to use the webservice.
    /// </summary>
    /// <remarks>
    /// The login method requires the "Company", "Account" and "Password" properties, containing the application-specific access parameters.
    /// </remarks>
    public class LoginCredentials
    {
        /// <summary>   Gets or sets the company name. </summary>
        /// <value> The company name. </value>
        public string Company { get; set; }
 
        /// <summary>   Gets or sets the user name. </summary>
        /// <value> The user name. </value>
        public string Account { get; set; }
 
        /// <summary>   Gets or sets the password. </summary>
        /// <value> The password. </value>
        public string Password { get; set; }
    }
}
 
©   TecAlliance GmbH