blazor wasm using Cryptography.Algorithms Error - cryptography

Unhandled exception rendering component: System.Security.Cryptography.Algorithms is not supported on this platform.
System.PlatformNotSupportedException: System.Security.Cryptography.Algorithms is not supported on this platform.
at System.Security.Cryptography.Aes.Create()
at AutoTradingWebAppV2.Helper.Crypto.Encryptstring(String text, String keyString) in D:\Web\AutoTradingApp-BWASM\AutoTradingWebAppV2\Helper\Crypto.cs:line 12
at AutoTradingWebAppV2.Handler.CustomUpbitAuthHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) in D:\Web\AutoTradingApp-BWASM\AutoTradingWebAppV2\Handler\CustomUpbitAuthHandler.cs:line 31
at System.Net.Http.DelegatingHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
at Microsoft.Extensions.Http.Logging.LoggingScopeHttpMessageHandler.<>n__0(HttpRequestMessage request, CancellationToken cancellationToken)
at Microsoft.Extensions.Http.Logging.LoggingScopeHttpMessageHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
at System.Net.Http.HttpClient.<SendAsync>g__Core|83_0(HttpRequestMessage request, HttpCompletionOption completionOption, CancellationTokenSource cts, Boolean disposeCts, CancellationTokenSource pendingRequestsCts, CancellationToken originalCancellationToken)
at System.Net.Http.Json.HttpClientJsonExtensions.<GetFromJsonAsyncCore>d__13`1[[System.Collections.Generic.IEnumerable`1[[DTOs.AccountDTO, DTOs, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]], System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]].MoveNext()
at Services.UpbitService.GetAccounts() in D:\Web\AutoTradingApp-BWASM\Services\UpbitService.cs:line 31
at AppViewModels.UpbitTradingViewModel.GetAccounts() in D:\Web\AutoTradingApp-BWASM\AppViewModels\UpbitTradingViewModel.cs:line 156
at AutoTradingWebAppV2.Pages.TradingInfoBoard.TryConnectToWebsocket() in D:\Web\AutoTradingApp-BWASM\AutoTradingWebAppV2\Pages\TradingInfoBoard.razor.cs:line 48
at Microsoft.AspNetCore.Components.ComponentBase.CallStateHasChangedOnAsyncCompletion(Task task)
at Microsoft.AspNetCore.Components.RenderTree.Renderer.GetErrorHandledTask(Task taskToHandle, ComponentState owningComponentState)
https://learn.microsoft.com/en-us/dotnet/core/compatibility/cryptography/5.0/cryptography-apis-not-supported-on-blazor-webassembly
then how to create JWT at blazor ? or use AES?
how to fix it or when they update blazor?
var jwtToken = JwtBuilder.Create()
.WithAlgorithm(new HMACSHA256Algorithm())
.WithSecret(SecretKey)
.AddClaim("access_key",AccessKey)
.AddClaim("nonce", Guid.NewGuid().ToString())
.Encode();
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", jwtToken);
I Added this code to httpclient handler, but can not use this code on blazor...
+
here is the open API sampleCode. I have to create JWT Token at Client and send request to api
C# CODE.
public class OpenAPISample {
public static void Main() {
var payload = new JwtPayload
{
{ "access_key", "Access Key" },
{ "nonce", Guid.NewGuid().ToString() },
{ "query_hash", queryHash },
{ "query_hash_alg", "SHA512" }
};
byte[] keyBytes = Encoding.Default.GetBytes("Secret Key");
var securityKey = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(keyBytes);
var credentials = new Microsoft.IdentityModel.Tokens.SigningCredentials(securityKey, "HS256");
var header = new JwtHeader(credentials);
var secToken = new JwtSecurityToken(header, payload);
var jwtToken = new JwtSecurityTokenHandler().WriteToken(secToken);
var authorizationToken = "Bearer " + jwtToken;
}
}
JAVA Example CODE (there is no C# CODE in web site)
public static void main(String[] args) {
String accessKey = System.getenv("OPEN_API_ACCESS_KEY");
String secretKey = System.getenv("OPEN_API_SECRET_KEY");
String serverUrl = System.getenv("OPEN_API_SERVER_URL");
Algorithm algorithm = Algorithm.HMAC256(secretKey);
String jwtToken = JWT.create()
.withClaim("access_key", accessKey)
.withClaim("nonce", UUID.randomUUID().toString())
.sign(algorithm);
String authenticationToken = "Bearer " + jwtToken;
try {
HttpClient client = HttpClientBuilder.create().build();
HttpGet request = new HttpGet(serverUrl + "/v1/accounts");
request.setHeader("Content-Type", "application/json");
request.addHeader("Authorization", authenticationToken);
HttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();
System.out.println(EntityUtils.toString(entity, "UTF-8"));
} catch (IOException e) {
e.printStackTrace();
}
}

how to create JWT at blazor ?
A JWT is created on the Server. And consumed by a Client app.
The APIs are unsupported for technical reasons but you shouldn't want to use them on a Client. Your client is not able to hide any credentials, it would only give false security.
That holds for AES as well. You can't hide the key.
they only give me accesskey and secret key and ask me make jwt
You should do this on your own Server. Your SPA client calls your Server that calls the Open API server.
Make sure the secret key never ends up in the SPA client.

Related

Azure function app using CSOM and Azure AD for authentication

I'm not sure if this is possible but my objective is an Azure function app that can use the SharePoint CSOM. I'm stuck on how to do the authorization with no user credentials. I've pieced together the code below but it throws a 401 unauthorized. This could be a configuration issue which I've had problems with when doing a JavaScript application and a Web Api. But I'm also wondering if this is even feasible or if I'm going about it the wrong way. Some key points before the code:
My front end demo app was created with a secret to be used in authentication
My Api demo app was granted API permissions to Azure AD, Microsoft Graph, and SharePoint
My Api demo app exposed an API and the front end demo app was added as an authorized client app
private static async Task ProcessMessageAsync(string myQueueItem, ILogger log)
{
const string mName = "ProcessMessageAsync()";
string resource = "https://my-Portal.onmicrosoft.com/demoapp-api"; //demoapp-api with permission to sharepoint
string clientId = "guid-of-demoapp-frontend"; //demoapp-frontend
string clientSecret = "secret-from-demoapp-frontend"; //demoapp-frontend secret
string siteUrl = "https://my-portal.sharepoint.com/sites/my-site"; //sharepoint site
string authorityUri = "https://login.microsoftonline.com/my-portal.onmicrosoft.com";
try
{
using (ClientContext ctx = await GetClientContext(authorityUri, siteUrl, resource, clientId, clientSecret))
{
Web web = ctx.Web;
ctx.Load(web);
ctx.ExecuteQuery();
log.LogInformation($"found site : {web.Title}");
}
}
catch (Exception ex) {
Console.WriteLine("***Unexpected Exception in {0} *** : {1}", mName, ex.Message);
log.LogInformation("***Unexpected Exception in {0} *** : {1}", mName, ex.Message);
while (ex.InnerException != null)
{
ex = ex.InnerException;
Console.WriteLine(ex.Message);
}
}
}
public async static Task<ClientContext> GetClientContext(string authorityuri, string siteUrl, string resource, string clientId, string clientSecret)
{
AuthenticationContext authContext = new AuthenticationContext(authorityuri);
AuthenticationResult ar = await GetAccessToken(authorityuri, resource, clientId, clientSecret);
string token = ar.AccessToken;
var ctx = new ClientContext(siteUrl);
ctx.ExecutingWebRequest += (s, e) =>
{
e.WebRequestExecutor.RequestHeaders["Authorization"] = "Bearer " + ar.AccessToken;
};
return ctx;
}
static async Task<AuthenticationResult> GetAccessToken(string authority, string resource, string clientId, string clientSecret)
{
var clientCredential = new ClientCredential(clientId, clientSecret);
AuthenticationContext context = new AuthenticationContext(authority, false);
AuthenticationResult authenticationResult = await context.AcquireTokenAsync(
resource, // the resource (app) we are going to access with the token
clientCredential); // the client credentials
return authenticationResult;
}
Update
After further research I think the problem might be that I was using delegate permissions and instead I need application permissions (which require that I have admin access in the directory).
You get token with following code:
AuthenticationResult ar = await GetAccessToken(authorityuri, resource, clientId, clientSecret);
string token = ar.AccessToken;
However, the token you get can only be used to access the resource you specified as the parameter. In your case, it is "https://my-Portal.onmicrosoft.com/demoapp-api".
So, you can only use that token to access your endpoint web API, not sharepoint directly.

Forward POST request from asp.net core controller to different URL

I wanto to forward an incoming POST request to my asp.net core controller "as is" (including headers, body, from-data) to a different URL without using a middleware.
I found an example for doing that for asp.net: https://philsversion.com/2012/09/06/creating-a-proxy-with-apicontroller/
But this does not work for asp.net core, since the call to
return await http.SendAsync(this.Request);
in asp.net core accepts an HttpRequestMessage and the Request object is of type HttpRequest.
I also found some code, which creates a HttpRequestMessage from an HttpRequest, see: Convert Microsoft.AspNetCore.Http.HttpRequest to HttpRequestMessage
Using this code, the receiving endpoint (to which I forward to) gets the Body, but it does not get Form fields.
Checking the class HttpRequestMessage I saw that it does not contain a property for FormFields.
[Microsoft.AspNetCore.Mvc.HttpPost]
[NrgsRoute("api/redirect-v1/{key}")]
public async Task<HttpResponseMessage> Forward(
[FromUri] string key,
CancellationToken cancellationToken)
{
// the URL was shortened, we need to get the original URL to which we want to forward the POST request
var url = await _shortenUrlService.GetUrlFromToken(key, cancellationToken).ConfigureAwait(false);
using (var httpClient = new HttpClient())
{
var forwardUrl = new Uri(url);
Request.Path = new PathString(forwardUrl.PathAndQuery);
// see: https://stackoverflow.com/questions/45759417/convert-microsoft-aspnetcore-http-httprequest-to-httprequestmessage
var requestMessage = Request.ToHttpRequestMessage();
return await httpClient.SendAsync(requestMessage, cancellationToken);
// Problem: Forwards header and body but NOT form fields
}
}
Expected result would be that at my receiving endpoint I have the same
- headers
- body
- form fields
as in the original POST request.
I ended up doing the following:
[HttpPost]
[NrgsRoute("api/redirect-v1/{key}")]
public async Task<RedirectResult> Forward(string key, CancellationToken cancellationToken)
{
var url = await _shortenUrlService.GetUrlFromToken(key, cancellationToken).ConfigureAwait(false);
if (string.IsNullOrEmpty(url))
throw new BadRequestException($"Could not create forward URL from parameter {key}", "redirect-error");
using (var httpClient = new HttpClient())
{
var forwardUrl = new Uri(url);
Request.Path = new PathString(forwardUrl.PathAndQuery);
HttpResponseMessage responseMessage;
if (Request.HasFormContentType)
responseMessage = await ForwardFormData(key, httpClient, forwardUrl, cancellationToken);
else
responseMessage = await ForwardBody(key, httpClient, cancellationToken);
var queryParams = forwardUrl.GetQueryStringParams();
var lUlr = queryParams["lurl"];
return new RedirectResult(lUlr);
}
}
private async Task<HttpResponseMessage> ForwardFormData(string key, HttpClient httpClient, Uri forwardUrl, CancellationToken cancellationToken)
{
var formContent = new List<KeyValuePair<string, string>>();
HttpResponseMessage result;
if (Request.ContentType == "application/x-www-form-urlencoded")
{
foreach (var formKey in Request.Form.Keys)
{
var content = Request.Form[formKey].FirstOrDefault();
if (content != null)
formContent.Add(new KeyValuePair<string, string>(formKey, content));
}
var formUrlEncodedContent = new FormUrlEncodedContent(formContent);
result = await httpClient.PostAsync(forwardUrl, formUrlEncodedContent, cancellationToken);
}
else
{
var multipartFormDataContent = new MultipartFormDataContent();
foreach (var formKey in Request.Form.Keys)
{
var content = Request.Form[formKey].FirstOrDefault();
if (content != null)
multipartFormDataContent.Add(new StringContent(content), formKey);
}
result = await httpClient.PostAsync(forwardUrl, multipartFormDataContent, cancellationToken);
}
return result;
}
private async Task<HttpResponseMessage> ForwardBody(string key, HttpClient httpClient, CancellationToken cancellationToken)
{
// we do not have direct access to Content, see: https://stackoverflow.com/questions/41508664/net-core-forward-a-local-api-form-data-post-request-to-remote-api
var requestMessage = Request.ToHttpRequestMessage();
return await httpClient.SendAsync(requestMessage, cancellationToken);
}

HttpClient with multiple proxies

How can one use HttpClient with a pipeline of multiple proxies?
A single proxy can be handled via HttpClientHandler:
HttpClient client1 = new HttpClient(new HttpClientHandler()
{
Proxy = new WebProxy()
{
Address = new Uri($"http://{proxyIp}:{proxyPort}"),
BypassProxyOnLocal = false,
UseDefaultCredentials = false
}
});
I want the requests to pass through multiple proxies.
I already tried subclassing DelegatingHandler like this:
public class ProxyDelegatingHandler : DelegatingHandler
{
public ProxyDelegatingHandler(string proxyIp, int proxyPort):
base(new HttpClientHandler()
{
Proxy = new WebProxy()
{
Address = new Uri($"http://{proxyIp}:{proxyPort}"),
BypassProxyOnLocal = false,
UseDefaultCredentials = false
}
})
{
}
protected override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request, CancellationToken cancellationToken)
{
return base.SendAsync(request, cancellationToken);
}
}
And passing the list to factory, but it throws an exception which is probably caused by incorrect implementation of ProxyDelegatingHandler:
var handlers = new List<DelegatingHandler>();
handlers.Add(new ProxyDelegatingHandler(ip1, port2));
handlers.Add(new ProxyDelegatingHandler(ip2, port2));
HttpClient client = HttpClientFactory.Create(handlers.ToArray())
HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Get, url);
var res = await client.SendAsync(requestMessage);
Exception:
The 'DelegatingHandler' list is invalid because the property 'InnerHandler' of 'CustomHandler' is not null. Parametername: handlers
Related Post: link

