GithubHelp home page GithubHelp logo

azure-samples / active-directory-dotnet-webapp-webapi-multitenant-openidconnect Goto Github PK

View Code? Open in Web Editor NEW
66.0 71.0 48.0 29.82 MB

A sample .NET 4.5 MVC SaaS web app that signs-up and signs-in users from any Azure AD tenant, and calls the Azure AD Graph API.

C# 7.56% CSS 0.21% ASP 0.04% HTML 2.14% JavaScript 87.49% Roff 2.56%

active-directory-dotnet-webapp-webapi-multitenant-openidconnect's Introduction

active-directory-dotnet-webapp-webapi-multitenant-openidconnect's People

Contributors

acomsmpbot avatar bryanla avatar danieldobalian avatar dstrockis avatar jmprieur avatar kjyam98 avatar pataltimore avatar priyamohanram avatar vibronet avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

active-directory-dotnet-webapp-webapi-multitenant-openidconnect's Issues

SharePoint Online - Accessing site gives error 401-unauthorized.

When the code is received in ProcessCode function and then using the result.AccessToekn gives error "401-unanothroized".

I have given the all access to "O365 SharePoint". The App gets autheticated but using the authorization token received using the code doesn't allow to fetch site details like list, site title etc.

              AuthenticationResult result = await authContext.AcquireTokenByAuthorizationCodeAsync(
                   code, new Uri(Request.Url.GetLeftPart(UriPartial.Path)), credential);


               try
               {
                   string siteUrl = "https://svtestsite.sharepoint.com/sites/powerapps";
                   ClientContext ctx = new ClientContext(siteUrl);
                   ctx.ExecutingWebRequest +=
                          delegate(object oSender, WebRequestEventArgs webRequestEventArgs)
                          {
                              webRequestEventArgs.WebRequestExecutor.RequestHeaders["Authorization"] =
                                  "Bearer " + result.AccessToken; // accessToken;
                          };
                       ctx.Load(ctx.Web, p => p.Title);
                       ctx.ExecuteQuery();
                       Console.WriteLine(siteUrl);
                       Console.WriteLine(ctx.Web.Title);
               }
               catch (Exception ex)
               {
                   Console.WriteLine("Failure : " + ex.Message);
               }

Java Version

Any chance a java version will be added? Need to add support for Azure AD to an existing java app.

Thanks.

Clicking username results in Newtonsoft.Json.JsonReaderException

SignIn and click on username
https://localhost:44302/UserProfile results in below error

Server Error in '/' Application.

Error reading string. Unexpected token: StartArray. Path 'amr', line 1, position 220.
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: Newtonsoft.Json.JsonReaderException: Error reading string. Unexpected token: StartArray. Path 'amr', line 1, position 220.

Source Error:

Line 77: // CallContext currentCallContext = new CallContext { AccessToken = tce.AccessToken, ClientRequestId = Guid.NewGuid(), TenantId = tenantID, ApiVersion = "2013-11-08" };
Line 78:
Line 79: CallContext currentCallContext = new CallContext(tce.AccessToken, Guid.NewGuid(), "2013-11-08");
Line 80:
Line 81: GraphConnection graphConnection = new GraphConnection(currentCallContext);

Source File: d:\Test\GitHubAADSamples\AadAdfsSamples\WebApp-WebAPI-MultiTenant-OpenIdConnect-DotNet\TodoListWebApp\Controllers\UserProfileController.cs Line: 79

Stack Trace:

