Here is my code for google sign in with azure.
I have set up everything needed to use the google sign in including my authorized callback urls
https://myAzureSite.azurewebsites.net/.auth/login/google/callback
and authorized javascript origins
https://myAzureSite.azurewebsites.net
I have also followed the instructions and enabled the social api and put the client id and client secret into the azure authentication settings for google. The content security policy meta tag is also there in my index file.
After researching some more I found this error on my application logs... something about the input not being valid
Application logs
2017-07-19T16:09:28 Welcome, you are now connected to log-streaming service.
2017-07-19T16:09:36 PID[5300] Critical System.FormatException: The input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding characters, or an illegal character among the padding characters.
at System.Convert.FromBase64_Decode(Char* startInputPtr, Int32 inputLength, Byte* startDestPtr, Int32 destLength)
at System.Convert.FromBase64CharPtr(Char* inputPtr, Int32 inputLength)
at System.Convert.FromBase64String(String s)
at Microsoft.Azure.AppService.Authentication.ModuleUtils.ParseKeyString(String keyString)
at Microsoft.Azure.AppService.Authentication.CryptoHelper.get_Default()
at Microsoft.Azure.AppService.Authentication.IdentityProviderBase.<RedirectToLoginPageAsync>d__6.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.Azure.AppService.Authentication.IdentityProviderBase.<TryHandleProtocolRequestAsync>d__0.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(Task task)
at Microsoft.Azure.AppService.Authentication.EasyAuthModule.<OnBeginRequestAsync>d__0.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.Azure.AppService.Authentication.HttpModuleDispatcher.<DispatchAsync>d__13.MoveNext()
2017-07-19T16:09:36 PID[5300] Information Sending response: 500.79 Internal Server Error
2017-07-19 16:09:03 SCANNIN GET /.auth/login/google session_mode=token&X-ARR-LOG-ID=a0c71b7f-1ba1-4c70-b28e-053c0e2792ac 443 - 205.185.209.163 Mozilla/5.0+Google ARRAffinity=9d2a904ebce60f45ea468ce406b610510a42678c8d3f0cd761756aef31b3c514 - scannin.azurewebsites.net 500 79 2147500037 329 1039 15
2017-07-19 16:09:10 ~1SCANNIN GET /Microsoft.Mobile.Management/tables api-version=2014-11-01&_=1500480350552&X-ARR-LOG-ID=4340640e-40e4-40ea-97c0-dd4ead98d0ce 443 - 70.37.57.58 Mozilla/5.0+(Macintosh;+Intel+Mac+OS+X+10_12_5)+AppleWebKit/603.2.4+(KHTML,+like+Gecko)+Version/10.1.1+Safari/603.2.4 - https://management.azure.com/subscriptions/bd5771bb-237c-4508-bf66-419541298fd0/resourceGroups/ScanIn/providers/Microsoft.Web/sites/ScannIn/extensions/Microsoft.Mobile.Management/tables?api-version=2014-11-01&_=1500480350552 scannin.scm.azurewebsites.net 200 0 0 1715 2611 31
login code
client.login("google").done(function (results) {
alert("You are now logged in as: " + results.userId);
}, function (err) {
alert("Error: " + err);
});
Silly mistake on my part, this past month I have been trying to add custom authentication to my application but with no avail. During this process I added a website signing key to my application settings. This is what caused the error.
Related
I started this process back in November with this question: How to migrate an existing SSRS setup to a new server?
I was able to migrate everything to the new server without any issues. There were no errors on any of the tabs in the Report Server Configuration Manager. And the Reporting Service started with out errors. I was able navigate the expected "directory" structure through the web interface. However, when I tried to execute a report, upload a report or manage the report I received an error dialog that read "An error has occurred. Something went wrong. Please try again later." This isn't the most helpful error, so I went to the Report Service error log and found this exception in the log:
Microsoft.ReportingServices.Portal.WebHost!reportserverwebapp!4a!03/02/2019-12:44:39:: e ERROR: [c4tdsgh8]: OData exception occurred: System.Net.WebException: Unable to connect to the remote server ---> System.Net.Sockets.SocketException: No connection could be made because the target machine actively refused it 127.0.0.1:443
at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress)
at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Exception& exception)
--- End of inner exception stack trace ---
at System.Net.HttpWebRequest.GetRequestStream(TransportContext& context)
at System.Net.HttpWebRequest.GetRequestStream()
at System.Web.Services.Protocols.SoapHttpClientProtocol.Invoke(String methodName, Object[] parameters)
at Microsoft.SqlServer.ReportingServices2010.ReportingService2010.IsSSLRequired()
at Microsoft.SqlServer.ReportingServices2010.RSConnection2010.SetConnectionProtocol()
at Microsoft.SqlServer.ReportingServices2010.RSConnection2010.SoapMethodWrapper`1.ExecuteMethod(Boolean setConnectionProtocol)
at Microsoft.SqlServer.ReportingServices2010.RSConnection2010.SoapMethodWrapper`1.ExecuteMethod()
at Microsoft.SqlServer.ReportingServices2010.RSConnection2010.SetItemDefinition(String itemPath, Byte[] definition, Property[] properties)
at Microsoft.ReportingServices.Portal.Services.SoapProxy.SoapRS2010Proxy.<>c__DisplayClass14.<SetItemDefinition>b__13()
at Microsoft.ReportingServices.Portal.Services.SoapProxy.SoapAuthenticationHelper.ExecuteWithWindowsAuth[TReturn](SoapHttpClientProtocol soapClient, IPrincipal userPrincipal, Func`1 func)
at Microsoft.ReportingServices.Portal.Services.SoapProxy.SoapAuthenticationHelper.ExecuteWithCorrespondingAuthMechanism[TReturn](SoapHttpClientProtocol soapClient, IPrincipal userPrincipal, Func`1 func)
at Microsoft.ReportingServices.Portal.Services.SoapProxy.SoapRS2010Proxy.SetItemDefinition(IPrincipal userPrincipal, String itemPath, Byte[] definition, Property[] properties)
at Microsoft.ReportingServices.Portal.Repositories.CatalogItemRepository.UpdateReport(IPrincipal userPrincipal, String origItemPath, Report item, Boolean renameOrMove, String[] delta)
at Microsoft.ReportingServices.Portal.Repositories.CatalogItemRepository.Update(IPrincipal userPrincipal, Guid key, CatalogItem catalogItem, String[] delta)
at Microsoft.ReportingServices.Portal.ODataWebApi.V1.Controllers.CatalogItemsController.PutEntity(String key, CatalogItem entity)
at Microsoft.ReportingServices.Portal.ODataWebApi.V1.Controllers.Reflection.EntitySetReflectionODataController`1.Put(ODataPath oDataPath, T value)
at lambda_method(Closure , Object , Object[] )
at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClass10.<GetExecutor>b__9(Object instance, Object[] methodParameters)
at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ExecuteAsync(HttpControllerContext controllerContext, IDictionary`2 arguments, CancellationToken cancellationToken)
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Web.Http.Controllers.ApiControllerActionInvoker.<InvokeActionAsyncCore>d__0.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Web.Http.Controllers.ActionFilterResult.<ExecuteAsync>d__2.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Web.Http.Controllers.ExceptionFilterResult.<ExecuteAsync>d__0.MoveNext().
I spent a few hours looking this error up with no solution. It could be that I was pretty fried and I missed something, but any guidance would be appreciated.
You may find its faster to create a SSRS project in SSDT, import the reports and redeploy them. You may have to recreate the data sources but in my experience this is the fastest way to get it done.
I am attempting to integrate Ping Federate as an external OIDC provider for my IdentityServer4 instance. When I initiate the external login flow I am getting the following error:
System.Exception: Correlation failed.
at Microsoft.AspNetCore.Authentication.RemoteAuthenticationHandler`1.<HandleRequestAsync>d__12.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at IdentityServer4.Hosting.FederatedSignOut.AuthenticationRequestHandlerWrapper.<HandleRequestAsync>d__6.MoveNext() in C:\local\identity\server4\IdentityServer4\src\IdentityServer4\Hosting\FederatedSignOut\AuthenticationRequestHandlerWrapper.cs:line 38
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.<Invoke>d__6.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.AspNetCore.Cors.Infrastructure.CorsMiddleware.<Invoke>d__7.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at IdentityServer4.Hosting.BaseUrlMiddleware.<Invoke>d__3.MoveNext() in C:\local\identity\server4\IdentityServer4\src\IdentityServer4\Hosting\BaseUrlMiddleware.cs:line 43
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.<Invoke>d__7.MoveNext()
I'm kind of stumped on why FederatedSignOut is even being called. Any ideas on what I may be missing here?
Here is the AddAuthentication configuration:
services.AddOidcStateDataFormatterCache();
services.AddAuthentication()
.AddOpenIdConnect("ping", "Ping Federate", options =>
{
options.SignInScheme = IdentityServerConstants.ExternalCookieAuthenticationScheme;
options.SignOutScheme = IdentityServerConstants.SignoutScheme;
options.Authority = "https://ping.domain.com/";
options.ClientId = "IdentityServer4";
options.ClientSecret = "IdentityServer4";
options.TokenValidationParameters = new TokenValidationParameters
{
NameClaimType = "name",
RoleClaimType = "role"
};
});
Add this in the configuration in startup.cs. Its an issue with going from http to https.
app.UseForwardedHeaders(new ForwardedHeadersOptions
{
ForwardedHeaders = ForwardedHeaders.XForwardedProto
});
We are using IdentityServer4("http://docs.identityserver.io/en/release/quickstarts/0_overview.html") with EntityFrameworkCore to store operational and configuration data. To add signing credentials we are using x509 self signed certificates. We have used following command to create x509 self signed certificate:makecert -r -pe -n "CN=CertName_IdentityServer" -b 01/01/2015 -e 01/01/2039 -eku 1.3.6.1.5.5.7.3.3 -sky signature -a sha256 -len 2048 identityserver.cer. And add this certificate as embedded source in the solution.
Here is our startup.cs file:
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<IConfiguration>(Configuration);
//connection string
string connectionString = Configuration.GetConnectionString("IdentityServer");
var migrationsAssembly = typeof(Startup).GetTypeInfo().Assembly.GetName().Name;
ConfigureSigningCerts(services);
services.AddIdentityServer()
// this adds the config data from DB (clients, resources)
.AddConfigurationStore(options =>
{
options.ConfigureDbContext = builder =>
builder.UseSqlServer(connectionString,
sql => sql.MigrationsAssembly(migrationsAssembly));
}) // this adds the operational data from DB (codes, tokens, consents)
.AddOperationalStore(options =>
{
options.ConfigureDbContext = builder =>
builder.UseSqlServer(connectionString,
sql => sql.MigrationsAssembly(migrationsAssembly));
// this enables automatic token cleanup. this is optional.
options.EnableTokenCleanup = true;
options.TokenCleanupInterval = 30;
});
}
private static void ConfigureSigningCerts(IServiceCollection services)
{
var assembly = typeof(Startup).GetTypeInfo().Assembly;
/*
* IdentityServer.WebApi\
* Certificates\
* identityserver.cer
*
* {assembly name}.{directory}.{file name}
*/
using (Stream resource = assembly.GetManifestResourceStream("IdentityServer.WebApi.Certificates.identityserver.cer"))
using (var reader = new BinaryReader(resource))
{
var signingCert = new X509Certificate2(reader.ReadBytes((int)resource.Length));
var keys = new List<SecurityKey>();
if (signingCert == null) throw new InvalidOperationException("No valid signing certificate could be found.");
var signingCredential = new SigningCredentials(new X509SecurityKey(signingCert), "RS256");
services.AddSingleton<ISigningCredentialStore>(new DefaultSigningCredentialsStore(signingCredential));
var validationCredential = new SigningCredentials(new X509SecurityKey(signingCert), "RS256");
keys.Add(validationCredential.Key);
services.AddSingleton<IValidationKeysStore>(new DefaultValidationKeysStore(keys));
}
}
When we execute the application on local host discovery endpoint works fine but when called connect/token endpoint we got the following error message:
crit: IdentityServer4.Hosting.IdentityServerMiddleware[0]
Unhandled exception: System.InvalidOperationException: IDX10638: Cannot created the SignatureProvider, 'key.HasPrivateKey' is false, cannot create signatures. Key: Microsoft.IdentityModel.Tokens.X509SecurityKey.
at Microsoft.IdentityModel.Tokens.AsymmetricSignatureProvider..ctor(SecurityKey key, String algorithm, Boolean willCreateSignatures)
at Microsoft.IdentityModel.Tokens.CryptoProviderFactory.CreateSignatureProvider(SecurityKey key, String algorithm, Boolean willCreateSignatures)
at Microsoft.IdentityModel.Tokens.CryptoProviderFactory.CreateForSigning(SecurityKey key, String algorithm)
at System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.CreateEncodedSignature(String input, SigningCredentials signingCredentials)
at System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.WriteToken(SecurityToken token)
at IdentityServer4.Services.DefaultTokenCreationService.CreateJwtAsync(JwtSecurityToken jwt) in C:\local\identity\server4\IdentityServer4\src\IdentityServer4\Services\DefaultTokenCreationService.cs:line 209
at IdentityServer4.Services.DefaultTokenCreationService.<CreateTokenAsync>d__4.MoveNext() in C:\local\identity\server4\IdentityServer4\src\IdentityServer4\Services\DefaultTokenCreationService.cs:line 67
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at IdentityServer4.Services.DefaultTokenService.<CreateSecurityTokenAsync>d__9.MoveNext() in C:\local\identity\server4\IdentityServer4\src\IdentityServer4\Services\DefaultTokenService.cs:line 210
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at IdentityServer4.ResponseHandling.TokenResponseGenerator.<CreateAccessTokenAsync>d__14.MoveNext() in C:\local\identity\server4\IdentityServer4\src\IdentityServer4\ResponseHandling\TokenResponseGenerator.cs:line 313
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at IdentityServer4.ResponseHandling.TokenResponseGenerator.<ProcessTokenRequestAsync>d__13.MoveNext() in C:\local\identity\server4\IdentityServer4\src\IdentityServer4\ResponseHandling\TokenResponseGenerator.cs:line 249
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at IdentityServer4.ResponseHandling.TokenResponseGenerator.<ProcessAsync>d__7.MoveNext() in C:\local\identity\server4\IdentityServer4\src\IdentityServer4\ResponseHandling\TokenResponseGenerator.cs:line 84
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at IdentityServer4.Endpoints.TokenEndpoint.<ProcessTokenRequestAsync>d__7.MoveNext() in C:\local\identity\server4\IdentityServer4\src\IdentityServer4\Endpoints\TokenEndpoint.cs:line 98
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at IdentityServer4.Endpoints.TokenEndpoint.<ProcessAsync>d__6.MoveNext() in C:\local\identity\server4\IdentityServer4\src\IdentityServer4\Endpoints\TokenEndpoint.cs:line 70
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at IdentityServer4.Hosting.IdentityServerMiddleware.<Invoke>d__3.MoveNext() in C:\local\identity\server4\IdentityServer4\src\IdentityServer4\Hosting\IdentityServerMiddleware.cs:line 54
crit: IdentityServer4.Hosting.IdentityServerMiddleware[0]
Unhandled exception: System.InvalidOperationException: IDX10638: Cannot created the SignatureProvider, 'key.HasPrivateKey' is false, cannot create signatures. Key: Microsoft.IdentityModel.Tokens.X509SecurityKey.
at Microsoft.IdentityModel.Tokens.AsymmetricSignatureProvider..ctor(SecurityKey key, String algorithm, Boolean willCreateSignatures)
at Microsoft.IdentityModel.Tokens.CryptoProviderFactory.CreateSignatureProvider(SecurityKey key, String algorithm, Boolean willCreateSignatures)
at Microsoft.IdentityModel.Tokens.CryptoProviderFactory.CreateForSigning(SecurityKey key, String algorithm)
at System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.CreateEncodedSignature(String input, SigningCredentials signingCredentials)
at System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.WriteToken(SecurityToken token)
at IdentityServer4.Services.DefaultTokenCreationService.CreateJwtAsync(JwtSecurityToken jwt) in C:\local\identity\server4\IdentityServer4\src\IdentityServer4\Services\DefaultTokenCreationService.cs:line 209
at IdentityServer4.Services.DefaultTokenCreationService.<CreateTokenAsync>d__4.MoveNext() in C:\local\identity\server4\IdentityServer4\src\IdentityServer4\Services\DefaultTokenCreationService.cs:line 67
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at IdentityServer4.Services.DefaultTokenService.<CreateSecurityTokenAsync>d__9.MoveNext() in C:\local\identity\server4\IdentityServer4\src\IdentityServer4\Services\DefaultTokenService.cs:line 210
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at IdentityServer4.ResponseHandling.TokenResponseGenerator.<CreateAccessTokenAsync>d__14.MoveNext() in C:\local\identity\server4\IdentityServer4\src\IdentityServer4\ResponseHandling\TokenResponseGenerator.cs:line 313
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at IdentityServer4.ResponseHandling.TokenResponseGenerator.<ProcessTokenRequestAsync>d__13.MoveNext() in C:\local\identity\server4\IdentityServer4\src\IdentityServer4\ResponseHandling\TokenResponseGenerator.cs:line 249
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at IdentityServer4.ResponseHandling.TokenResponseGenerator.<ProcessAsync>d__7.MoveNext() in C:\local\identity\server4\IdentityServer4\src\IdentityServer4\ResponseHandling\TokenResponseGenerator.cs:line 84
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at IdentityServer4.Endpoints.TokenEndpoint.<ProcessTokenRequestAsync>d__7.MoveNext() in C:\local\identity\server4\IdentityServer4\src\IdentityServer4\Endpoints\TokenEndpoint.cs:line 98
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at IdentityServer4.Endpoints.TokenEndpoint.<ProcessAsync>d__6.MoveNext() in C:\local\identity\server4\IdentityServer4\src\IdentityServer4\Endpoints\TokenEndpoint.cs:line 70
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at IdentityServer4.Hosting.IdentityServerMiddleware.<Invoke>d__3.MoveNext() in C:\local\identity\server4\IdentityServer4\src\IdentityServer4\Hosting\IdentityServerMiddleware.cs:line 54
It looks like if you use a file you may need to do an additional step and assign a password to allow the private key to be accessed.
This should hopefully help: How to create a self signed certificate with the private key inside in a file in one simple step?
An alternative is to generate the cert in the local machine certificate store and then export it via the certificate management MMC snap-in.
From Powershell (run Powershell as administrator):
$cert = New-SelfSignedCertificate -DnsName yourSiteHere.com -type Custom -CertStoreLocation cert:\localmachine\my -KeyExportPolicy Exportable
With the above command Issuer becomes yourSiteHere and the expiration date is the default of one year out. It will also have RSA keys of length 2048.
You can then export the cert using the certmgr utility (there are also more commands in Powershell to export as well which I haven't used yet).
See these links for more info:
https://www.petri.com/create-self-signed-certificate-using-powershell
https://learn.microsoft.com/en-us/powershell/module/pkiclient/new-selfsignedcertificate?view=win10-ps
Now, in IdentityServer4, I extended the IIdentityServerBuilder class to provide a method for cert binding from that type of file - very quickly, if you have a static class, and its methods take a parameter of form "this someClass", then it's an "extension". You can extend any class, even those standard classes internal to C# (like string, etc). If you do this, your methods will also come up with Intellisense when you type the period after that class or variables of that type. This means that I have access to my method from the builder at startup (you just need to put a using to the extension class's namespace in Startup.cs):
public static class SigningCredentialExtension
{
public static IIdentityServerBuilder GetCertFromAzure(this IIdentityServerBuilder builder)
{
//Note: in order for the certificate to be visible to the app,
//an application setting "WEBSITE_LOAD_CERTIFICATES" with the value
//of your SSL cert's thumbprint must be added to your IdentityServer
//webapp on Azure.
var thumbprint = "your cert's thumbprint";
var store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
store.Open(OpenFlags.ReadOnly);
var certs = store.Certificates.Find(X509FindType.FindByThumbprint,
certThumbprint, true);
if (certs.Count > 0)
{
X509Certificate2 cert =
new X509Certificate2(certs[0].Export(X509ContentType.Pfx,
"your cert's password"));
builder.AddSigningCredential(cert);
builder.AddValidationKey(cert);
}
return builder;
}
public static IIdentityServerBuilder GetCertFromEmbeddedProjectFile(
IIdentityServerBuilder builder)
{
var assembly = Assembly.GetExecutingAssembly();
var fileName = "Your.Project.Namespace.FileName.fileExtension";
using (Stream stream = assembly.GetManifestResourceStream(resourceName))
{
Byte[] raw = new Byte[stream.Length];
for (Int32 i = 0; i < stream.Length; i++)
{
raw[i] = (Byte)stream.ReadByte();
}
X509Certificate2 cert = new X509Certificate2(raw, password);
builder.AddSigningCredential(cert);
builder.AddValidationKey(cert);
}
return builder;
}
}
So - include the above class in your project, make sure that Startup.cs can see it (include a using if necessary), get rid of your ConfigureSigningCerts() method, and after your line "services.AddIdentityServer()" type a '.' and you'll see the extension methods in the list. Use the method you want. You don't need to specify a parameter, the method will automatically get the builder. The builder will be returned for the later methods after it.
I've been experiencing some odd issues with my application that I am not sure how to go about tracking down because it is so random. I was wondering if there may be any ideas based on the stack trace below.
Here is some quick bullet points:
Issue seems to be related to code in the View (.cshtml)
It RANDOMLY appears and it has something to do with the session cookie because if you try from another computer then it is no issue or if you clear your cache it is no issue
My GetUserByIdentifier is wrapped in a try{}catch{} which returns NULL if we enter the catch{}.. which should redirect to the login screen.
Could this be something internal causing the error message? This unhandled exception can even happen on my login.cshtml page which doesn't even have any code in the view.
The error message:
Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index]
System.ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument argument, ExceptionResource resource) +72
System.SZArrayHelper.get_Item(Int32 index) +13816967
Nancy.ViewEngines.Razor.RazorViewEngine.GetLineNumber(Int32 startLineIndex, IReadOnlyList`1 compilationSource) +39
Nancy.ViewEngines.Razor.<>c__DisplayClass19_0.<BuildErrorMessages>b__0(Diagnostic error) +118
System.Linq.WhereSelectArrayIterator`2.MoveNext() +80
System.Linq.WhereEnumerableIterator`1.MoveNext() +51
System.Linq.Buffer`1..ctor(IEnumerable`1 source) +250
System.Linq.Enumerable.ToArray(IEnumerable`1 source) +106
Nancy.ViewEngines.Razor.RazorViewEngine.BuildErrorMessages(IEnumerable`1 errors, IList`1 templateLines, IReadOnlyList`1 compilationSource) +272
Nancy.ViewEngines.Razor.RazorViewEngine.BuildErrorMessage(EmitResult result, ViewLocationResult viewLocationResult, String sourceCode) +366
Nancy.ViewEngines.Razor.<>c__DisplayClass14_0.<GenerateRazorViewFactory>b__0() +49
Nancy.ViewEngines.Razor.RazorViewEngine.GetViewInstance(ViewLocationResult viewLocationResult, IRenderContext renderContext, Object model) +1064
Nancy.ViewEngines.Razor.<>c__DisplayClass9_0.<RenderView>b__0(Stream stream) +4700
Nancy.Hosting.Aspnet.<ProcessRequest>d__2.MoveNext() +381
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +13891908
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +61
System.Web.TaskAsyncHelper.EndTask(IAsyncResult ar) +69
System.Web.CallHandlerExecutionStep.OnAsyncHandlerCompletion(IAsyncResult ar) +178
All the examples I see about obtaining an access token with which to access the Azure Key Vault involve using a ClientId and ClientSecret to request a token for the well known https://vault.azure.net resource.
This works fine...but I want to be able to use integrated security to obtain an access token which which to access the key vault.
For example, I have
const string VaultResource = "https://vault.azure.net";
var context = new AuthenticationContext(myTenantAuthority, false);
// using integrated auth
var token1 = await context.AcquireTokenAsync(VaultResource, nativeAppClientId, new UserCredential());
// OR interactive
var token2 = context.AcquireToken(VaultResource, nativeAppClientId, new Uri("https://localhost"),
PromptBehavior.Auto, new UserIdentifier(UserPrincipal.Current.UserPrincipalName, UserIdentifierType.RequiredDisplayableId));
Both of these attempts fail. The first one says
Microsoft.IdentityModel.Clients.ActiveDirectory.AdalServiceException occurred
ErrorCode=invalid_grant
HResult=-2146233088
Message=AADSTS65001: The user or administrator has not consented to use the application with ID '306d0ff4-0f32-4c38-bdb9-4ea500000000'. Send an interactive authorization request for this user and resource.
Trace ID: 2ca2fb3f-3931-4868-b176-700f29158a3a
Correlation ID: 39875bc5-cb1c-4a62-925d-7448d8716f30
Timestamp: 2016-02-23 08:51:45Z
Source=Microsoft.IdentityModel.Clients.ActiveDirectory
StatusCode=400
StackTrace:
at Microsoft.IdentityModel.Clients.ActiveDirectory.HttpHelper.<SendPostRequestAndDeserializeJsonResponseAsync>d__0`1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.IdentityModel.Clients.ActiveDirectory.AcquireTokenHandlerBase.<SendHttpMessageAsync>d__15.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
And the second:
Microsoft.IdentityModel.Clients.ActiveDirectory.AdalServiceException occurred
ErrorCode=access_denied
HResult=-2146233088
Message=AADSTS65005: The client application has requested access to resource 'https://vault.azure.net'. This request has failed because the client has not specified this resource in its requiredResourceAccess list.
Trace ID: 5652658c-54bf-4880-bcc8-dea822a4b10b
Correlation ID: 1f97c7c0-858f-4542-9936-4a5114a93cc0
Timestamp: 2016-02-23 08:36:17Z
Source=Microsoft.IdentityModel.Clients.ActiveDirectory
StatusCode=0
StackTrace:
at Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext.RunAsyncTask[T](Task`1 task)
How do I update the requiredResourceAccessList?
UPDATE: Here is how the application is configured
You may need to set delegated permissions. Have a look here https://azure.microsoft.com/en-gb/documentation/articles/active-directory-integrating-applications/
Also, you might want to consider authenticating using a certificate. See A more secure way to use key vault