With All Due Respect.
Below Code Is My Login Page. In Which I Authenticate Through API And Getting Token To Login.
But I Need To Separate Authentication Code From Login Page To Class File.
How I Can Achieve This. Please Help.
I Need To Separate Authentication Code Into Class File.
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace _5M_Solution
{
public partial class auth_login : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btn_Login_Click(object sender, EventArgs e)
{
string strToken = "";
if (!string.IsNullOrEmpty(strToken))
{
Console.WriteLine("Token issued is: {0}", strToken);
// string strrequesturl = "http://210.255.200.204:804/api/Voucher/GetVoucherByDate?Date_From=2022/04/01&Date_To=2022/04/24";
//string data = CommonFacade.ExecuteGET(strrequesturl, strToken);
// lbl_Msg.Text = data;
Response.Redirect("~/Default.aspx?MasterUserName=" + txt_username.Text);
}
else
{
Console.WriteLine("Error : {0}", strToken);
lbl_Msg.Text = "Authentication Failed";
}
}
//Cleanup string
string DecodeEncodedNonAsciiCharacters(string value)
{
return Regex.Replace(
value,
@"\\u(?<Value>[a-zA-Z0-9]{4})",
m =>
{
return ((char)int.Parse(m.Groups["Value"].Value, NumberStyles.HexNumber)).ToString();
});
}
//string BaseUrl = "http://mbmgroup.dyndns.biz/";
//string BaseUrl = "http://210.255.200.205/";
string BaseUrl = "http://210.255.200.204:804/";
string username = "";
string password = "";
public string Authenticate()
{
string token = string.Empty;
string tokenKey = "Authenticate_Token_Key";
token = (string)CommonFacade.getCacheObject(tokenKey); // Read token from cache
if (!string.IsNullOrEmpty(token)) // if found then return it immediately
{
return token;
}
// else contirnue to get it again
if (string.IsNullOrEmpty(txt_username.Text.Trim()) || string.IsNullOrEmpty(txt_password.Text.Trim()) ||
string.IsNullOrEmpty(BaseUrl))
{
// throw new ArgumentException("Username or password or Base cannot be empty");
return "";
}
Stream dataStream = null;
WebResponse response = null;
StreamReader reader = null;
try
{
// Prepare Data
//string body = string.Format("username={0}&Password={1}&HostName=&grant_type=password", txt_username.Text.Trim(),
string body = string.Format("username={0}&Password={1}&HostName=&grant_type=password", txt_username.Text.Trim(),
txt_password.Text.Trim());// Create body of the authetication request
byte[] byteArray = Encoding.UTF8.GetBytes(body);// convert it to a byte array with UTF8 encoding
string requestUrl = BaseUrl + "token";// ex: http://localhost:6888/token/
// Below lines are used for SSL Handshake. Mostly not required
//ServicePointManager.Expect100Continue = true;
//ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
// Create Http Request
WebRequest request = WebRequest.Create(requestUrl);
request.Method = "POST";
request.ContentType = "Application/x-www-form-urlencoded";
request.ContentLength = byteArray.Length;
//ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls| SecurityProtocolType.Tls11| SecurityProtocolType.Tls12| SecurityProtocolType.Ssl3;
// Read Request
dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
string responseText = string.Empty;
using (WebResponse webResponse = request.GetResponse())
using (StreamReader rd = new StreamReader(webResponse.GetResponseStream()))
{
responseText = rd.ReadToEnd();
}
var settings = new JsonSerializerSettings();
settings.StringEscapeHandling = StringEscapeHandling.EscapeHtml;
if (responseText.ToLower().Contains("\"error\""))
{
// SharikError resp = JsonConvert.DeserializeObject<SharikError>(DecodeEncodedNonAsciiCharacters(responseText), settings);
}
else
{
Token resp = JsonConvert.DeserializeObject<Token>(DecodeEncodedNonAsciiCharacters(responseText), settings);
if (resp != null && !string.IsNullOrEmpty(resp.AccessToken))
{
token = resp.AccessToken;
}
}
CommonFacade.AddToCache(tokenKey, token, CommonFacade.DefaultCacheTime); // store int cache for 2 hours
return token;
}
catch (Exception ex)// any response other than 200 OK
{
return "";
//throw;
}
finally
{
if (reader != null)
reader.Close();
if (dataStream != null)
dataStream.Close();
if (response != null)
response.Close();
}
}
public class Token
{
//[JsonProperty("access_token")]
//public string AccessToken { get; set; }
[JsonProperty("access_token")]
public string AccessToken { get; set; }
[JsonProperty("token_type")]
public string TokenType { get; set; }
[JsonProperty("expires_in")]
public int ExpiresIn { get; set; }
[JsonProperty("refresh_token")]
public string RefreshToken { get; set; }
[JsonProperty("error")]
public string Error { get; set; }
}
}
}