GithubHelp home page GithubHelp logo

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

View Code? Open in Web Editor NEW
82.0 72.0 69.0 1.29 MB

A .NET 4.5 MVC web app that signs Azure AD users in with OpenID Connect and calls a web api using OAuth 2.0 access tokens.

C# 68.79% CSS 1.52% ASP 0.09% HTML 12.91% JavaScript 15.78% Roff 0.91%

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

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

Contributors

acomsmpbot avatar bkwdesign avatar dstrockis avatar iouri-s avatar jmprieur avatar pataltimore avatar priyamohanram avatar skwan avatar supernova-eng avatar v-hearya avatar vibronet avatar whoiskevinrich 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  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  avatar

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

Deployed to a non root directory in IIS and login fails with The redirect address is not valid

Looks like this happens due to GetLeftpart at
AuthenticationResult result = authContext.AcquireTokenByAuthorizationCode(
code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority)), credential, graphResourceId);

Detailed Error:
[WebException: The remote server returned an error: (401) Unauthorized.]
System.Net.HttpWebRequest.GetResponse() +8548300
Microsoft.IdentityModel.Clients.ActiveDirectory.HttpHelper.SendPostRequestAndDeserializeJsonResponse(String uri, StringBuilder messageBuilder) +134

[ActiveDirectoryAuthenticationException: AADSTS70002: Error validating credentials. AADSTS70000: The redirect address 'https://root/' is not valid.
Trace ID: b378d6b5-9f07-4eab-bfc8-830938b9c807
Correlation ID: 1fb9923b-ce79-463f-8cfc-967a3b029552
Timestamp: 2014-06-25 06:20:02Z]
Microsoft.IdentityModel.Clients.ActiveDirectory.ExceptionHelper.ThrowServiceException(WebException ex, ErrorFormat format) +294
Microsoft.IdentityModel.Clients.ActiveDirectory.HttpHelper.SendPostRequestAndDeserializeJsonResponse(String uri, StringBuilder messageBuilder) +346
Microsoft.IdentityModel.Clients.ActiveDirectory.OAuth2Request.SendHttpMessage(String uri, StringBuilder messageBuilder) +281
Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext.AcquireTokenByAuthorizationCode(String authorizationCode, Uri redirectUri, ClientCredential credential, String resource) +177
TodoListWebApp.Startup.b__2(AccessCodeReceivedNotification context) in d:\Test\GitHubAADSamples\AadAdfsSamples\WebApp-WebAPI-OpenIDConnect-DotNet\TodoListWebApp\App_Start\Startup.Auth.cs:80
Microsoft.Owin.Security.OpenIdConnect.d__1e.MoveNext() +4285
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() +32
Microsoft.Owin.Security.OpenIdConnect.d__1e.MoveNext() +6323
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +144
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +84
System.Runtime.CompilerServices.TaskAwaiter`1.GetResult() +49
Microsoft.Owin.Security.Infrastructure.d__0.MoveNext() +1008
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +144
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +84
Microsoft.Owin.Security.Infrastructure.d__0.MoveNext() +483
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +144
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +84
Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.d__5.MoveNext() +291
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +144
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +84
Microsoft.Owin.Security.Infrastructure.d__0.MoveNext() +1107
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +144
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +84
Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.d__5.MoveNext() +291
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +144
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +84
Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.d__2.MoveNext() +293
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() +32
Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.IntegratedPipelineContext.EndFinalWork(IAsyncResult ar) +208
System.Web.AsyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +434
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +288

Add comment about redirect URL sent from app must match redirect URL registered in portal

Often one will forget to include the backslash at the end of the redirect URL when entering it in the portal. The code in this sample will always include the backslash on the end of the URI. Add a comment to this effect plus break out the URI creation so it's easier to see the value in the debugger.

Example error that you will see if there is a mismatch:

'Microsoft.IdentityModel.Clients.ActiveDirectory.ActiveDirectoryAuthenticationException' occurred in Microsoft.IdentityModel.Clients.ActiveDirectory.dll but was not handled in user code

Additional information: AADSTS70002: Error validating credentials. AADSTS70000: The provided access grant is invalid or malformed.

Logout caused the infinite loop

Hi

I tested this sample code with IIS express, and did experience infinite loop somehow.

Can you please advise how to fix this issue?

Thanks,
Vincent

Requirement for using AntiForgery Tokens

If you plan on using @Html.AntiForgeryToken() in Views with this authentication method, you need to add the following line to your Global.asax.cs file:

using System.Security.Claims;
using System.Web.Helpers;

AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.NameIdentifier;

ADFS On-premises sample

Hi

Is this sample code compatible with ADFS On-premises scenario?

If not, would you be able to share the on-premises example?

Thanks,
Vincent

ReadMe Step 3: Number 11

Step 3: Number 11: Instruction says:
Find the Client ID value and copy it aside, you will need this later when configuring your application.

Nowhere do I see this "Client ID" of the service being used again in ReadMe. So what is the point of copying it and setting it aside? I suspect this is the reason this sample is failing with AccessDenied

Manifest File Issues (2)

  1. The Manifest file does not have a "appPermisions" section as per sample instructions.

  2. After changing the ID guid value, an attempt to upload the edited Manifest file fails with the following error message:

webapp-webapi-openidconnect-dotnet manifest upload error

"ParameterValidationException=Invalid parameters provided; BadRequestException=Property value cannot be deleted unless it is disabled first.; "

TodoListController throws exception when attempting to grab token to call TodoService

failed_to_acquire_token_silently: Failed to acquire token silently. Call method AcquireToken at Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext.RunAsyncTask[T](Task`1 task) at Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext.AcquireTokenSilent(String resource, ClientCredential clientCredential, UserIdentifier userId) at TodoListWebApp.Controllers.TodoListController.d__6.MoveNext()

