diff --git a/articles/quickstart/webapp/aspnet-owin/00-intro.md b/articles/quickstart/webapp/aspnet-owin/00-intro.md deleted file mode 100644 index a43baf79a2..0000000000 --- a/articles/quickstart/webapp/aspnet-owin/00-intro.md +++ /dev/null @@ -1,31 +0,0 @@ ---- -title: Introduction -name: Introduction to the quickstart guide and configuring the environment -description: This quickstart guide will walk you through the various tasks related to integrating Auth0 into your ASP.NET MVC 5 application. -budicon: 715 -topics: - - quickstarts - - webapp - - aspnet-owin -contentType: tutorial -useCase: quickstart ---- - -::: panel System Requirements -This tutorial and seed project have been tested with the following: - -* Microsoft Visual Studio 2017 v15.7 -* Microsoft.Owin.Security.OpenIdConnect v4.0.0 -::: - -This quickstart guide will walk you through the various tasks related to integrating Auth0 into your ASP.NET MVC 5 application. - -## Sample Projects - -If you would like to follow along with this quickstart, you can download a blank starter [seed project](https://github.com/auth0-samples/auth0-aspnet-owin-mvc-samples/tree/master/Quickstart/00-Starter-Seed). This is just a regular ASP.NET MVC application with a home page and a `web.config` file where you can configure the various Auth0-related settings for your application. - -Each of the steps in this guide contains a sample project download that shows the completion of the step. These projects can also be downloaded from the [ASP.NET (OWIN) MVC samples repository](https://github.com/auth0-samples/auth0-aspnet-owin-mvc-samples) where you can find the final result for each step in the relevant folder. - -<%= include('../../../_includes/_new_app') %> - -<%= include('_includes/_setup') %> \ No newline at end of file diff --git a/articles/quickstart/webapp/aspnet-owin/01-login.md b/articles/quickstart/webapp/aspnet-owin/01-login.md index 499504cf3c..4c0d187be1 100644 --- a/articles/quickstart/webapp/aspnet-owin/01-login.md +++ b/articles/quickstart/webapp/aspnet-owin/01-login.md @@ -8,15 +8,197 @@ topics: - aspnet-owin - login github: - path: Quickstart/01-Login + path: Quickstart/Sample contentType: tutorial useCase: quickstart sample_download_required_data: - client - - api --- <%= include('../../../_includes/_new_app', { showClientSecret: true, isPublicClient: false }) %> <%= include('_includes/_setup') %> -<%= include('_includes/_login') %> +## Install and configure the OpenID Connect middleware + +::: note + This quickstart uses OWIN middleware and as such, you need to use OWIN in your application. If your application is not currently using OWIN, please refer to Microsoft's OWIN documentation to enable it in your application. +::: + +The easiest way to enable authentication with Auth0 in your ASP.NET MVC application is to use the OWIN OpenID Connect middleware, so install the `Microsoft.Owin.Security.OpenIdConnect` NuGet package first: + +```bash +Install-Package Microsoft.Owin.Security.OpenIdConnect +``` + +You must also install the following middleware library to enable cookie authentication in your project: + +```bash +Install-Package Microsoft.Owin.Security.Cookies +``` + +::: note +There are issues when configuring the OWIN cookie middleware and System.Web cookies at the same time. Please read about the [System.Web cookie integration issues doc](https://github.com/aspnet/AspNetKatana/wiki/System.Web-response-cookie-integration-issues) to learn about how to mitigate these problems +::: + +Now go to the `Configuration` method of your `Startup` class and configure the cookie middleware as well as the Auth0 middleware. + +```cs +// Startup.cs +using Microsoft.IdentityModel.Protocols.OpenIdConnect; +using Microsoft.IdentityModel.Tokens; +using Microsoft.Owin; +using Microsoft.Owin.Host.SystemWeb; +using Microsoft.Owin.Security; +using Microsoft.Owin.Security.Cookies; +using Microsoft.Owin.Security.OpenIdConnect; +using MvcApplication.Support; +using Owin; + +public void Configuration(IAppBuilder app) +{ + // Configure Auth0 parameters + string auth0Domain = ConfigurationManager.AppSettings["auth0:Domain"]; + string auth0ClientId = ConfigurationManager.AppSettings["auth0:ClientId"]; + string auth0RedirectUri = ConfigurationManager.AppSettings["auth0:RedirectUri"]; + string auth0PostLogoutRedirectUri = ConfigurationManager.AppSettings["auth0:PostLogoutRedirectUri"]; + + // Set Cookies as default authentication type + app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType); + app.UseCookieAuthentication(new CookieAuthenticationOptions + { + AuthenticationType = CookieAuthenticationDefaults.AuthenticationType, + LoginPath = new PathString("/Account/Login"), + + // Configure SameSite as needed for your app. Lax works well for most scenarios here but + // you may want to set SameSiteMode.None for HTTPS + CookieSameSite = SameSiteMode.Lax, + + // More information on why the CookieManager needs to be set can be found here: + // https://github.com/aspnet/AspNetKatana/wiki/System.Web-response-cookie-integration-issues + CookieManager = new SameSiteCookieManager(new SystemWebCookieManager()) + }); + + // Configure Auth0 authentication + app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions + { + AuthenticationType = "Auth0", + + Authority = $"https://{auth0Domain}", + + ClientId = auth0ClientId, + + RedirectUri = auth0RedirectUri, + PostLogoutRedirectUri = auth0PostLogoutRedirectUri, + Scope = "openid profile email", + TokenValidationParameters = new TokenValidationParameters + { + NameClaimType = "name" + }, + + // More information on why the CookieManager needs to be set can be found here: + // https://docs.microsoft.com/en-us/aspnet/samesite/owin-samesite + CookieManager = new SameSiteCookieManager(new SystemWebCookieManager()), + + // Configure Auth0's Logout URL by hooking into the RedirectToIdentityProvider notification, + // which is getting triggered before any redirect to Auth0 happens. + Notifications = new OpenIdConnectAuthenticationNotifications + { + RedirectToIdentityProvider = notification => + { + // Only when the RequestType is OpenIdConnectRequestType.Logout should we configure the logout URL. + // Any other RequestType means a different kind of interaction with Auth0 that isn't logging out. + if (notification.ProtocolMessage.RequestType == OpenIdConnectRequestType.Logout) + { + var logoutUri = $"https://{auth0Domain}/v2/logout?client_id={auth0ClientId}"; + + var postLogoutUri = notification.ProtocolMessage.PostLogoutRedirectUri; + if (!string.IsNullOrEmpty(postLogoutUri)) + { + if (postLogoutUri.StartsWith("/")) + { + // transform to absolute + var request = notification.Request; + postLogoutUri = request.Scheme + "://" + request.Host + request.PathBase + postLogoutUri; + } + logoutUri += $"&returnTo={ Uri.EscapeDataString(postLogoutUri)}"; + } + + notification.Response.Redirect(logoutUri); + notification.HandleResponse(); + } + return Task.FromResult(0); + } + } + }); +} +``` + +It is essential that you register both the cookie middleware and the OpenID Connect middleware, as they are required (in that order) for the authentication to work. The OpenID Connect middleware will handle the authentication with Auth0. Once the user has authenticated, their identity will be stored in the cookie middleware. + +In the code snippet above, note that the `AuthenticationType` is set to **Auth0**. This will be used in the next section to challenge the OpenID Connect middleware and start the authentication flow. Also note code in the `RedirectToIdentityProvider` notification event which constructs the correct [logout URL](/logout). + + + + +## Add login to your application + +To allow users to login to your ASP.NET OWIN application, add a `Login` action to your controller. + +Call `HttpContext.GetOwinContext().Authentication.Challenge` and pass `"Auth0"` as the authentication scheme. This invokes the OIDC authentication handler that was registered earlier. Be sure to specify the corresponding `AuthenticationProperties`, including a `RedirectUri`. + +After successfully calling `HttpContext.GetOwinContext().Authentication.Challenge`, the user is redirected to Auth0 and signed in to both the OIDC middleware and the cookie middleware upon being redirected back to your application. This will allow users to be authenticated on subsequent requests. + +```cs +public class AccountController : Controller +{ + public ActionResult Login(string returnUrl) + { + HttpContext.GetOwinContext().Authentication.Challenge(new AuthenticationProperties + { + RedirectUri = returnUrl ?? Url.Action("Index", "Home") + }, + "Auth0"); + return new HttpUnauthorizedResult(); + } +} +``` + +## Add logout to your application + +From your controller's action, call `HttpContext.GetOwinContext().Authentication.SignOut` with the `CookieAuthenticationDefaults.AuthenticationType` authentication scheme to log the user out of your application. + +Additionally, if you want to log the user out from Auth0 (this might also log them out of other applications that rely on Single Sign-On), call `HttpContext.GetOwinContext().Authentication.SignOut` with the `"Auth0"` authentication scheme. + +```cs +public class AccountController : Controller +{ + [Authorize] + public void Logout() + { + HttpContext.GetOwinContext().Authentication.SignOut(CookieAuthenticationDefaults.AuthenticationType); + HttpContext.GetOwinContext().Authentication.SignOut("Auth0"); + } +} +``` + +## Display the user profile + +After the middleware successfully retrieves the tokens from Auth0, it extracts the user's information and claims from the ID token and makes them available as `ClaimsIdentity`. Access the extracted information by using the `User` property on the controller. + +To create a user profile, retrieve a user's name, email address, and profile image from `User.Identity` and pass it to the view from inside your controller. +```csharp +// Controllers/AccountController.cs + +[Authorize] +public ActionResult UserProfile() +{ + var claimsIdentity = User.Identity as ClaimsIdentity; + + return View(new + { + Name = claimsIdentity?.FindFirst(c => c.Type == claimsIdentity.NameClaimType)?.Value, + EmailAddress = claimsIdentity?.FindFirst(c => c.Type == ClaimTypes.Email)?.Value, + ProfileImage = claimsIdentity?.FindFirst(c => c.Type == "picture")?.Value + }); +} +``` diff --git a/articles/quickstart/webapp/aspnet-owin/02-user-profile.md b/articles/quickstart/webapp/aspnet-owin/02-user-profile.md deleted file mode 100644 index 6131c433ec..0000000000 --- a/articles/quickstart/webapp/aspnet-owin/02-user-profile.md +++ /dev/null @@ -1,133 +0,0 @@ ---- -title: User Profile -description: This tutorial demonstrates how to get the user's profile and display it. -budicon: 292 -topics: - - quickstarts - - webapp - - aspnet-owin - - user-profile -github: - path: Quickstart/02-User-Profile -contentType: tutorial -useCase: quickstart ---- - -## Getting the profile - -The OpenID Connect middleware will automatically retrieve the user's information from Auth0 and add it as claims to the `ClaimsIdentity`. The seed project contains a controller action and view which will display the claims associated with a particular user. Once a user has signed in, you can go to `/Account/Claims` to see these claims. - -By default, the `email` claim is not included in the list of claims returned by Auth0. You will need to request it explicitly by requesting the **email** scope when your register the Auth0 middleware. - -Update the OpenID Connect middleware configuration and set the value of the `Scope` property to `openid profile email`: - -```csharp -// Startup.cs - -public void Configuration(IAppBuilder app) -{ - // Some code omitted for brevity... - - // Configure Auth0 authentication - app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions - { - //... - Scope = "openid profile email", - //... - }); -} -``` - -You may also want to create a user profile page which will display a user's name, email address, and profile image. - -First, create a view model which will contain the basic user profile information, such as a `Name`, `EmailAddress`, and `ProfileImage`: - -```csharp -// ViewModels/UserProfileViewModel.cs - -public class UserProfileViewModel -{ - public string EmailAddress { get; set; } - - public string Name { get; set; } - - public string ProfileImage { get; set; } -} -``` - -Add a new `UserProfile` action to the `AccountController`, extract the relevant claims and add them to a new instance of `UserProfileViewModel` which is then passed to the view. Be sure to decorate the action with the `[Authorize]` attribute so only authenticated users can access the action: - -```csharp -// Controllers/AccountController.cs - -[Authorize] -public ActionResult UserProfile() -{ - var claimsIdentity = User.Identity as ClaimsIdentity; - - return View(new UserProfileViewModel() - { - Name = claimsIdentity?.FindFirst(c => c.Type == claimsIdentity.NameClaimType)?.Value, - EmailAddress = claimsIdentity?.FindFirst(c => c.Type == ClaimTypes.Email)?.Value, - ProfileImage = claimsIdentity?.FindFirst(c => c.Type == "picture")?.Value - }); -} -``` - -Next, create a view. For the view, display the user's name, email address and profile image. - -```html - - -@model global::MvcApplication.ViewModels.UserProfileViewModel -@{ - ViewData["Title"] = "User Profile"; -} - -
-
-
-