[JsonReaderException: Error reading string. Unexpected token: StartArray. Path 'amr', line 1, position 220.]
Newtonsoft.Json.JsonReader.ReadAsStringInternal() +526
Newtonsoft.Json.JsonTextReader.ReadAsString() +36
Newtonsoft.Json.Serialization.JsonSerializerInternalReader.ReadForType(JsonReader reader, JsonContract contract, Boolean hasConverter) +279
Newtonsoft.Json.Serialization.JsonSerializerInternalReader.PopulateDictionary(IDictionary dictionary, JsonReader reader, JsonDictionaryContract contract, JsonProperty containerProperty, String id) +1876
Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateObject(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, Object existingValue) +1679
Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateValueInternal(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, Object existingValue) +189
Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(JsonReader reader, Type objectType, Boolean checkAdditionalContent) +749
Newtonsoft.Json.JsonSerializer.DeserializeInternal(JsonReader reader, Type objectType) +1665
Newtonsoft.Json.JsonSerializer.Deserialize(JsonReader reader, Type objectType) +47
Newtonsoft.Json.JsonConvert.DeserializeObject(String value, Type type, JsonSerializerSettings settings) +198
Newtonsoft.Json.JsonConvert.DeserializeObject(String value, JsonSerializerSettings settings) +118
Newtonsoft.Json.JsonConvert.DeserializeObject(String value) +81
Microsoft.Azure.ActiveDirectory.GraphClient.Utils.GetTenantId(String accessToken) +455
Microsoft.Azure.ActiveDirectory.GraphClient.CallContext..ctor(String accessToken, Guid clientRequestId, String apiVersion, String graphApiDomainName) +127
Microsoft.Azure.ActiveDirectory.GraphClient.CallContext..ctor(String accessToken, Guid clientRequestId, String apiVersion) +72
TodoListWebApp.Controllers.UserProfileController.Index() in d:\Test\GitHubAADSamples\AadAdfsSamples\WebApp-WebAPI-MultiTenant-OpenIdConnect-DotNet\TodoListWebApp\Controllers\UserProfileController.cs:79
lambda_method(Closure , ControllerBase , Object[] ) +101
System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +59
System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary2 parameters) +435 System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary2 parameters) +60
System.Web.Mvc.Async.ActionInvocation.InvokeSynchronousActionMethod() +76
System.Web.Mvc.Async.AsyncControllerActionInvoker.b__39(IAsyncResult asyncResult, ActionInvocation innerInvokeState) +36
System.Web.Mvc.Async.WrappedAsyncResult2.CallEndDelegate(IAsyncResult asyncResult) +73 System.Web.Mvc.Async.WrappedAsyncResultBase1.End() +136
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +102
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +49
System.Web.Mvc.Async.AsyncInvocationWithFilters.b__3f() +117
System.Web.Mvc.Async.<>c__DisplayClass48.b__41() +323
System.Web.Mvc.Async.<>c__DisplayClass33.b__32(IAsyncResult asyncResult) +44
System.Web.Mvc.Async.WrappedAsyncResult1.CallEndDelegate(IAsyncResult asyncResult) +47 System.Web.Mvc.Async.WrappedAsyncResultBase1.End() +136
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +102
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +50
System.Web.Mvc.Async.<>c__DisplayClass2b.b__1c() +72
System.Web.Mvc.Async.<>c__DisplayClass21.b__1e(IAsyncResult asyncResult) +185
System.Web.Mvc.Async.WrappedAsyncResult1.CallEndDelegate(IAsyncResult asyncResult) +42 System.Web.Mvc.Async.WrappedAsyncResultBase1.End() +133
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +56
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +40
System.Web.Mvc.Controller.b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) +34
System.Web.Mvc.Async.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult asyncResult) +70 System.Web.Mvc.Async.WrappedAsyncResultBase1.End() +139
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +59
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +44
System.Web.Mvc.Controller.b__15(IAsyncResult asyncResult, Controller controller) +39
System.Web.Mvc.Async.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult asyncResult) +62 System.Web.Mvc.Async.WrappedAsyncResultBase1.End() +139
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +59
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40
System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +39
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +39
System.Web.Mvc.MvcHandler.b__5(IAsyncResult asyncResult, ProcessRequestState innerState) +39
System.Web.Mvc.Async.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult asyncResult) +70 System.Web.Mvc.Async.WrappedAsyncResultBase1.End() +139
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +59
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +40
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +38
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9514928
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155

AfterAccessNotification - this.HasStateChanged always true.

Hi! I think that in EFADALTokenCache.cs, on the AfterAccessNotification method the following line will always return true (Line 83 ):

        if (this.HasStateChanged){
       }

Because on the BeforeAccessNotification method there is always a call to Deserialize:

       this.Deserialize((Cache == null) ? null : Cache.cacheBits);