Azure web api Unauthorized 401

I have some code that used to call Azure Scheduler to get a token, then using that token, make restful calls. Works a treat.
So i decided to adopt the code into a new app but this time call my own web api hosted on azure. The API is registered in Active directory I have created a secret key etc. When i initiliaze my static httpclient it fetches a token succesfully.
But when i make a call to the API using the token for auth, the response is a 401 "unauthorized", below is the code.
public static class SchedulerHttpClient
{
const string SPNPayload = "resource={0}&client_id={1}&grant_type=client_credentials&client_secret={2}";
private static Lazy<Task<HttpClient>> _Client = new Lazy<Task<HttpClient>>(async () =>
{
string baseAddress = ConfigurationManager.AppSettings["BaseAddress"];
var client = new HttpClient();
client.BaseAddress = new Uri(baseAddress);
await MainAsync(client).ConfigureAwait(false);
return client;
});
public static Task<HttpClient> ClientTask => _Client.Value;
private static async Task MainAsync(HttpClient client)
{
string tenantId = ConfigurationManager.AppSettings["AzureTenantId"];
string clientId = ConfigurationManager.AppSettings["AzureClientId"];
string clientSecret = ConfigurationManager.AppSettings["AzureClientSecret"];
string token = await AcquireTokenBySPN(client, tenantId, clientId, clientSecret).ConfigureAwait(false);
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token); //TODO ssmith: const or localization
}
private static async Task<string> AcquireTokenBySPN(HttpClient client, string tenantId, string clientId, string clientSecret)
{
var payload = String.Format(SPNPayload,
WebUtility.UrlEncode(ConfigurationManager.AppSettings["ARMResource"]),
WebUtility.UrlEncode(clientId),
WebUtility.UrlEncode(clientSecret));
var body = await HttpPost(client, tenantId, payload).ConfigureAwait(false);
return body.access_token;
}
private static async Task<dynamic> HttpPost(HttpClient client, string tenantId, string payload)
{
var address = String.Format(ConfigurationManager.AppSettings["TokenEndpoint"], tenantId);
var content = new StringContent(payload, Encoding.UTF8, "application/x-www-form-urlencoded");
using (var response = await client.PostAsync(address, content).ConfigureAwait(false))
{
if (!response.IsSuccessStatusCode)
{
Console.WriteLine("Status: {0}", response.StatusCode);
Console.WriteLine("Content: {0}", await response.Content.ReadAsStringAsync().ConfigureAwait(false));
}//TODO: start removing tests
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsAsync<dynamic>().ConfigureAwait(false);
}
}
}
The above code is the class that creates a httpclient and gets its authorization.
public virtual async Task<T> GetAsync(string apiURL)
{
try
{
_client = await SchedulerHttpClient.ClientTask;
var response = await _client.GetAsync(apiURL);
response.EnsureSuccessStatusCode();
var responseContent = await response.Content.ReadAsAsync<T>().ConfigureAwait(false);
return responseContent;
}
catch (Exception e)
{
return default(T);
}
}
The above code is a quick lift of my old code simply to test if i can get any results. but as stated it returns a 401.
My question is, is my old code to get authorization incorrect?
<add key="ARMResource" value="https://management.core.windows.net/" />
<add key="TokenEndpoint" value="https://login.windows.net/{0}/oauth2/token" />
<add key="BaseAddress" value="https://mysite.azurewebsites.net" />
As suspected, This particular issue was cause by the incorrect "ARMresource" in the case of a web api it required me to change it to the client id.
Source of answer
Seems my issue was the same, however i suspect i may be able to omit the resource entirely from my SPNPayload string.