Request Unauthorized error

Hi ,
I was working on the sample you have given and able to pass the authentication but getting unauthorized exception while making call to ToDOListService.

Request you to provide some help here..

Thanks,
Ritesh
unauthorized

Scope claim always null

Hello, I am trying to mess around with a sample but I stuck with some annoying exception. Everytime a call to the service is made, it ends up at the point where the check regarding scope claim is being done:

ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/scope").Value != "user_impersonation"

Always leads to null reference exception. I guess it somehow relates to the application's manifest within AD, but I cannot figure it out.

Can someone help me please? Thanks!

Cannot apply Roles to the backend WebAPI

I set up projects by following instructions. all works fine except the appRoles. I know the appRoles was not mentioned in the sample project, but I am wondering if it is possible to apply appRoles to backend WebAPI project(ToGoAPI project) like [Authorize(Roles="myAppRoles")].

the process is that I created appRoles in To Do SPA app, and the id_token does contain appRoles I belongs to after I login the App(To Do SPA). however, when i call the To Go API(To Go API App) , I need to get access token to the API. and I got and parsed the access token, found that there is no appRoles contained in it. In To Go API, the authorization without Roles works fine. and it returns unauthorized when i call the API with [Authorize(Roles="myAppRoles")].

deploying problem on azure

I have created sample project using WebApp-WebAPI-OpenIDConnect-DotNet.

I followed all the steps as described on git repo. My sample project is working properly on local host. But when I am deploying my project on Azure it's giving following error.

Please check below stack trace.

Stack trace:

[NullReferenceException: Object reference not set to an instance of an object.]
CMS.Web.Utils.NaiveSessionCache.Load() in c:\a\src\CMS.Web\CMS.Web\Utils\NaiveSessionCache.cs:30
CMS.Web.Utils.NaiveSessionCache..ctor(String userId) in c:\a\src\CMS.Web\CMS.Web\Utils\NaiveSessionCache.cs:23
CMS.Web.Startup.b__2(AuthorizationCodeReceivedNotification context) in c:\a\src\CMS.Web\CMS.Web\App_Start\Startup.Auth.cs:83
Microsoft.Owin.Security.OpenIdConnect.d__1a.MoveNext() +4995
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() +22
Microsoft.Owin.Security.OpenIdConnect.d__1a.MoveNext() +6529
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +93
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +52
Microsoft.Owin.Security.Infrastructure.d__0.MoveNext() +595
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +93
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +52
Microsoft.Owin.Security.Infrastructure.d__0.MoveNext() +264
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +93
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +52
Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.d__5.MoveNext() +191
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +93
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +52
Microsoft.Owin.Security.Infrastructure.d__0.MoveNext() +665
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +93
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +52
Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.d__5.MoveNext() +191
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +93
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +52
Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.d__2.MoveNext() +189
Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.StageAsyncResult.End(IAsyncResult ar) +69
Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.IntegratedPipelineContext.EndFinalWork(IAsyncResult ar) +64
System.Web.AsyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +415
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155

User's permission on applications

Hi! After several testings I realize that user's tab under application configuration (ActiveDirectory-> Applications -> Users) has no effect on allowing or not a user to log into the application. Does anyone know which is the objective of that configuration ? Or maybe I'm using it in a wrong way.

