locked
Obtaining Bearer Token from Azure Active Directory OpenIDConnect Sign-In RRS feed

  • Question

  • User-409009743 posted

    I'm trying to build an app with both MVC and Web API using Azure Active Directory for authentication where MVC uses cookies and Web API uses bearer tokens. After the user is signed in with the OpenIDConnect method, is there a way to grab that token, so I can use it in the client side to call the Web API? Or if the user is already signed in with a cookie, is there a way to get the token then?

    Here's the code from Startup.Auth.cs

    public partial class Startup
    {
        private static string clientId = ConfigurationManager.AppSettings["ida:ClientId"];
        private static string appKey = ConfigurationManager.AppSettings["ida:AppKey"];
        private static string aadInstance = ConfigurationManager.AppSettings["ida:AADInstance"];
        private static string tenant = ConfigurationManager.AppSettings["ida:Tenant"];
        private static string postLogoutRedirectUri = ConfigurationManager.AppSettings["ida:PostLogoutRedirectUri"];
        public static string audience = ConfigurationManager.AppSettings["ida:Audience"];
    
        public static readonly string Authority = String.Format(CultureInfo.InvariantCulture, aadInstance, tenant);
    
        public void ConfigureAuth(IAppBuilder app)
        {
            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
    
            app.UseCookieAuthentication(new CookieAuthenticationOptions());
    
            app.UseWindowsAzureActiveDirectoryBearerAuthentication(
                new WindowsAzureActiveDirectoryBearerAuthenticationOptions
                {
                    Audience = audience,
                    Tenant = tenant,
                    AuthenticationType = "OAuth2Bearer"
                });
    
            app.UseOpenIdConnectAuthentication(
                new OpenIdConnectAuthenticationOptions
                {
                    ClientId = clientId,
                    Authority = Authority,
                    PostLogoutRedirectUri = postLogoutRedirectUri,
                });
        }
    }

    Thanks!

    Friday, October 17, 2014 11:40 AM

Answers

  • User1779161005 posted

    WAAD uses hybrid flow (code/id_token) and the Katana OIDC middleware only processes the id_token (and thus doesn't finish thru with the code flow of exchanging the code for the access token). You'll need to do this code/access token exchange yourself with the WAAD SDK in the AuthorizationCodeReceived event on the OIDC middleware.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, October 17, 2014 11:49 AM

All replies

  • User1779161005 posted

    WAAD uses hybrid flow (code/id_token) and the Katana OIDC middleware only processes the id_token (and thus doesn't finish thru with the code flow of exchanging the code for the access token). You'll need to do this code/access token exchange yourself with the WAAD SDK in the AuthorizationCodeReceived event on the OIDC middleware.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, October 17, 2014 11:49 AM
  • User-409009743 posted

    Thanks!

    I was getting an error (AADSTS90027: The client and resource identify the same application) during the AcquireTokenByAuthorizationCode method since the MVC and WebAPI are in the same project. To solve this, I created a new app in Azure for the WebAPI and gave the original app access to it. I was still able to leave the MVC and WebAPI in the same project though. I just had to change the Tenant for the WAAD Authentication options to the new app's App ID URI.

    Here's the final Startup.Auth.cs file.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    
    using Owin;
    using Microsoft.Owin.Security;
    using Microsoft.Owin.Security.Cookies;
    using Microsoft.Owin.Security.OpenIdConnect;
    using System.Configuration;
    using System.Globalization;
    using Microsoft.IdentityModel.Clients.ActiveDirectory;
    using System.Threading.Tasks;
    using Applicants.Utils;
    using Microsoft.Owin.Security.ActiveDirectory;
    using System.IdentityModel.Tokens;
    
    namespace Applicants
    {
        public partial class Startup
        {
            private static string clientId = ConfigurationManager.AppSettings["ida:ClientId"];
            private static string appKey = ConfigurationManager.AppSettings["ida:AppKey"];
            private static string aadInstance = ConfigurationManager.AppSettings["ida:AADInstance"];
            private static string tenant = ConfigurationManager.AppSettings["ida:Tenant"];
            private static string postLogoutRedirectUri = ConfigurationManager.AppSettings["ida:PostLogoutRedirectUri"];
            public static string apiResourceId = ConfigurationManager.AppSettings["api:ResourceId"];
    
            public static readonly string Authority = String.Format(CultureInfo.InvariantCulture, aadInstance, tenant);
    
            public void ConfigureAuth(IAppBuilder app)
            {
                app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
    
                app.UseCookieAuthentication(new CookieAuthenticationOptions());
    
                app.UseWindowsAzureActiveDirectoryBearerAuthentication(
                    new WindowsAzureActiveDirectoryBearerAuthenticationOptions
                    {
                        Tenant = tenant,
                        AuthenticationType = "OAuth2Bearer",
                        TokenValidationParameters = new TokenValidationParameters() { ValidAudience = apiResourceId}
                    });
    
                app.UseOpenIdConnectAuthentication(
                    new OpenIdConnectAuthenticationOptions
                    {
                        ClientId = clientId,
                        Authority = Authority,
                        PostLogoutRedirectUri = postLogoutRedirectUri,
                        Notifications = new OpenIdConnectAuthenticationNotifications()
                        {
                            AuthorizationCodeReceived = (context) =>
                            {
                                var code = context.Code;
    
                                string client = ConfigurationManager.AppSettings["ida:ClientId"];
                                string key = ConfigurationManager.AppSettings["ida:AppKey"];
                                ClientCredential credential = new ClientCredential(client, key);
    
                                Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext authContext =
                                    new Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext(Authority);
    
                                Uri redirectUri = new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path));
    
                                AuthenticationResult result = authContext.AcquireTokenByAuthorizationCode(
                                    context.Code, redirectUri, credential, apiResourceId);
    
                                return Task.FromResult(0);
                            }
                        }
                    });
            }
        }
    }

    Friday, October 17, 2014 4:43 PM