Unity app not responding and get "request time out" when call to WebAPI

I'm having a Unity app call to a Like() method in DLL, which connect to a WebAPI to do the job. However, when I debug the application and code run to
string liked = SocialConnector.LikePost(token, postID);
It got stuck there, unity became not responding and after work normal again, the debug show Request time out.
Below are my detail code in DLL
public static String LikePost(String token, String postID)
{
HttpCommon common = new HttpCommon();
string url = Constant.ApiURL + Constant.API_LINK_POST_LIKE_UNLIKE + "?postID=" + postID;
String result = common.HttpPost<String>(url, token);
return result;
}
Code in HTTPCommon
public T HttpPost<T>(String url, String token)
{
var request = (HttpWebRequest)WebRequest.Create(url);
//var data = Encoding.ASCII.GetBytes(postData);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
//request.ContentLength = data.Length;
request.Headers["Authorization"] = "Bearer " + token;
var stream = request.GetRequestStream();
var response = (HttpWebResponse)request.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
try
{
var responseData = JsonConvert.DeserializeObject<T>(responseString);
return responseData;
}
catch (Exception e)
{
throw new Exception(responseString);
}
}
Error log:
WebException: The request timed out
System.Net.HttpWebRequest.EndGetResponse (IAsyncResult asyncResult)
System.Net.HttpWebRequest.GetResponse ()
GSEP_DLL.Connectors.HttpCommon.HttpPost[String] (System.String url, System.String token)
GSEP_DLL.Connectors.SocialConnector.LikePost (System.String token, System.String postID)
Like.onClick () (at Assets/Scripts/Like.cs:39)
UnityEngine.Events.InvokableCall.Invoke (System.Object[] args) (at C:/buildslave/unity/build/Runtime/Export/UnityEvent.cs:110)
UnityEngine.Events.InvokableCallList.Invoke (System.Object[] parameters) (at C:/buildslave/unity/build/Runtime/Export/UnityEvent.cs:574)
UnityEngine.Events.UnityEventBase.Invoke (System.Object[] parameters) (at C:/buildslave/unity/build/Runtime/Export/UnityEvent.cs:716)
UnityEngine.Events.UnityEvent.Invoke () (at C:/buildslave/unity/build/Runtime/Export/UnityEvent_0.cs:53)
UnityEngine.UI.Button.Press () (at C:/buildslave/unity/build/Extensions/guisystem/UnityEngine.UI/UI/Core/Button.cs:35)
UnityEngine.UI.Button.OnPointerClick (UnityEngine.EventSystems.PointerEventData eventData) (at C:/buildslave/unity/build/Extensions/guisystem/UnityEngine.UI/UI/Core/Button.cs:44)
UnityEngine.EventSystems.ExecuteEvents.Execute (IPointerClickHandler handler, UnityEngine.EventSystems.BaseEventData eventData) (at C:/buildslave/unity/build/Extensions/guisystem/UnityEngine.UI/EventSystem/ExecuteEvents.cs:52)
UnityEngine.EventSystems.ExecuteEvents.Execute[IPointerClickHandler] (UnityEngine.GameObject target, UnityEngine.EventSystems.BaseEventData eventData, UnityEngine.EventSystems.EventFunction`1 functor) (at C:/buildslave/unity/build/Extensions/guisystem/UnityEngine.UI/EventSystem/ExecuteEvents.cs:269)
UnityEngine.EventSystems.EventSystem:Update()
Update: Problem solved. The WebAPI return type of bool but my DLL forced to return String.
Problem solved. The WebAPI return type of bool but my DLL forced to return String.