Skip to main content
Version: 8.1

Implement authentication using C#

Level: intermediate
Example

Implement authentication using C#.

Example implementation algorithm

Create a C# console application in Visual Studio and give it a name, e.g., RequestAuthentification.

Example of a software implementation of the authentication
// Sends a request to the authentication service and processes the response.
public void TryLogin() {
var authData = @"{
""UserName"":""" + _userName + @""",
""UserPassword"":""" + _userPassword + @"""
}";
var request = CreateRequest(_authServiceUrl, authData);
_authCookie = new CookieContainer();
request.CookieContainer = _authCookie;
// Upon successful authentication, we save authentication cookies for
// further use in requests to Creatio. In case of failure
// authentication application console displays a message about the reason
// of the mistake.
using (var response = (HttpWebResponse)request.GetResponse())
{
if (response.StatusCode == HttpStatusCode.OK)
{
using (var reader = new StreamReader(response.GetResponseStream()))
{
var responseMessage = reader.ReadToEnd();
Console.WriteLine(responseMessage);
if (responseMessage.Contains("\"Code\":1"))
{
throw new UnauthorizedAccessException($"Unauthorized {_userName} for {_appUrl}");
}
}
string authName = ".ASPXAUTH";
string authCookeValue = response.Cookies[authName].Value;
_authCookie.Add(new Uri(_appUrl), new Cookie(authName, authCookeValue));
}
}
}
// Create request to the authentication service.
private HttpWebRequest CreateRequest(string url, string requestData = null)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.ContentType = "application/json";
request.Method = "POST";
request.KeepAlive = true;
if (!string.IsNullOrEmpty(requestData))
{
using (var requestStream = request.GetRequestStream())
{
using (var writer = new StreamWriter(requestStream))
{
writer.Write(requestData);
}
}
}
return request;
}
// Method realizes protection from CSRF attacks: copies cookie, which contents CSRF-token
// and pass it to the header of the next request.
private void AddCsrfToken(HttpWebRequest request) {
var cookie = request.CookieContainer.GetCookies(new Uri(_appUrl))["BPMCSRF"];
if (cookie != null) {
request.Headers.Add("BPMCSRF", cookie.Value);
}
}

Resources

GitHub (example implementation)