How to send encrypted (3DES) data into aqueduct without getting any error? - request

I m using Aqueduct 3.0. I need to learn How to capture post request in Aqueduct 3.0?
My Request: http://127.0.0.1:8888/login/ziD7v0Ul99vmNWnxJRxZIiTY4zakNoq8GjM+oHROYz/YTHnd3NH1XfHRULY0jaHU
Get a Response:
[INFO] aqueduct: GET /login/ziD7v0Ul99vmNWnxJRxZIiTY4zakNoq8GjM+oHROYz/YTHnd3NH1XfHRULY0jaHU 11ms 404
my channel.dart routing
// TODO: connect to Socket **********
router.route('/login/[:value]').link(() {
return new LoginController();
//..contentType = ContentType.TEXT;
});
my LoginController.dart
import 'package:aqueduct/aqueduct.dart';
import 'package:niyaziapi/niyaziapi.dart';
import 'package:niyaziapi/util/niyaziGetPrivate.dart';
import 'package:niyaziapi/util/niyaziSetPrivate.dart';
class LoginController extends Controller {
String _xCustomerToken;
String _xCustomerName;
String _xPrivate;
String _xResult;
String _xRequestValue;
String _xReply;
#override
Future<RequestOrResponse> processRequest(Request request) async {
String tempData = request.toString();
print("tempDate: $tempData"); // can’t print
try {
if (request.path.variables.containsKey('value')) {
_xPrivate = (request.path.variables['value']).trim();
print("_xPrivate: $_xPrivate");
var decryptedData = await getPrivate(_xPrivate);
var decryptedList = decryptedData.split(":_:");
decryptedData = null;
decryptedData = "Q101:_:" + decryptedList[2].toString() + ":_:" + decryptedList[3].toString();
print(decryptedData);
var socket = await Socket.connect('192.168.1.22', 1024);
socket.write("$decryptedData\r\n");
await for (var data in socket) {
_xReply = new String.fromCharCodes(data).trim();
var list = _xReply.split(":_:");
_xCustomerToken = list[2].toString();
_xCustomerName = list[3].toString();
});
_xResult = "$_xCustomerToken:_:$_xCustomerName";
var encryptedData = await setPrivate(_xResult);
return new Response.ok("$encryptedData");
}
} else {
return new Response.ok("404: Wrong Request");
}
} catch (e) {
return new Response.ok("404: $e.errorMessage");
}
}
}
when I testing I found that my code works. Only reason that I am sending 3DES data and has + and / character in it.
If you look at closely in first request, there is a + and / character in data which give me an error.
/login/ziD7v0Ul99vmNWnxJRxZIiTY4zakNoq8GjM+oHROYz/YTHnd3NH1XfHRULY0jaHU 19ms 404
on the other hand if I remove those character than I get perfect response.
/login/ziD7v0Ul99vmNWnxJRxZIiTY4zakNoq8GjMoHROYzYTHnd3NH1XfHRULY0jaHU 13 ms 200
So, question comes how to send encrypted (3DES) data into aqueduct without getting any error?

Going to Like Aqueduct twice :)
It was very simple:
var _xPrivate = (request.path.variables['value']).trim(); change to:
var _xPrivate = request.path.remainingPath;
print("request: $_xPrivate");

Related

MSAL TokenAcquisition from the token stored in the file

I have saved initial usertakencache in a file. Now when I want to acquire the AcquireTokenSilent, I dont know how to use that saved token cache because all the documentation I find are used on the basis of cache but not for other memory formats.
I have searched on number of microsoft MSAL repos but they do not provide any help with the solution.
IConfidentialClientApplication app = MsalAppBuilder.BuildConfidentialClientApplication();
AuthenticationResult result = null;
StreamReader sr = new StreamReader("D:\\Test.txt");
string line = sr.ReadLine();
var accounts = await app.GetAccountsAsync();
string[] scopes = { "Mail.Read" };
try
{
// try to get token silently
result = await app.AcquireTokenSilent(scopes, accounts.FirstOrDefault()).ExecuteAsync().ConfigureAwait(false);
}
catch (MsalUiRequiredException)
{
ViewBag.Relogin = "true";
return View();
}
catch (Exception eee)
{
ViewBag.Error = "An error has occurred. Details: " + eee.Message;
return View();
}
if (result != null)
{
// Use the token to read email
HttpClient hc = new HttpClient();
hc.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", result.AccessToken);
HttpResponseMessage hrm = await hc.GetAsync("https://graph.microsoft.com/v1.0/me/messages");
string rez = await hrm.Content.ReadAsStringAsync();
ViewBag.Message = rez;
}

NancyFX on Krestrel - Response Stream Closed