Thanks a lot.

After user consent, get AADSTS 65005 Error

Hi there,

this is Jun from China. i'm using this sample to make this work for China environment. pull the code and make the following change, this only occurred on 1st sign in with User Consent.

here are the repro steps for my environment.

  1. Follow Readme.md to create TodoListService & TodoListWebapp on Azure China portal.

  2. TodoListService

  3. add MetadataAddress for China in Startup.Auth.cs
    MetadataAddress = "https://login.chinacloudapi.cn/d93cb861-a6db-4e95-9c95-69c4d22a5374/federationmetadata/2007-06/federationmetadata.xml",

  4. change web.config of TodoListWebApp to meet the requirement for China endpoint

  5. After rebuild and sign in as a user. once consent, get the following error:
    AADSTS70002: Error validating credentials. AADSTS65005: Misconfigured application. This could be due to one of the following: The client has not listed any permissions for 'Microsoft Graph' in the requested permissions in the client's application registration. Or, The admin has not consented in the tenant. Or, Check the application identifier in the request to ensure it matches the configured client application identifier. Please contact your admin to fix the configuration or consent on behalf of the tenant. Client app ID: 6317d553-494d-427c-a34a-d9ae5bc1f171.

  6. open the new tab to sign in the webapp page again, it can be worked as expected. this is very strange.
    please help, any help will be appreciated. thanks!

Error message returned to user on TodoList page is inconsistent.

Both messages should refer to the TodoList. :)
From WebApp \ Views \ TodoList \ Index.cshtml :

@if (ViewBag.ErrorMessage == "AuthorizationRequired")
{

You have to sign-in to see your profile. Click @Html.ActionLink("here", "Index", "TodoList", new { reauth = true }, null) to sign-in.

}

@if (ViewBag.ErrorMessage == "UnexpectedError")
{

An unexpected error occurred while retrieving your to do list. Please try again. You may need to sign-in.


}

failed_to_acquire_token_silently

Hi everyone,

I'm testing this sample but i'm not able to run it !!! I can sign in correctly but when i consume the todolist when the code do:

result = await authContext.AcquireTokenSilentAsync(todoListResourceId, credential, new UserIdentifier(userObjectID, UserIdentifierType.UniqueId));

on TodoListcontroller of TodoListWebApp i always get the following error:

Error code: failed_to_acquire_token_silently
mesasge: AADSTS65001: The user or administrator has not consented to use the application with ID '13e7d551-bf1a-42df-9fc4-9ee2aeb13a4d'. Send an interactive authorization request for this user and resource.

I lost a lot of time someone could help me please??

Crash after upgrading Microsoft.IdentityModel.Clients.ActiveDirectory to latest

The sample crashes after upgrade nuget package Microsoft.IdentityModel.Clients.ActiveDirectory to latest (3.13.8 as of writing). See below for call stacks

An exception of type 'System.NullReferenceException' occurred in TodoListWebApp.dll but was not handled in user code

Additional information: Object reference not set to an instance of an object.

at TodoListWebApp.Utils.NaiveSessionCache.Load() in C:\github\AzureSamples\active-directory-dotnet-webapp-webapi-openidconnect\TodoListWebApp\Utils\NaiveSessionCache.cs:line 27
at TodoListWebApp.Utils.NaiveSessionCache.BeforeAccessNotification(TokenCacheNotificationArgs args) in C:\github\AzureSamples\active-directory-dotnet-webapp-webapi-openidconnect\TodoListWebApp\Utils\NaiveSessionCache.cs:line 54
at Microsoft.IdentityModel.Clients.ActiveDirectory.TokenCache.OnBeforeAccess(TokenCacheNotificationArgs args)
at Microsoft.IdentityModel.Clients.ActiveDirectory.AcquireTokenHandlerBase.NotifyBeforeAccessCache()
at Microsoft.IdentityModel.Clients.ActiveDirectory.AcquireTokenHandlerBase.d__55.MoveNext()

Typo in web.config of TodoListWebApp

Please change
key="ida:AppKey" value="[Enter client ID as obtained from Azure Portal, e.g. j5+dsyukPzKtNIkh1t6eMk6+lYgMgCOWjBkrgybsL7E=]"
to
key="ida:AppKey" value="[Enter app key as obtained from Azure Portal, e.g. j5+dsyukPzKtNIkh1t6eMk6+lYgMgCOWjBkrgybsL7E=]"

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.