When I generate public key by using ECDH_KeyGeneration.getPublicKey() in robovm library.
it throws an exception - NoSuchMethodException.
This problem occurred in Android Q only . till android pie it is working fine.
X9ECParameters ecp = SECNamedCurves.getByName("secp256r1");
ECDomainParameters domainParams = new ECDomainParameters(ecp.getCurve(),
ecp.getG(), ecp.getN(), ecp.getH(),
ecp.getSeed());
// Generate a private key and a public key
AsymmetricCipherKeyPair keyPair;
ECKeyGenerationParameters keyGenParams = new ECKeyGenerationParameters(domainParams, new SecureRandom());
ECKeyPairGenerator generator = new ECKeyPairGenerator();
generator.init(keyGenParams);
keyPair = generator.generateKeyPair();
ECPrivateKeyParameters privateKey = (ECPrivateKeyParameters) keyPair.getPrivate();
ECPublicKeyParameters publicKey = ((ECPublicKeyParameters) keyPair.getPublic());
mPrivateKeyBytes2 = privateKey.getD().toByteArray();
String str = Hex.toHexString(publicKey.getQ().getEncoded(false));
Lcom/android/org/bouncycastle/asn1/sec/SECNamedCurves; or its super classes (declaration of 'com.android.org.bouncycastle.asn1.sec.SECNamedCurves' appears in /apex/com.android.runtime/javalib/bouncycastle.jar)
at projects.athansys.com.athandoctorassist.helper.ECDH_KeyGeneration.getPublicKey(ECDH_KeyGeneration.java:25)
The following code will help you, you can generate algorithm using bouncy castle library:
private static ECDsa GetEllipticCurveAlgorithm(string privateKey)
{
var keyParams = (ECPrivateKeyParameters)PrivateKeyFactory
.CreateKey(Convert.FromBase64String(privateKey));
var normalizedECPoint = keyParams.Parameters.G.Multiply(keyParams.D).Normalize();
return ECDsa.Create(new ECParameters
{
Curve = ECCurve.CreateFromValue(keyParams.PublicKeyParamSet.Id),
D = keyParams.D.ToByteArrayUnsigned(),
Q =
{
X = normalizedECPoint.XCoord.GetEncoded(),
Y = normalizedECPoint.YCoord.GetEncoded()
}
});
}
and generate the token in the following way:
var signatureAlgorithm = GetEllipticCurveAlgorithm(privateKey);
ECDsaSecurityKey eCDsaSecurityKey = new ECDsaSecurityKey(signatureAlgorithm)
{
KeyId = settings.Apple.KeyId
};
var handler = new JwtSecurityTokenHandler();
var token = handler.CreateJwtSecurityToken(
issuer: iss,
audience: AUD,
subject: new ClaimsIdentity(new List<Claim> { new Claim("sub", sub) }),
expires: DateTime.UtcNow.AddMinutes(5),
issuedAt: DateTime.UtcNow,
notBefore: DateTime.UtcNow,
signingCredentials: new SigningCredentials(eCDsaSecurityKey, SecurityAlgorithms.EcdsaSha256));
Related
I'm trying to send an HTTP request from .NET Core 3.1 REST API to another API but below Exception keep appeared Although I'm already added the Authentication Key :
The request was missing an Authentication Key. Please, refer to section "Authentication"
here is my code :
public class AppService
{
private readonly IHttpClientFactory _clientFactory;
string key = "key=llllll ......";
string webAPIKey = "......";
string Id = "......";
public AppService(IHttpClientFactory clientFactory) {
_clientFactory = clientFactory;
}
public async Task<string> sendBroadCastNotification()
{
Data _data = new Data();
_data.title = "test data Ttile";
_data.detail = "test data detail";
Notification _notification = new Notification();
_notification.title = "test notification Ttile";
_notification.body = "test notification body";
MyNotification NotifcationData = new MyNotification {
data=_data,
notification=_notification,
to= "/topics/all"
};
try {
var client = _clientFactory.CreateClient();
client.DefaultRequestHeaders.Add("project_id", Id );
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Authorization", key);
StringContent bodyOfRequest = new StringContent(System.Text.Json.JsonSerializer.Serialize(NotifcationData ), Encoding.UTF8, "application/json");
using var httpResponse =
await client.PostAsync("https://.......", bodyOfRequest);
var result = httpResponse.Content.ReadAsStringAsync().Result;
return result;
}
catch (Exception ex)
{
throw new System.ArgumentException(ex.Message.ToString(), "original");
}
//return null;
}
}
I found the answer here in this link:
I add the key by using the below line:
client.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", key);
the below way that I was trying to add the authorization header wasn't understandable as an authorization header :
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Authorization", key);
I have little problem with using Cloudinary, I can upload the images it works fine but I guess i cant get any response from Cloudinary. Suggestion? about required parameters
Handler
public async Task<Photo> Handle(Command request, CancellationToken cancellationToken)
{
var photoUploadResult = _photoAccessor.AddPhoto(request.File);
var photo = new Photo
{
Url = photoUploadResult.Url,
Id = photoUploadResult.PublicId
};
var success = await _context.SaveChangesAsync() > 0;
if (success) return photo;
throw new Exception("Problem saving changes");
}
Accessor
public PhotoUploadResult AddPhoto(IFormFile file)
{
var uploadResult = new ImageUploadResult();
if (file.Length > 0)
{
using (var stream = file.OpenReadStream())
{
var uploadParams = new ImageUploadParams
{
File = new FileDescription(file.FileName, stream)
};
uploadResult = _cloudinary.Upload(uploadParams);
}
}
if (uploadResult.Error != null)
throw new Exception(uploadResult.Error.Message);
return new PhotoUploadResult
{
PublicId = uploadResult.PublicId,
Url = uploadResult.SecureUri.AbsoluteUri
};
}
What do you get in response? Can you try:
string cloud_name = "<Cloud Name>";
string ApiKey = "<Api-Key>";
string ApiSecret = "<Api-Secret>";
Account account = new Account(cloud_name,ApiKey,ApiSecret);
Cloudinary cloudinary = new Cloudinary(account);
cloudinary.Api.Timeout = int.MaxValue;
var ImguploadParams = new ImageUploadParams()
{
File = new FileDescription(#"http://res.cloudinary.com/demo/image/upload/couple.jpg"),
PublicId = "sample",
Invalidate = true,
Overwrite = true
};
var ImguploadResult = cloudinary.Upload(ImguploadParams);
Console.WriteLine(ImguploadResult.SecureUri);
Is it possible to encrypt the assertion response with ITfoxtec Identity Saml2 (open source - https://itfoxtec.com/identitysaml2)? Haven't been able to find anything.
The GitHub site (https://github.com/ITfoxtec/ITfoxtec.Identity.Saml2) mentions decrypting but not encrypting. Doesn't seem to be any examples on encrypting either.
Any help is appreciated. Thanks.
In saml2postbinding class, replace BindInternal method with below code.
protected override Saml2PostBinding BindInternal(Saml2Request saml2RequestResponse, string messageName)
{
BindInternal(saml2RequestResponse);
var element1 = XmlDocument.CreateElement("saml2", "EncryptedAssertion", "urn:oasis:names:tc:SAML:2.0:assertion");
XmlDocument xmlDoc = new XmlDocument();
var assertionElements = XmlDocument.DocumentElement.SelectNodes($"//*[local-name()='{Saml2Constants.Message.Assertion}']");
var assertionElement = (assertionElements[0] as XmlElement).ToXmlDocument().DocumentElement;
var certificate = ITfoxtec.Identity.Saml2.Util.CertificateUtil.Load(#"F:\IT-FoxTec-Core Copy\ITfoxtec.Identity.Saml2-master (1)\ITfoxtec.Identity.Saml2-master\test\TestIdPCore\itfoxtec.identity.saml2.testwebappcore_Certificate.crt");
var wrappedAssertion = $#"<saml2:EncryptedAssertion xmlns:saml2=""urn:oasis:names:tc:SAML:2.0:assertion"">{assertionElement.OuterXml}</saml2:EncryptedAssertion>";
xmlDoc.LoadXml(wrappedAssertion);
var elementToEncrypt = (XmlElement)xmlDoc.GetElementsByTagName("Assertion", Saml2Constants.AssertionNamespace.OriginalString)[0];
element1.InnerXml = wrappedAssertion.ToXmlDocument().DocumentElement.SelectNodes($"//*[local-name()='{Saml2Constants.Message.Assertion}']")[0].OuterXml;
var element2 = wrappedAssertion.ToXmlDocument().DocumentElement;
var childNode = XmlDocument.GetElementsByTagName("Assertion", Saml2Constants.AssertionNamespace.OriginalString)[0];
XmlDocument.DocumentElement.RemoveChild(childNode);
var status = XmlDocument.DocumentElement[Saml2Constants.Message.Status, Saml2Constants.ProtocolNamespace.OriginalString];
XmlDocument.DocumentElement.InsertAfter(element1, status);
if (certificate == null) throw new ArgumentNullException(nameof(certificate));
var encryptedData = new EncryptedData
{
Type = EncryptedXml.XmlEncElementUrl,
EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncAES256Url)
};
var algorithm = true ? EncryptedXml.XmlEncRSAOAEPUrl : EncryptedXml.XmlEncRSA15Url;
var encryptedKey = new EncryptedKey
{
EncryptionMethod = new EncryptionMethod(algorithm),
};
var encryptedXml = new EncryptedXml();
byte[] encryptedElement;
using (var encryptionAlgorithm = new AesCryptoServiceProvider())
{
encryptionAlgorithm.KeySize = 256;
encryptedKey.CipherData = new CipherData(EncryptedXml.EncryptKey(encryptionAlgorithm.Key, (RSA)certificate.PublicKey.Key, true));
encryptedElement = encryptedXml.EncryptData(elementToEncrypt, encryptionAlgorithm, false);
}
encryptedData.CipherData.CipherValue = encryptedElement;
encryptedData.KeyInfo = new KeyInfo();
encryptedData.KeyInfo.AddClause(new KeyInfoEncryptedKey(encryptedKey));
EncryptedXml.ReplaceElement((XmlElement)xmlDoc.GetElementsByTagName("Assertion", Saml2Constants.AssertionNamespace.OriginalString)[0], encryptedData, false);
EncryptedXml.ReplaceElement((XmlElement)XmlDocument.GetElementsByTagName("Assertion", Saml2Constants.AssertionNamespace.OriginalString)[0], encryptedData, false);
if ((!(saml2RequestResponse is Saml2AuthnRequest) || saml2RequestResponse.Config.SignAuthnRequest) && saml2RequestResponse.Config.SigningCertificate != null)
{
Cryptography.SignatureAlgorithm.ValidateAlgorithm(saml2RequestResponse.Config.SignatureAlgorithm);
XmlDocument = XmlDocument.SignDocument(saml2RequestResponse.Config.SigningCertificate, saml2RequestResponse.Config.SignatureAlgorithm, CertificateIncludeOption, saml2RequestResponse.Id.Value);
}
PostContent = string.Concat(HtmlPostPage(saml2RequestResponse.Destination, messageName));
return this;
}
Here certificate is public key certificate for any relying party.
I m sorry to say that assertion response encryption is currently not supported.
You are Welcome to create an issue on the missing encryption funktionalitet.
If you implement the functionality please share the code.
I'm implementing the OAuth 2 refresh token with ASP.NET API2 and OWIN, the following code is my OAuthAuthorizationOptions
public static OAuthAuthorizationServerOptions AuthorizationServerOptions
{
get
{
if (_AuthorizationServerOptions == null)
{
_AuthorizationServerOptions = new OAuthAuthorizationServerOptions()
{
AuthenticationType = OAuthDefaults.AuthenticationType,
AllowInsecureHttp = true,
TokenEndpointPath = new PathString(AuthSettings.TokenEndpoint),
AuthorizeEndpointPath = new PathString(AuthSettings.AuthorizeEndpoint),
AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(AuthSettings.TokenExpiry),
Provider = new CustomOAuthAuthorizationServerProvider(AuthSettings.PublicClientId),
// TODO: Remove the dependency with Thinktecture.IdentityModel library here
AccessTokenFormat = new CustomJWTFormat(),
RefreshTokenProvider = new CustomRefreshTokenProvider()
};
}
return _AuthorizationServerOptions;
}
}
Here is my CustomRefreshTokenProvider class
public override Task CreateAsync(AuthenticationTokenCreateContext context)
{
var identifier = context.Ticket.Identity.FindFirst(System.Security.Claims.ClaimTypes.NameIdentifier);
if (identifier == null || string.IsNullOrEmpty(identifier.Value))
{
return Task.FromResult<object>(null);
}
var refreshToken = HashHelper.Hash(Guid.NewGuid().ToString("n"));
var tokenIssued = DateTime.UtcNow;
var tokenExpire = DateTime.UtcNow.AddSeconds(AuthSettings.RefreshTokenExpiry);
context.Ticket.Properties.IssuedUtc = tokenIssued;
context.Ticket.Properties.ExpiresUtc = tokenExpire;
context.Ticket.Properties.AllowRefresh = true;
var protectedTicket = context.SerializeTicket();
AuthService.AddUserRefreshTokenSession(
identifier.Value,
refreshToken,
tokenIssued,
tokenExpire,
protectedTicket);
context.SetToken(refreshToken);
return Task.FromResult<object>(null);
}
public override Task ReceiveAsync(AuthenticationTokenReceiveContext context)
{
var refToken = context.Token;
var protectedTicket = AuthService.GetProtectedTicket(refToken);
if (!string.IsNullOrEmpty(protectedTicket))
{
context.DeserializeTicket(protectedTicket);
}
return Task.FromResult<object>(null);
}
I have used postman to send POST request to the token endpoint as below
Postman refresh token
the server return 400 bad request status code.
I debugged and found that the context.DeserializeTicket(protectedTicket)
throw an Exception
Exception thrown: 'System.Security.Cryptography.CryptographicException' in System.Web.dll
I don't think it is the expiration issue because
the AuthSettings.RefreshTokenExpiry is 30 days from now.
I also tried to add Machine key to my web.config OAuth Refresh Token does not deserialize / invalid_grant
but it still not working.
Does anyone have an idea?
Any solutions will be highly appreciated.
Sorry for the late answered.
I have resolved this issue and end up with a solution that remove entirely Thinktecture.Identity out of my project, since it's somehow conflict with System.IdentityModel.Tokens.JWT.dll
Another solution if you still want to use Thinktecture.Identity is that downgrade System.IdentityModel.Tokens.JWT to v4.0.2.206221351 (this version worked for me, I haven't tested with another version).
Here is the code of CustomJWTFormat.cs
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.OAuth;
using MST.Service.Core.Logging;
using System;
using System.Security.Claims;
namespace MST.Service.Core.Auth
{
public class CustomJWTFormat : ISecureDataFormat
{
private byte[] _SymetricKey = null;
public CustomJWTFormat()
{
_SymetricKey = Convert.FromBase64String(AuthSettings.JwtTokenSecret);
}
///
/// Create jwt token
///
///
/// Token string
public string Protect(AuthenticationTicket data)
{
var tokenHandler = new System.IdentityModel.Tokens.JwtSecurityTokenHandler();
var now = DateTime.UtcNow;
System.IdentityModel.Tokens.JwtSecurityToken jwtSecurityToken = new System.IdentityModel.Tokens.JwtSecurityToken(
AuthSettings.Issuer,
AuthSettings.JwtAudiences,
data.Identity.Claims,
DateTime.UtcNow,
DateTime.UtcNow.AddMinutes(AuthSettings.TokenExpiry),
new System.IdentityModel.Tokens.SigningCredentials(
new System.IdentityModel.Tokens.InMemorySymmetricSecurityKey(_SymetricKey),
System.IdentityModel.Tokens.SecurityAlgorithms.HmacSha256Signature,
System.IdentityModel.Tokens.SecurityAlgorithms.Sha256Digest)
);
var token = tokenHandler.WriteToken(jwtSecurityToken);
return token;
}
public AuthenticationTicket Unprotect(string protectedText)
{
var tokenHandler = new System.IdentityModel.Tokens.JwtSecurityTokenHandler();
var validationParameters = new System.IdentityModel.Tokens.TokenValidationParameters()
{
RequireExpirationTime = true,
ValidateIssuer = true,
ValidateLifetime = true,
AuthenticationType = OAuthDefaults.AuthenticationType,
ValidIssuers = new string[] { AuthSettings.Issuer },
ValidAudiences = new string[] { AuthSettings.JwtAudiences },
ValidateAudience = true,
ValidateIssuerSigningKey = false,
IssuerSigningKey = new System.IdentityModel.Tokens.InMemorySymmetricSecurityKey(_SymetricKey)
};
System.IdentityModel.Tokens.SecurityToken securityToken = null;
ClaimsPrincipal principal = null;
try
{
principal = tokenHandler.ValidateToken(protectedText, validationParameters, out securityToken);
var validJwt = securityToken as System.IdentityModel.Tokens.JwtSecurityToken;
if (validJwt == null)
{
throw new ArgumentException("Invalid JWT");
}
}
catch (Exception ex)
{
LoggerManager.AuthLog.Error($"Parse token error: {ex.ToString()}");
return null;
}
// Validation passed. Return a valid AuthenticationTicket:
return new AuthenticationTicket(principal.Identity as ClaimsIdentity, new AuthenticationProperties());
}
}
}
and JWTBearerAuthenticationOptions (if you host Resource Server and Authorization Server in the same machine)
public static JwtBearerAuthenticationOptions JwtAuthenticationOptions
{
get
{
if (_JwtAuthenticationOptions == null)
{
_JwtAuthenticationOptions = new JwtBearerAuthenticationOptions()
{
//AuthenticationMode = Microsoft.Owin.Security.AuthenticationMode.Passive,
AuthenticationType = OAuthDefaults.AuthenticationType,
AllowedAudiences = new[] { AuthSettings.JwtAudiences },
IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[]
{
new SymmetricKeyIssuerSecurityTokenProvider(AuthSettings.Issuer, AuthSettings.JwtTokenSecret)
}
};
}
return _JwtAuthenticationOptions;
}
}
in Startup.cs just register middleware as usual
app.UseJwtBearerAuthentication(AuthenticationOptions.JwtAuthenticationOptions);
`loadconfig.SourceUris.Add(#"gs:\\planar-fulcrum-837\leadload-ip\01-
02-2013");`
Null object reference set to instance of an object
Here is the working sample for loading CSV file from cloud storage into Google Big Query.
Update variables such as "ServiceAccountEmail, KeyFileName, KeySecret, ProjectID, Dataset name and etc..
Add your table schema into this variable
TableSchema Schema = new TableSchema();
Here i am using single file loading, you can add N number of CSV file into this variable
System.Collections.Generic.IList<string> URIs = newSystem.Collections.Generic.List<string>();
URIs.Add(filePath);
Use this below code modify & work with it. Have a great day. (This solution i have found working more than 3 days).
using Google.Apis.Auth.OAuth2;
using System.IO;
using System.Threading;
using Google.Apis.Bigquery.v2;
using Google.Apis.Bigquery.v2.Data;
using System.Data;
using Google.Apis.Services;
using System;
using System.Security.Cryptography.X509Certificates;
namespace GoogleBigQuery
{
public class Class1
{
private static void Main()
{
try
{
String serviceAccountEmail = "SERVICE ACCOUNT EMAIL";
var certificate = new X509Certificate2(#"KEY FILE NAME & PATH", "KEY SECRET", X509KeyStorageFlags.Exportable);
// SYNTAX: var certificate=new X509Certificate2(KEY FILE PATH+NAME (Here it resides in Bin\Debug folder so only name is enough), SECRET KEY, X509KeyStorageFlags.Exportable);
ServiceAccountCredential credential = new ServiceAccountCredential(
new ServiceAccountCredential.Initializer(serviceAccountEmail)
{
Scopes = new[] { BigqueryService.Scope.Bigquery, BigqueryService.Scope.BigqueryInsertdata, BigqueryService.Scope.CloudPlatform, BigqueryService.Scope.DevstorageFullControl }
}.FromCertificate(certificate));
// Create and initialize the Bigquery service. Use the Project Name value
// from the New Project window for the ApplicationName variable.
BigqueryService Service = new BigqueryService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "APPLICATION NAME"
});
TableSchema Schema = new TableSchema();
TableFieldSchema F1 = new TableFieldSchema();
F1.Name = "COLUMN NAME";
F1.Type = "STRING";
F1.Mode = "REQUIRED";
TableFieldSchema F2 = new TableFieldSchema();
F1.Name = "COLUMN NAME";
F1.Type = "INTEGER";
F1.Mode = "NULLABLE";
//Add N number of fields as per your needs
System.Collections.Generic.IList<TableFieldSchema> FS = new System.Collections.Generic.List<TableFieldSchema>();
FS.Add(F1);
FS.Add(F2);
Schema.Fields = FS;
JobReference JR = JobUpload("PROJECT ID", "DATASET NAME", "TABLE NAME", #"gs://BUCKET NAME/FILENAME", Schema, "CREATE_IF_NEEDED", "WRITE_APPEND", '|', Service);
//SYNTAX JobReference JR = JobUpload(PROJECT ID, DATASET NAME, TABLE NAME, FULL PATH OF CSV FILE,FILENAME IN CLOUD STORAGE, TABLE SCHEMA, CREATE DISPOSITION, DELIMITER, BIGQUERY SERVICE);
while (true)
{
var PollJob = Service.Jobs.Get(JR.ProjectId, JR.JobId).Execute();
Console.WriteLine("Job status" + JR.JobId + ": " + PollJob.Status.State);
if (PollJob.Status.State.Equals("DONE"))
{
Console.WriteLine("JOB Completed");
Console.ReadLine();
return;
}
}
}
catch (Exception e)
{
Console.WriteLine("Error Occurred: " + e.Message);
}
Console.ReadLine();
}
public static JobReference JobUpload(string project, string dataset, string tableId, string filePath, TableSchema schema, string createDisposition, string writeDisposition, char delimiter, BigqueryService BigQueryService)
{
TableReference DestTable = new TableReference();
DestTable.ProjectId = project;
DestTable.DatasetId = dataset;
DestTable.TableId = tableId;
Job Job = new Job();
JobConfiguration Config = new JobConfiguration();
JobConfigurationLoad ConfigLoad = new JobConfigurationLoad();
ConfigLoad.Schema = schema;
ConfigLoad.DestinationTable = DestTable;
ConfigLoad.Encoding = "ISO-8859-1";
ConfigLoad.CreateDisposition = createDisposition;
ConfigLoad.WriteDisposition = writeDisposition;
ConfigLoad.FieldDelimiter = delimiter.ToString();
ConfigLoad.AllowJaggedRows = true;
ConfigLoad.SourceFormat = "CSV";
ConfigLoad.SkipLeadingRows = 1;
ConfigLoad.MaxBadRecords = 100000;
System.Collections.Generic.IList<string> URIs = new System.Collections.Generic.List<string>();
URIs.Add(filePath);
//You can add N number of CSV Files here
ConfigLoad.SourceUris = URIs;
Config.Load = ConfigLoad;
Job.Configuration = Config;
//set job reference (mainly job id)
JobReference JobRef = new JobReference();
Random r = new Random();
var JobNo = r.Next();
JobRef.JobId = "Job" + JobNo.ToString();
JobRef.ProjectId = project;
Job.JobReference = JobRef;
JobsResource.InsertRequest InsertMediaUpload = new JobsResource.InsertRequest(BigQueryService, Job, Job.JobReference.ProjectId);
var JobInfo = InsertMediaUpload.Execute();
return JobRef;
}
}
}