I'm attempting it make a simple proxy server that will try to stream back data from an IP camera (the IP camera doesn't honor OPTIONS and has some other issues!). I tried doing this using NancyFX and Krestrel with the following proxy module. The idea was to just get 1028 bytes of data in and write it to the output stream asynchronously until canceled.
Here is a sample Nancy Module:
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading;
using System.Threading.Tasks;
using Nancy;
namespace Server.Modules
{
public class Proxy : NancyModule
{
public Proxy() : base("api/proxy")
{
Get("/", ProxyPage);
}
private async Task<Response> ProxyPage(dynamic args, CancellationToken cancellationToken)
{
// Create HttpClient
using (var httpClient = new HttpClient()) // Make this global/cached and indexed by auth code
{
// Handle Authentication
var auth = string.Empty;
if (!string.IsNullOrEmpty(Request.Headers.Authorization) && Request.Headers.Authorization.Contains(" "))
auth = Request.Headers.Authorization.Split(' ')[1];
else if (!string.IsNullOrEmpty(Request.Query.authorization))
auth = Request.Query.authorization;
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", auth);
// Create Proxy REsponse object
var proxyResponse = new Response();
// Get Async
HttpResponseMessage response = await httpClient.GetAsync(Request.Query["url"],
HttpCompletionOption.ResponseHeadersRead, cancellationToken);
// Set Content Type
proxyResponse.ContentType = response.Content.Headers.ContentType.ToString();
// Set Status Code
proxyResponse.StatusCode = (HttpStatusCode)(int)response.StatusCode;
// Handle stream writing
proxyResponse.Contents = async s =>
{
var result = response.Content.ReadAsStreamAsync();
var data = new byte[1028];
int bytesRead;
while (!cancellationToken.IsCancellationRequested && (bytesRead = await result.Result.ReadAsync(data, 0, data.Length, cancellationToken)) > 0)
{
await s.WriteAsync(data, 0, bytesRead, cancellationToken);
await s.FlushAsync(cancellationToken);
}
response.Dispose();
};
// Return Response container
return proxyResponse;
}
}
}
}
When I run it, I get through the while loop a couple times but then get an exception in FrameResponseStream (Krestrel): "System.ObjectDisposedException: 'Cannot access a disposed object.'" It appears that the stream is being closed (_state = FrameStreamState.Closed -- https://github.com/aspnet/KestrelHttpServer/blob/rel/2.0.0/src/Microsoft.AspNetCore.Server.Kestrel.Core/Internal/Http/FrameResponseStream.cs) prematurely but I cannot figure out why or what I need to change to resolve it!
You should use ResponseContentRead instead of ResponseHeadersRead
HttpResponseMessage response = await httpClient.GetAsync(Request.Query["url"],
HttpCompletionOption.ResponseContentRead, cancellationToken);

Node promises and catch issue

I am currently writing a database class that receives a node http request and saves data into a db.
It uses MSSQL (yeah...), therefore I'm using node-mssql.
I created a class to manage DB access, code:
"use strict";
var config = require('../../config/mainConfigs');
const mssql = require('mssql');
class db {
constructor(){
this._pool = null;
}
get_pool(){
if (!this._pool) {
if (config.Logging.DB.type == 'mssql'){
const dbOptions = {
user: config.Logging.DB.user,
password: config.Logging.DB.password,
server: config.Logging.DB.mssql.server,
database: config.Logging.DB.mssql.database,
options: {
encrypt: config.Logging.DB.encrypt
}
};
this._pool = new mssql.ConnectionPool(dbOptions);
}
}
return this._pool;
}
insertHTTPRequest(req){
const pool = this.get_pool();
if (config.Logging.DB.type == 'mssql'){
if (pool._connected){
var request = new mssql.Request(pool);
var query = `INSERT INTO SD_LOG (
MODULE,
INSTANCE,
REMOTE_ADDR,
USERNAME,
USER_AGENT,
HTTP_METHOD,
HTTP_REQ_URL
) OUTPUT Inserted.ID_SD_LOG VALUES (
#module,
#instance,
#remote_addr,
#username,
#user_agent,
#http_method,
#http_req_url
)`;
request.input('module', 'tokenizer');
request.input('instance', config.Deployment.instance);
request.input('remote_addr', req.ip);
request.input('username', req.user.displayName);
request.input('user_agent', req.headers['user-agent']);
request.input('http_method', req.method);
request.input('http_req_url', req.url);
return request.query(query);
}else{
return pool.connect().then(() => {
var request = new mssql.Request(pool);
var query = `INSERT INTO SD_LOG (
MODULE,
INSTANCE,
REMOTE_ADDR,
USERNAME,
USER_AGENT,
HTTP_METHOD,
HTTP_REQ_URL
) OUTPUT Inserted.ID_SD_LOG VALUES (
#module,
#instance,
#remote_addr,
#username,
#user_agent,
#http_method,
#http_req_url
)`;
request.input('module', 'tokenizer');
request.input('instance', config.Deployment.instance);
request.input('remote_addr', req.ip);
request.input('username', req.user.displayName);
request.input('user_agent', req.headers['user-agent']);
request.input('http_method', req.method);
request.input('http_req_url', req.url);
request.query(query);
}
}
}
}
I am using a middleware in the routes to save the request into the DB, like this:
app.use(function(req, res, next){
//send req to DB, get ID_SD_LOG from DB, assign to req.id
db_instance.insertHTTPRequest(req).then((genid)=>{
req.id = genid;
next();
}).catch((err)=>{
combinedLogger.error(err);
res.send('Database is unavailable.');
res.end();
})
});
Thing is, I am getting an error, however, in console, the error is undefined. So I really can't figure out whats wrong. I can imagine it's the connect() method, as I tested logging in console static string in the db request and I don't them, which I assume it's not even accessing that part.
Any help?
Thanks!

TokenCache: No matching token was found in the cache, Azure AD Api

I'd like to use Azure AD Api and I couldn't acquire token some reason. I have two methods, and I got this after calling:
TokenCache: No matching token was found in the cache iisexpress.exe Information: 0
Here's my code:
public string GetToken()
{
string authority = "https://login.microsoftonline.com/{tenantId}/";
string clientId = "";
string secret = "";
string resource = "https://graph.windows.net/";
var credential = new ClientCredential(clientId, secret);
AuthenticationContext authContext = new AuthenticationContext(authority);
//I think the problem is here:
var token = authContext.AcquireTokenAsync(resource, credential).Result.AccessToken;
return token;
}
public string MakeRequest()
{
string accessToken = GetToken();
var tenantId = "";
string graphResourceId = "https://graph.windows.net/";
Uri servicePointUri = new Uri(graphResourceId);
Uri serviceRoot = new Uri(servicePointUri, tenantId);
ActiveDirectoryClient client = new ActiveDirectoryClient(serviceRoot, async () => await Task.FromResult(accessToken));
foreach (var user in client.Users.ExecuteAsync().Result.CurrentPage)
Console.WriteLine(user.DisplayName);
var client1 = new HttpClient();
var uri = "https://graph.windows.net/" + tenantId + "/users?api-version=1.6";
client1.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", accessToken);
var response = client1.GetAsync(uri).Result;
var result = response.Content.ReadAsStringAsync().Result;
return result;
}
I don't know what's the problem, and I didn't find any great hint, under other questions and a little explanation would be helpful. I'd like to understand this part, of course.
//When you are calling
Main() { Method_A() }
aync Method_A() { await Method_B() }
Task < T > Method_B() { return T; }
//It will through the error. //Need to keep Mehtod_B in another Task and run.
// Here I am avoiding few asyncs
Main() { Method_A() }
Method_A() { Method_B().Wait() }
Task Method_B() { return T; }
There is no output using the Console.WriteLine in a IIS progress. If you want to output the result in a output window for the web project, you can use System.Diagnostics.Debug.WriteLine() method.

Cannot Validate SAML sign (Using OpenSAML)

I use OpenSAML. I get a problem it cannot validate sign
I try to validate after I got I get Response, It' Ok. But when I convert to XML and unmarshall, it cannot validate it.
My Code
Element responseElement = null;
ResponseMarshaller marshaller = new ResponseMarshaller();
try {
responseElement = marshaller.marshall(response); //
/*
* SAML utility = new SAML(); Document doc =
* utility.asDOMDocument(response); // Element target =
* doc.getDocumentElement();
*/
Signer.signObjects(signatures);
} catch (Exception ex) {
ex.printStackTrace();
}
When I use ResponseElement to validate, it works.
MY Code Convert SAMLResponse to String
String samlXmlString = XMLHelper.prettyPrintXML(responseElement);
BasicParserPool parserPool = new BasicParserPool();
parserPool.setNamespaceAware(true);
Document document;
logger.debug("Parsing...");
document = parserPool.parse(new StringReader(samlXmlString));
Element responseElement = document.getDocumentElement();
logger.debug("responseElement is:\n{}", convertToString(responseElement));
Response response;
logger.debug("Unmarshalling...");
UnmarshallerFactory unmarshallerFactory = Configuration.getUnmarshallerFactory();
Unmarshaller unmarshaller = unmarshallerFactory.getUnmarshaller(responseElement);
response = (Response) unmarshaller.unmarshall(responseElement);
logger.debug("Successfully unmarshalled");
I use Response to validate. It doesn't work.
How can I validate it?

Resources