Wouldn't be correct to call Deserialize only if the Cache is stale?

Thanks!

EFADALTokenCache uses expired token

I always have to clear the PerUserCacheList table. or it will use a expired token and return an error when trying to access UserProfile.

Visual Studio 2015 have a similar class (ADALTokenCache) with the same bug

The provided access grant is invalid or malformed.

Hi,
I get the below error
{"AADSTS70002: Error validating credentials. AADSTS70000: The provided access grant is invalid or malformed.\r\nTrace ID: 6f573d7b-8e09-4c82-98d6-430be938a6f4\r\nCorrelation ID: 08a02615-0fc9-4788-9174-811940e871a2\r\nTimestamp: 2014-07-16 21:30:27Z"}
on line
AuthenticationContext authContext = new AuthenticationContext(string.Format("https://login.windows.net/{0}", tenantID));
AuthenticationResult result = authContext.AcquireTokenByAuthorizationCode(
code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential, graphResourceID);

I'm trying to retrieve the token of logged-in (sign-in)user.

signup is working great and I'm able to receive the token after signup, but not for the sign-in user. could you please correct me where i'm going wrong.

many thanks in advance.

Did you break the app again?!

I got this issue when I was trying to login with an active directory user. What might be the problem.

With your code, besides changing the ClientId and keys, what else do I need to do?

Thank you!

AAD integration works locally but not when deploying app on Azure

I just setup a new Azure Active Directory and added some users to it. I created a new MVC application and enabled multi-tenant authentication for this project.

If I now run the project I can login using an account from the Active Directory.

I then ran into 2 problems:

  1. When I deployed the application to Azure using an AzureRM script from VSTS I ran into the issue that the application that's hosted in Azure kept redirecting met to http://localhost:44333/ which ofcourse was my local instance of the website. After doing some searching I managed to fix this by editing the manifest of the application that was automatically created during the creation of the MVC application.

I changed the HomePage url to my Azure url and I also changed the redirect URL to the same Azure URL.

Now the real issue popped up:

  1. Whenever I now browse to the website, I correctly see the login prompt and can login with my Azure AD account. However when I click on the last "Next" button it starts loading for a few minutes. After that I get redirected to the Error page of my MVC application.

I did some investigation by enabling remote debugging and managed to trace it down to the following call (I did verify that all parameters provided are exactly the same as when running it from my local machine):

AuthenticationContext authContext = new AuthenticationContext(aadInstance + tenantID, new ADALTokenCache(signedInUserID));

This call takes about a minute and then the code resumes in the following function:

AuthenticationFailed = (context) =>
{
	context.OwinContext.Response.Redirect("/Home/Error");
	context.HandleResponse(); // Suppress the exception
	return Task.FromResult(0);
}

When checking the context parameter I can see the following error:

A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 52 - Unable to locate a Local Database Runtime installation. Verify that SQL Server Express is properly installed and that the Local Database Runtime feature is enabled.)

I've already tried recreating the application, manually creating a webapi application in the AD, changing the redirect urls, setting some booleans to true in the application manifest on the AD, etc. but nothing seems to change anything.

picture

SecurityTokenValidated received prior to AuthorizationCodeReceived

After the last nuget update to OpenIdConnect package (Microsoft.Owin.Security.OpenIdConnect), the SecurityTokenValidated callback is called before AuthorizationCodeReceived (this was AccessCodeReceived in previoud release), as the result I cannot acquire access token prior to SecurityTokenValidated. I needed a token to validate user is granted access to application based on his security groups. To retrieve security groups I talked to graph API inside SecurityTokenValidated callback with a token acquired by authorization code. So, this sample is no longer right after the last update to nuget package

Feedback from Dan's intern

Github Sample:

o Per instructions, I downloaded Visual Studio 2013. I assume there are other versions of Visual Studio that would have sufficed as well? I already had Visual Studio 2010, couldn’t I have just used that?
o Step 3.9, as someone who had never made an AAD Tenant before, and had never used the portal before, I had no idea what my domain was at this step, and didn’t know where to go to find it. I was able to figure it out eventually because it I saw my domain in the page’s URL, but that was a weird way to figure it out
o The bar at the bottom of the Azure Management Portal page is referred to in 3 different ways, which threw me off a bit: “the drawer”, “the command bar”, and “bottom command bar
o Step 3.13, “Enable sign-on and read users’ profiles” was actually the default Permission, so I didn’t actually have to do this step. I think it’s still good to draw attention to what the set permissions are though, so I wouldn’t propose getting rid of this step altogether.
o Step 4.4, what is a clipboard? Also, the directions say to “use” the key “now,” I think what was actually meant was that I needed to save the key now
o Step 5, I did not know what “solution” meant, nor did I know how to open it in VS
 In this step, managed to get pretty confused, somehow involving my opening the wrong web.config file, therefore incorrectly changing the ClientID and Password values, etc. Overall some more specific instructions in this step would’ve been useful
o Step 6, “click Add”, there is no Add button, there’s a “New+” button though

Onboarding Tenant with Admin consent rights

Hi Vittorio,

I'm trying to implement the signup functionality to onboard new tenant from my application, I can onboard tenant only for one domain where Application is integrated. but not for the subdomains. I get an error and coudn't see the Consent page at all for the subdomains.

""AADSTS65005: The application needs access to a service that your organization InnubexSub has not subscribed to. Please contact your Administrator to review the configuration of your service subscriptions.\r\nTrace ID: e8d70d11-eb92-4e42-8fc0-abfdd5eac843\r\nCorrelation ID: 9067c1eb-16eb-4c30-9d8a-e2fc686591b1\r\nTimestamp: 2014-07-30 11:26:09Z""

Many thanks in advance.

How can I run my AAD graph api differential query application as multi-tenant?

followed the same steps which is mentioned in the below GitHub sample to query graph api from my console application
https://github.com/AzureADSamples/ConsoleApp-GraphAPI-DiffQuery-DotNet

MainTenant - application is created under the MainTenant
and I'm able to retrieve users from my console application with the below configuration

But if I try to retrieve users for other tenants I get the following error
The remote server returned an error: (401) Unauthorized.
at System.Net.WebClient.DownloadDataInternal(Uri address, WebRequest& request)

updated my configuration for to get users from other tenant

string AuthEndpoint="https://login.windows.net/{0}";

retrieving the accesstoken from the below method is possible

protected string GetTokenForApplication()
{
string aEndpoint = string.Format(AuthEndpoint, TenantDomainName);
AuthenticationContext authenticationContext = new AuthenticationContext(aEndpoint, false);
// Config for OAuth client credentials
ClientCredential clientCred = new ClientCredential(this.AppPrincipalId, this.AppPrincipalPassword);
AuthenticationResult authenticationResult = authenticationContext.AcquireToken(this.ProtectedResourcePrincipalId, clientCred);
return authenticationResult.AccessToken;
}
but it throws error when I execute the DownloadData method

private byte[] DownloadData(WebClient webClient, string suffix)

{
this.AddHeaders(webClient);
string serviceEndPoint = string.Format(
@"https://{0}/{1}/{2}",
"graph.windows.net",
TenantDomainName,
suffix);

            return webClient.DownloadData(serviceEndPoint);

}
error: The remote server returned an error: (401) Unauthorized.
at System.Net.WebClient.DownloadDataInternal(Uri address, WebRequest& request)

could some one pls help me to fix this error

thanks in advance

'System.Data.SqlClient.SqlException'

My debug window shows this over and over...

Exception thrown: 'System.Data.SqlClient.SqlException' in System.Data.dll
Exception thrown: 'System.Data.SqlClient.SqlException' in System.Data.dll

Is there a data component that needs to be configured?

Sign up and Todo list does not work for me

A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 50 - Local Database Runtime error occurred. Cannot create an automatic instance. See the Windows Application event log for error details.
)

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.Data.SqlClient.SqlException: A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 50 - Local Database Runtime error occurred. Cannot create an automatic instance. See the Windows Application event log for error details.
)

Source Error:

Line 42: tenant.IssValue = stateMarker;
Line 43: tenant.Created = DateTime.Now;
Line 44: db.Tenants.Add(tenant);
Line 45: db.SaveChanges();
Line 46:

Source File: C:\Users\W2BI\Desktop\Cloud\Azure\Active Directory\oidc-dotne\TodoListWebApp\Controllers\OnboardingController.cs Line: 44

Stack Trace:

[SqlException (0x80131904): A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 50 - Local Database Runtime error occurred. Cannot create an automatic instance. See the Windows Application event log for error details.
)]
System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action1 wrapCloseInAction) +92 System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) +285 System.Data.SqlClient.TdsParser.Connect(ServerInfo serverInfo, SqlInternalConnectionTds connHandler, Boolean ignoreSniOpenTimeout, Int64 timerExpire, Boolean encrypt, Boolean trustServerCert, Boolean integratedSecurity, Boolean withFailover, SqlAuthenticationMethod authType) +372 System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean ignoreSniOpenTimeout, TimeoutTimer timeout, Boolean withFailover) +172 System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString connectionOptions, SqlCredential credential, TimeoutTimer timeout) +849 System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(TimeoutTimer timeout, SqlConnectionString connectionOptions, SqlCredential credential, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance) +320 System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData, DbConnectionPool pool, String accessToken) +591 System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions) +304 System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnectionPool pool, DbConnection owningObject, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions) +38 System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection) +681 System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection) +89 System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection) +426 System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompletionSource1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection) +78
System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection) +191 System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource1 retry, DbConnectionOptions userOptions) +154
System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource1 retry, DbConnectionOptions userOptions) +21 System.Data.SqlClient.SqlConnection.TryOpenInner(TaskCompletionSource1 retry) +90
System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource1 retry) +166 System.Data.SqlClient.SqlConnection.Open() +96 System.Data.Entity.Infrastructure.Interception.DbConnectionDispatcher.<Open>b__36(DbConnection t, DbConnectionInterceptionContext c) +10 System.Data.Entity.Infrastructure.Interception.InternalDispatcher1.Dispatch(TTarget target, Action2 operation, TInterceptionContext interceptionContext, Action3 executing, Action3 executed) +468 System.Data.Entity.Infrastructure.Interception.DbConnectionDispatcher.Open(DbConnection connection, DbInterceptionContext interceptionContext) +360 System.Data.Entity.SqlServer.<>c__DisplayClass33.<UsingConnection>b__32() +426 System.Data.Entity.SqlServer.<>c__DisplayClass1.<Execute>b__0() +10 System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute(Func1 operation) +189
System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute(Action operation) +78
System.Data.Entity.SqlServer.SqlProviderServices.UsingConnection(DbConnection sqlConnection, Action1 act) +175 System.Data.Entity.SqlServer.SqlProviderServices.UsingMasterConnection(DbConnection sqlConnection, Action1 act) +556
System.Data.Entity.SqlServer.SqlProviderServices.CreateDatabaseFromScript(Nullable1 commandTimeout, DbConnection sqlConnection, String createDatabaseScript) +86 System.Data.Entity.SqlServer.SqlProviderServices.DbCreateDatabase(DbConnection connection, Nullable1 commandTimeout, StoreItemCollection storeItemCollection) +164
System.Data.Entity.Core.Common.DbProviderServices.CreateDatabase(DbConnection connection, Nullable1 commandTimeout, StoreItemCollection storeItemCollection) +76 System.Data.Entity.Core.Objects.ObjectContext.CreateDatabase() +134 System.Data.Entity.Migrations.Utilities.DatabaseCreator.Create(DbConnection connection) +140 System.Data.Entity.Migrations.DbMigrator.EnsureDatabaseExists(Action mustSucceedToKeepDatabase) +142 System.Data.Entity.Migrations.DbMigrator.Update(String targetMigration) +78 System.Data.Entity.Internal.DatabaseCreator.CreateDatabase(InternalContext internalContext, Func3 createMigrator, ObjectContext objectContext) +89
System.Data.Entity.Internal.InternalContext.CreateDatabase(ObjectContext objectContext, DatabaseExistenceState existenceState) +116
System.Data.Entity.Database.Create(DatabaseExistenceState existenceState) +218
System.Data.Entity.DropCreateDatabaseIfModelChanges1.InitializeDatabase(TContext context) +250 System.Data.Entity.Internal.<>c__DisplayClassf1.b__e() +76
System.Data.Entity.Internal.InternalContext.PerformInitializationAction(Action action) +60
System.Data.Entity.Internal.InternalContext.PerformDatabaseInitialization() +357
System.Data.Entity.Internal.LazyInternalContext.b__4(InternalContext c) +7
System.Data.Entity.Internal.RetryAction1.PerformAction(TInput input) +110 System.Data.Entity.Internal.LazyInternalContext.InitializeDatabaseAction(Action1 action) +198
System.Data.Entity.Internal.LazyInternalContext.InitializeDatabase() +73
System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType) +28
System.Data.Entity.Internal.Linq.InternalSet1.Initialize() +53 System.Data.Entity.Internal.Linq.InternalSet1.get_InternalContext() +15
System.Data.Entity.Internal.Linq.InternalSet1.ActOnSet(Action action, EntityState newState, Object entity, String methodName) +62 System.Data.Entity.Internal.Linq.InternalSet1.Add(Object entity) +108
System.Data.Entity.DbSet1.Add(TEntity entity) +73 TodoListWebApp.Controllers.OnboardingController.SignUp(Tenant tenant) in C:\Users\W2BI\Desktop\Cloud\Azure\Active Directory\oidc-dotne\TodoListWebApp\Controllers\OnboardingController.cs:44 lambda_method(Closure , ControllerBase , Object[] ) +104 System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +14 System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary2 parameters) +157
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary2 parameters) +27 System.Web.Mvc.Async.AsyncControllerActionInvoker.<BeginInvokeSynchronousActionMethod>b__39(IAsyncResult asyncResult, ActionInvocation innerInvokeState) +22 System.Web.Mvc.Async.WrappedAsyncResult2.CallEndDelegate(IAsyncResult asyncResult) +29
System.Web.Mvc.Async.WrappedAsyncResultBase1.End() +49 System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +32 System.Web.Mvc.Async.AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3d() +50 System.Web.Mvc.Async.<>c__DisplayClass46.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f() +225 System.Web.Mvc.Async.<>c__DisplayClass33.<BeginInvokeActionMethodWithFilters>b__32(IAsyncResult asyncResult) +10 System.Web.Mvc.Async.WrappedAsyncResult1.CallEndDelegate(IAsyncResult asyncResult) +10
System.Web.Mvc.Async.WrappedAsyncResultBase1.End() +49 System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +34 System.Web.Mvc.Async.<>c__DisplayClass2b.<BeginInvokeAction>b__1c() +26 System.Web.Mvc.Async.<>c__DisplayClass21.<BeginInvokeAction>b__1e(IAsyncResult asyncResult) +100 System.Web.Mvc.Async.WrappedAsyncResult1.CallEndDelegate(IAsyncResult asyncResult) +10
System.Web.Mvc.Async.WrappedAsyncResultBase1.End() +49 System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +27 System.Web.Mvc.Controller.<BeginExecuteCore>b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) +13 System.Web.Mvc.Async.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult asyncResult) +29
System.Web.Mvc.Async.WrappedAsyncResultBase1.End() +49 System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +36 System.Web.Mvc.Controller.<BeginExecute>b__15(IAsyncResult asyncResult, Controller controller) +12 System.Web.Mvc.Async.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult asyncResult) +22
System.Web.Mvc.Async.WrappedAsyncResultBase1.End() +49 System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +26 System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +10 System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__5(IAsyncResult asyncResult, ProcessRequestState innerState) +21 System.Web.Mvc.Async.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult asyncResult) +29
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +28
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9721605
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155