@ViewData["Title"].

- -
- -
-
-

@Model.Name

-

- @Model.EmailAddress -

-
-
-
-
-``` - -Now when you log in and then go to the URL `/Account/UserProfile` you will see the user's profile displayed. - -## Displaying the User's Name in the Navigation Bar - -You may also want to put a link in the top navigation bar to display the user's name, and when the user clicks on that, you can navigate them to their Profile page. - -Go to the `Views/Shared/_Layout.cshtml` file and update the Navbar section which displays the Login and Logout options to also display the user's name and link to the `UserProfile` action in the `AccountController`: - -```html - - - -``` - -Now, after the user has logged in you will be able to see their name in the top right corner of the navigation bar: - -![](/media/articles/server-platforms/aspnet-owin/navbar-userprofile.png) diff --git a/articles/quickstart/webapp/aspnet-owin/03-authorization.md b/articles/quickstart/webapp/aspnet-owin/03-authorization.md deleted file mode 100644 index 22fac9808c..0000000000 --- a/articles/quickstart/webapp/aspnet-owin/03-authorization.md +++ /dev/null @@ -1,56 +0,0 @@ ---- -title: Authorization -description: This tutorial demonstrates how to assign roles to your users, and use those roles to authorize or deny a user to access certain routes in the app. -budicon: 500 -topics: - - quickstarts - - webapp - - aspnet-owin - - authorization -github: - path: Quickstart/03-Authorization -contentType: tutorial -useCase: quickstart ---- - -ASP.NET (OWIN) supports Role-based Authorization which allows you to limit access to your application based on the user's role. This tutorial shows how to add role information to the user's ID Token and then use it to limit access to your application. - -::: note -This tutorial assumes that you are familiar with [Rules](/rules/current). -::: - -<%= include('../_includes/_create_and_assign_roles') %> - -## Restrict an Action Based on a User's Role - -Update the OpenID Connect middleware registration inside your `Startup` class to inform it which claim in the ID Token contains the role information by setting the `RoleClaimType` property of the `TokenValidationParameters`. The value you specify must match the claim you used in your rule. - -``` csharp -// Startup.cs - -app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions -{ - //... - TokenValidationParameters = new TokenValidationParameters - { - NameClaimType = "name", - RoleClaimType = "https://schemas.quickstarts.com/roles" - }, - //... -}); - -``` - -Now you can add a new action to your controller and restrict it by decorating your controller actions with the `[Authorize(Roles = ?)]` attribute. - -The sample code below will restrict the particular action to users who have the "admin" role: - -```csharp -// Controllers/AccountController.cs - -[Authorize(Roles = "admin")] -public ActionResult Admin() -{ - return View(); -} -``` diff --git a/articles/quickstart/webapp/aspnet-owin/04-migrating.md b/articles/quickstart/webapp/aspnet-owin/04-migrating.md deleted file mode 100644 index 7af7d3ff7b..0000000000 --- a/articles/quickstart/webapp/aspnet-owin/04-migrating.md +++ /dev/null @@ -1,32 +0,0 @@ ---- -title: Migrating to OWIN 4 -description: This tutorial demonstrates how to migrate from OWIN 3.x to OWIN 4.0 -budicon: 500 ---- - - - -::: note -The `Auth0-ASPNET-Owin` NuGet package has unresolved security issues and has been deprecated. See the [Auth0 Security Bulletin CVE 2018-15121](/security/bulletins/cve-2018-15121) for more details. -::: - -Previously, Auth0 maintained a NuGet package with OWIN middleware which developers could use to integrate Auth0 into the ASP.NET (OWIN) applications. With the move to OWIN 4, the built-in OpenID Connect middleware was re-evaluated, and the decision was made to instead use this middleware as opposed to the custom Auth0 middleware. - -It is suggested that existing customers migrate their OWIN 3.x applications from OWIN 4.0 and replace the Auth0 middleware with the OpenID Connect middleware on which the new quickstart is based. - -To upgrade from OWIN 3.x using the Auth0 middleware to OWIN 4 using the OpenID Connect middleware, you can follow these steps: - -1. Upgrade all the OWIN related NuGet packages in your project to version 4.1.0. -1. Add a reference to the `Microsoft.Owin.Security.OpenIdConnect` NuGet package. -1. Remove the existing reference to the `Auth0-ASPNET-Owin` NuGet package which contains the previous OWIN 3.x based middleware. -1. Update your `Startup.cs` file to add the following namespaces: - - ``` - using Microsoft.IdentityModel.Protocols.OpenIdConnect; - using Microsoft.IdentityModel.Tokens; - using Microsoft.Owin.Security.OpenIdConnect; - ``` - -1. Also, remove the reference to the `Auth0.Owin` namespace from your `Startup.cs` file. -1. Remove the registration of the previously used Auth0 OWIN middleware from the `Configuration` method of your `Startup` class. -1. Follow the [steps in the OWIN Login Quickstart](/quickstart/webapp/aspnet-owin/01-login#install-and-configure-the-openid-connect-middleware) to register the OpenID Connect middleware in your `Startup` class. diff --git a/articles/quickstart/webapp/aspnet-owin/_includes/_login.md b/articles/quickstart/webapp/aspnet-owin/_includes/_login.md deleted file mode 100644 index f682ba13c9..0000000000 --- a/articles/quickstart/webapp/aspnet-owin/_includes/_login.md +++ /dev/null @@ -1,293 +0,0 @@ - - -## Configure Your Application to Use Auth0 - -[Universal Login](/hosted-pages/login) is the easiest way to set up authentication in your application. We recommend using it for the best experience, best security and the fullest array of features. This guide will use it to provide a way for your users to log in to your ASP.NET MVC 5 application. - -::: note -You can also create a custom login for prompting the user for their username and password. To learn how to do this in your application, follow the [Custom Login sample](https://github.com/auth0-samples/auth0-aspnet-owin-mvc-samples/tree/master/Samples/custom-login). -::: - -### Install and configure the OpenID Connect middleware - -::: note - This quickstart makes use of OWIN middleware and as such, you need to use OWIN in your application. If your application is not currently making use of OWIN, please refer to Microsoft's OWIN documentation to enable it in your application. -::: - -The easiest way to enable authentication with Auth0 in your ASP.NET MVC application is to use the OWIN OpenID Connect middleware which is available in the `Microsoft.Owin.Security.OpenIdConnect` NuGet package, so install that first: - -```bash -Install-Package Microsoft.Owin.Security.OpenIdConnect -``` - -You must also install the following middleware library to enable cookie authentication in your project: - -```bash -Install-Package Microsoft.Owin.Security.Cookies -``` - -:::note -There are issues when configuring the OWIN cookie middleware and System.Web cookies at the same time. Please read about the [System.Web cookie integration issues doc](https://github.com/aspnet/AspNetKatana/wiki/System.Web-response-cookie-integration-issues) to learn about how to mitigate these problems -::: - -Now go to the `Configuration` method of your `Startup` class and configure the cookie middleware as well as the Auth0 middleware. - -```cs -// Startup.cs -using Microsoft.IdentityModel.Protocols.OpenIdConnect; -using Microsoft.IdentityModel.Tokens; -using Microsoft.Owin; -using Microsoft.Owin.Host.SystemWeb; -using Microsoft.Owin.Security; -using Microsoft.Owin.Security.Cookies; -using Microsoft.Owin.Security.OpenIdConnect; -using MvcApplication.Support; -using Owin; - -public void Configuration(IAppBuilder app) -{ - // Configure Auth0 parameters - string auth0Domain = ConfigurationManager.AppSettings["auth0:Domain"]; - string auth0ClientId = ConfigurationManager.AppSettings["auth0:ClientId"]; - string auth0RedirectUri = ConfigurationManager.AppSettings["auth0:RedirectUri"]; - string auth0PostLogoutRedirectUri = ConfigurationManager.AppSettings["auth0:PostLogoutRedirectUri"]; - - // Set Cookies as default authentication type - app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType); - app.UseCookieAuthentication(new CookieAuthenticationOptions - { - AuthenticationType = CookieAuthenticationDefaults.AuthenticationType, - LoginPath = new PathString("/Account/Login"), - - // Configure SameSite as needed for your app. Lax works well for most scenarios here but - // you may want to set SameSiteMode.None for HTTPS - CookieSameSite = SameSiteMode.Lax, - - // More information on why the CookieManager needs to be set can be found here: - // https://github.com/aspnet/AspNetKatana/wiki/System.Web-response-cookie-integration-issues - CookieManager = new SameSiteCookieManager(new SystemWebCookieManager()) - }); - - // Configure Auth0 authentication - app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions - { - AuthenticationType = "Auth0", - - Authority = $"https://{auth0Domain}", - - ClientId = auth0ClientId, - - RedirectUri = auth0RedirectUri, - PostLogoutRedirectUri = auth0PostLogoutRedirectUri, - - TokenValidationParameters = new TokenValidationParameters - { - NameClaimType = "name" - }, - - // More information on why the CookieManager needs to be set can be found here: - // https://docs.microsoft.com/en-us/aspnet/samesite/owin-samesite - CookieManager = new SameSiteCookieManager(new SystemWebCookieManager()), - - Notifications = new OpenIdConnectAuthenticationNotifications - { - RedirectToIdentityProvider = notification => - { - if (notification.ProtocolMessage.RequestType == OpenIdConnectRequestType.Logout) - { - var logoutUri = $"https://{auth0Domain}/v2/logout?client_id={auth0ClientId}"; - - var postLogoutUri = notification.ProtocolMessage.PostLogoutRedirectUri; - if (!string.IsNullOrEmpty(postLogoutUri)) - { - if (postLogoutUri.StartsWith("/")) - { - // transform to absolute - var request = notification.Request; - postLogoutUri = request.Scheme + "://" + request.Host + request.PathBase + postLogoutUri; - } - logoutUri += $"&returnTo={ Uri.EscapeDataString(postLogoutUri)}"; - } - - notification.Response.Redirect(logoutUri); - notification.HandleResponse(); - } - return Task.FromResult(0); - } - } - }); -} -``` - -It is essential that you register both the cookie middleware and the OpenID Connect middleware, as they are required (in that order) for the authentication to work. The OpenID Connect middleware will handle the authentication with Auth0. Once the user has authenticated, their identity will be stored in the cookie middleware. - -In the code snippet above, note that the `AuthenticationType` is set to **Auth0**. This will be used in the next section to challenge the OpenID Connect middleware and start the authentication flow. Also note code in the `RedirectToIdentityProvider` notification event which constructs the correct [logout URL](/logout). - -## Trigger Authentication - -### Add Login and Logout methods - -Next, you will need to add `Login` and `Logout` actions to the `AccountController`. - -The `Login` action will challenge the OpenID Connect middleware to start the authentication flow. For the `Logout` action, you will need to sign the user out of the cookie middleware (which will clear the local application session), as well as the OpenID Connect middleware. For more information, you can refer to the Auth0 [Logout](/logout) documentation. - -```cs -// Controllers/AccountController.cs - -public class AccountController : Controller -{ - public ActionResult Login(string returnUrl) - { - HttpContext.GetOwinContext().Authentication.Challenge(new AuthenticationProperties - { - RedirectUri = returnUrl ?? Url.Action("Index", "Home") - }, - "Auth0"); - return new HttpUnauthorizedResult(); - } - - [Authorize] - public void Logout() - { - HttpContext.GetOwinContext().Authentication.SignOut(CookieAuthenticationDefaults.AuthenticationType); - HttpContext.GetOwinContext().Authentication.SignOut("Auth0"); - } - - [Authorize] - public ActionResult Claims() - { - return View(); - } -} -``` - -### Add Login and Logout links - -To add the Login and Logout links to the navigation bar, head over to `/Views/Shared/_Layout.cshtml` and add code to the navigation bar section which displays a Logout link when the user is authenticated, otherwise a Login link. These will link to the `Logout` and `Login` actions of the `AccountController` respectively: - -```html - - - -``` - -### Obtain an Access Token for calling an API - -If you want to call an API from your MVC application, you need to obtain an Access Token issued for the API you want to call. To receive and Access Token, pass an additional audience parameter containing the API identifier to the Auth0 authorization endpoint. - -You will also need to configure the OpenID Connect middleware to add the ID Token and Access Token as claims on the `ClaimsIdentity`. - -Update the OpenID Connect middleware registration in your `Startup` class as follows: - -1. Set the `ResponseType` to `OpenIdConnectResponseType.Code`. This will inform the OpenID Connect middleware to extract the Access Token and store it in the `ProtocolMessage`. -1. Set `RedeemCode` to `true`. -1. Set the `ClientSecret` to the application's Client Secret, which you can find in your Auth0 dashboard. -1. Handle the `RedirectToIdentityProvider` to check to an authentication request and add the `audience` parameter. -1. Handle the `SecurityTokenValidated` to extract the ID Token and Access Token from the `ProtocolMessage` and store them as claims. - -```csharp -// Startup.cs - -public void Configuration(IAppBuilder app) -{ - // Some code omitted for brevity... - - string auth0ClientSecret = ConfigurationManager.AppSettings["auth0:ClientSecret"]; - string auth0Audience = ConfigurationManager.AppSettings["auth0:Audience"]; - - // Configure Auth0 authentication - app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions - { - //... - - ClientSecret = auth0ClientSecret, - ResponseType = OpenIdConnectResponseType.Code, - RedeemCode = true, - //... - - Notifications = new OpenIdConnectAuthenticationNotifications - { - SecurityTokenValidated = notification => - { - notification.AuthenticationTicket.Identity.AddClaim(new Claim("id_token", notification.ProtocolMessage.IdToken)); - notification.AuthenticationTicket.Identity.AddClaim(new Claim("access_token", notification.ProtocolMessage.AccessToken)); - - return Task.FromResult(0); - }, - RedirectToIdentityProvider = notification => - { - if (notification.ProtocolMessage.RequestType == OpenIdConnectRequestType.Authentication) - { - // The context's ProtocolMessage can be used to pass along additional query parameters - // to Auth0's /authorize endpoint. - // - // Set the audience query parameter to the API identifier to ensure the returned Access Tokens can be used - // to call protected endpoints on the corresponding API. - notification.ProtocolMessage.SetParameter("audience", auth0Audience); - } - else if (notification.ProtocolMessage.RequestType == OpenIdConnectRequestType.Logout) - { - //... - } - return Task.FromResult(0); - } - } - }); - -} -``` - -As the above snippet is reading the `Auth0:ClientSecret` and `Auth0:Audience` from the appSettings, ensure they exist in your web.config and has their values set to the corresponding API Identifier for which you want to be retrieving an Access Token as well as the Client Secret for the application whose Client ID has been registered. - -``` xml - - - - - - -``` - -To access the ID Token and Access Token from one of your controllers, cast the `User.Identity` property to a `ClaimsIdentity`, and then find the particular claim by calling the `FindFirst` method. - -``` csharp -// Controllers/AccountController.cs - -[Authorize] -public ActionResult Tokens() -{ - var claimsIdentity = User.Identity as ClaimsIdentity; - - // Extract tokens - string accessToken = claimsIdentity?.FindFirst(c => c.Type == "access_token")?.Value; - string idToken = claimsIdentity?.FindFirst(c => c.Type == "id_token")?.Value; - - // Now you can use the tokens as appropriate... -} -``` \ No newline at end of file diff --git a/articles/quickstart/webapp/aspnet-owin/index.yml b/articles/quickstart/webapp/aspnet-owin/index.yml index c04cdf1368..a14bac0006 100644 --- a/articles/quickstart/webapp/aspnet-owin/index.yml +++ b/articles/quickstart/webapp/aspnet-owin/index.yml @@ -3,8 +3,8 @@ title: ASP.NET (OWIN) image: /media/platforms/asp.png logo: dotnet author: - name: Damien Guard - email: damien.guard@auth0.com + name: Frederik Prijck + email: frederik.prijck@okta.com community: false topics: - quickstart @@ -21,9 +21,6 @@ seo_alias: aspnet-owin default_article: 01-login articles: - 01-login - - 02-user-profile - - 03-authorization - - 04-migrating hidden_articles: - interactive show_steps: true @@ -35,7 +32,7 @@ requirements: - Microsoft Visual Studio 2017 - Microsoft.Owin.Security.OpenIdConnect v4.1.0 and up next_steps: - - path: 03-authorization + - path: 01-login list: - text: Configure other identity providers icon: 345 diff --git a/articles/quickstart/webapp/aspnet-owin/interactive.md b/articles/quickstart/webapp/aspnet-owin/interactive.md index 9ae64f0ae5..1272924c03 100644 --- a/articles/quickstart/webapp/aspnet-owin/interactive.md +++ b/articles/quickstart/webapp/aspnet-owin/interactive.md @@ -57,24 +57,24 @@ In the code snippet, `AuthenticationType` is set to **Auth0**. Use `Authenticati ## Add login to your application {{{ data-action=code data-code="AccountController.cs#7:16" }}} -To allow users to login to your ASP.NET OWIN application, add a `Login` action to your controller. +To allow users to log in to your ASP.NET OWIN application, add a `Login` action to your controller. Call `HttpContext.GetOwinContext().Authentication.Challenge` and pass `"Auth0"` as the authentication scheme. This invokes the OIDC authentication handler that was registered earlier. Be sure to specify the corresponding `AuthenticationProperties`, including a `RedirectUri`. -After succesfully calling `HttpContext.GetOwinContext().Authentication.Challenge`, the user redirects to Auth0 and signed in to both the OIDC middleware and the cookie middleware upon being redirected back to your application. This will allow the users to be authenticated on subsequent requests. +After successfully calling `HttpContext.GetOwinContext().Authentication.Challenge`, the user redirects to Auth0 and signed in to both the OIDC middleware and the cookie middleware upon being redirected back to your application. This will allow the users to be authenticated on subsequent requests. ::::checkpoint :::checkpoint-default Now that you have configured Login, run your application to verify that: -* Navigating to your `Login` action will redirects to Auth0 +* Navigating to your `Login` action will redirect to Auth0 * Entering your credentials will redirect you back to your application. ::: :::checkpoint-failure -Sorry about that. Here's a couple things to double check: +Sorry about that. Here are a couple of things to double-check: * make sure the correct application is selected * did you save after entering your URLs? * make sure the domain and client ID are configured correctly @@ -89,7 +89,7 @@ Still having issues? Check out our [documentation](https://auth0.com/docs) or vi From your controller's action, call `HttpContext.GetOwinContext().Authentication.SignOut` with the `CookieAuthenticationDefaults.AuthenticationType` authentication scheme to log the user out of your application. -Additionaly, if you want to log the user out from Auth0 (this *might* also log them out of other applications that rely on Single Sign-On), call `HttpContext.GetOwinContext().Authentication.SignOut` with the `"Auth0"` authentication scheme. +Additionally, if you want to log the user out from Auth0 (this *might* also log them out of other applications that rely on Single Sign-On), call `HttpContext.GetOwinContext().Authentication.SignOut` with the `"Auth0"` authentication scheme. ::::checkpoint @@ -97,12 +97,12 @@ Additionaly, if you want to log the user out from Auth0 (this *might* also log t Now that you have configured Logout, run your application to verify that: * Navigating to your `Logout` action ensures the user is logged out. -* Duing logout, you redirect to Auth0 and instantly redirect back to your own application during log out. +* During logout, you redirect to Auth0 and instantly redirect back to your application during log out. ::: :::checkpoint-failure -Sorry about that. Here's a couple things to double check: +Sorry about that. Here are a couple of things to double-check: * make sure the correct application is selected * did you save after entering your URLs? * make sure the domain and client ID are configured correctly @@ -124,12 +124,12 @@ To create a user profile, retrieve a user's name, email address, and profile ima :::checkpoint-default Now that you have set up your action to render the user's profile, run your application to verify that: -* Navigating to your `Profile` action after being succesfully logged in, shows the user's profile. +* Navigating to your `Profile` action after being successfully logged in, shows the user's profile. ::: :::checkpoint-failure -Sorry about that. Here's a couple things to double check: +Sorry about that. Here are a couple things to double-check: * make sure the correct application is selected * make sure the domain and client ID are configured correctly * Did you set `openid profile email` as the scope?