EfAdalTokenCache with Dependency Injection

Hi there,

I am looking for a way to use EfAdalTokenCache with Dependecy Injection. In the provided sample there is a hard reference to the underlying database.

public class EFADALTokenCache: TokenCache
{
        private TodoListWebAppContext db = new TodoListWebAppContext();
        string User;
        PerWebUserCache Cache;

        // constructor
        public EFADALTokenCache(string user)
        {
            //... some code

            Cache = db.PerUserCacheList.FirstOrDefault(c => c.webUserUniqueId == User);

            //... some code
        }

How would you adopt the sample code to support this?

Many thanks.

Best regards,

Veit

Multiple WebApps token cache issue

Not sure where to submit the question about the use of token cache, so decided to put it here. Using this sample I have next scenario: two web apps (same as sample code). Both apps use same token cache persistent store. I start the first web app and am able to authenticate, acquire tokens for graph API resource, all is good. I start the second app in the same browser window - new tab. As the result - app does not go through the normal path of authentication notifications (I never reach AuthorizationCodeReceived because I am already logged in). Now in the second app when I try to use AcquireTokenSilent to acquire a token for graph API - it fails. Error states that I need to use AcquireToken. The issue is as I understand that clientID (app client id) for the second app is different from what is in token cache (first app's ClientID) and as the result I cannot acquire a token in second app. What it the a correct way of using token cache to handle this scenario (two webapps, same tenant, same user, both are trying to query graph API)

Application requires access to Graph API Resource

I think you should put a description somewhere that says this application is also performing OAuth Authorization for accessing GraphAPI resource. Wouldn't it be possible to simply perform authentication without requiring access to Graph API

EFADALTokenCache.AfterAccessNotification ???

Am I missing something... how in the world can _cache.EntryId ever NOT be == 0 in this code?

if (HasStateChanged)
{
_cache = new PerWebUserCache
{
webUserUniqueId = _user,
cacheBits = Serialize(),
LastWrite = DateTime.Now
};

_db.Entry(_cache).State = _cache.EntryId == 0 ? EntityState.Added : EntityState.Modified;
_db.SaveChanges();

HasStateChanged = false;

}

ADAL TokenCache based on Azure Sql Db

I am trying to implement SQL Server caching for ADAL tokens following the approach in efadaltokencache. I have my database instance as an Azure SQL DB.

In order to implement, I created the necessary table with specified columns in SQL Server i.e. entryId (int), webUserUniqueId (nvarchar(max)), cacheBits(varbinary(max)) and lastWrite. For one, I didn't find the need to create this in the documentation of the sample, but if it's not there it needed to be created, so I created one.

Now, while saving the changes to the cache after a token has been generated, an event "AfterAccessNotification" is triggered to update the database. However, I am getting the exception on SaveChanges - "System.Data.SqlClient.SqlException: String or binary data would be truncated.The statement has been terminated."

Not sure what is it that I am missing?.

EFADALTokenCache needs documentation

I'm trying to understand why EFADALTokenCache works the way it does. All references I found say that I should implement my own TokenCache but leave that implementation as an exercise to the reader, and this sample implementations makes some counterintuitive decisions.

  • Why does EFADALTokenCache create a new entry in the database every time BeforeAccessNotification is called? If EFADALTokenCache.Clear is never called (because the user never clicks "Sign Out" and just lets his session expire), won't this grow the table unnecessarily?

  • Why does EFADALTokenCache pick the "FirstOrDefault" entry for a user instead of the latest one? There has been a fix suggested here 2 years ago, is there any reason why it was not merged to the master branch?
    #20
    It also seems to me that this fix is incomplete, there are other cases in EFADALTokenCache where the "FirstOfDefault" is used without an order by LastWrite.

not able to connect to sql db

Hi

I tried to run the application but I get the following error. TodoListWebAppContext.mdf db is found in \TodoListWebApp\App_Data. Is there any other changes do I need to do.

This is the connection string I see on debug

"Data Source=(localdb)\v12.0;AttachDbFilename=|DataDirectory|TodoListWebAppContext.mdf;Initial Catalog=TodoListWebAppContext;Integrated Security=True;MultipleActiveResultSets=True"

Server=localhost\SQLEXPRESS;Database=master;Trusted_Connection=True;

System.Data.SqlClient.SqlException
HResult=0x80131904
Message=A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 50 - Local Database Runtime error occurred. The specified LocalDB instance does not exist.
)
Source=.Net SqlClient Data Provider
StackTrace:

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.