locked
Azure Authentication using OAuth in ASP.NET WebForms NOT MVC RRS feed

  • Question

  • User430178104 posted

    Hi,

    I want to implement Azure authentication for my application using OAuth. Once I get the Barrier token I need to use this for other action in my application.

    Can anyone provide code snippet for this? I am not using MVC using legacy ASP.NET

    Tuesday, May 8, 2018 2:43 PM

Answers

  • User283571144 posted

    Hi pathipati,

    According to your description , I suggest you could follow below steps to implement azure AD login in asp.net web form.

    1.Install the OWIN middleware NuGet packages from Nuget Package:

    Install-Package Microsoft.Owin.Security.OpenIdConnect
    Install-Package Microsoft.Owin.Security.Cookies
    Install-Package Microsoft.Owin.Host.SystemWeb

    2.Right-click on the project's root folder: > Add > New Item... > OWIN Startup class. Name it Startup.cs

    3.Add OWIN and Microsoft.IdentityModel references to Startup.cs:

    using Microsoft.Owin;
    using Owin;
    using Microsoft.IdentityModel.Protocols.OpenIdConnect;
    using Microsoft.IdentityModel.Tokens;
    using Microsoft.Owin.Security;
    using Microsoft.Owin.Security.Cookies;
    using Microsoft.Owin.Security.OpenIdConnect;
    using Microsoft.Owin.Security.Notifications;

    4.Replace Startup class with the code below:

    public class Startup
    {
        // The Client ID is used by the application to uniquely identify itself to Azure AD.
        string clientId = System.Configuration.ConfigurationManager.AppSettings["ClientId"];
    
        // RedirectUri is the URL where the user will be redirected to after they sign in.
        string redirectUri = System.Configuration.ConfigurationManager.AppSettings["RedirectUri"];
    
        // Tenant is the tenant ID (e.g. contoso.onmicrosoft.com, or 'common' for multi-tenant)
        static string tenant = System.Configuration.ConfigurationManager.AppSettings["Tenant"];
    
        // Authority is the URL for authority, composed by Azure Active Directory v2 endpoint and the tenant name (e.g. https://login.microsoftonline.com/contoso.onmicrosoft.com/v2.0)
        string authority = String.Format(System.Globalization.CultureInfo.InvariantCulture, System.Configuration.ConfigurationManager.AppSettings["Authority"], tenant);
    
        /// <summary>
        /// Configure OWIN to use OpenIdConnect 
        /// </summary>
        /// <param name="app"></param>
        public void Configuration(IAppBuilder app)
        {
            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
    
            app.UseCookieAuthentication(new CookieAuthenticationOptions());
            app.UseOpenIdConnectAuthentication(
                new OpenIdConnectAuthenticationOptions
                {
                    // Sets the ClientId, authority, RedirectUri as obtained from web.config
                    ClientId = clientId,
                    Authority = authority,
                    RedirectUri = redirectUri,
                    // PostLogoutRedirectUri is the page that users will be redirected to after sign-out. In this case, it is using the home page
                    PostLogoutRedirectUri = redirectUri,
                    Scope = OpenIdConnectScope.OpenIdProfile,
                    // ResponseType is set to request the id_token - which contains basic information about the signed-in user
                    ResponseType = OpenIdConnectResponseType.IdToken,
                    // ValidateIssuer set to false to allow personal and work accounts from any organization to sign in to your application
                    // To only allow users from a single organizations, set ValidateIssuer to true and 'tenant' setting in web.config to the tenant name
                    // To allow users from only a list of specific organizations, set ValidateIssuer to true and use ValidIssuers parameter 
                    TokenValidationParameters = new TokenValidationParameters()
                    {
                        ValidateIssuer = false
                    },
                    // OpenIdConnectAuthenticationNotifications configures OWIN to send notification of failed authentications to OnAuthenticationFailed method
                    Notifications = new OpenIdConnectAuthenticationNotifications
                    {
                        AuthenticationFailed = OnAuthenticationFailed
                    }
                }
            );
        }
    
        /// <summary>
        /// Handle failed authentication requests by redirecting the user to the home page with an error in the query string
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        private Task OnAuthenticationFailed(AuthenticationFailedNotification<OpenIdConnectMessage, OpenIdConnectAuthenticationOptions> context)
        {
            context.HandleResponse();
            context.Response.Redirect("/?errormessage=" + context.Exception.Message);
            return Task.FromResult(0);
        }
    }

    Add the parameter value as below:

    <add key="ClientId" value="Enter_the_Application_Id_here" />
    <add key="redirectUri" value="Enter_the_Redirect_URL_here" />
    <add key="Tenant" value="common" />
    <add key="Authority" value="https://login.microsoftonline.com/{0}/v2.0" />

    5.Add Login and logout button in the aspx page.

        <asp:Button ID="Login" runat="server" Text="Button" OnClick="Login_Click" />
        <asp:Button ID="Loginout" runat="server" Text="Button"  OnClick="Loginout_Click"  />
        <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>

    Code-behind:

            protected void Page_Load(object sender, EventArgs e)
            {
                if (Request.IsAuthenticated)
                {
                    Label1.Text =  System.Security.Claims.ClaimsPrincipal.Current.FindFirst("name").Value;
                }
            }
    
            protected void Login_Click(object sender, EventArgs e)
            {
    
                Context.GetOwinContext().Authentication.Challenge(
        new AuthenticationProperties { RedirectUri = "/" },
        OpenIdConnectAuthenticationDefaults.AuthenticationType);
            }
    
            protected void Loginout_Click(object sender, EventArgs e)
            {
                Context.GetOwinContext().Authentication.SignOut(
                   OpenIdConnectAuthenticationDefaults.AuthenticationType,
                   CookieAuthenticationDefaults.AuthenticationType);
            }

    More details about how to create azure AD in portal and get the ClientId,Authority,RedirectUri, you could refer to below article.

    https://azure.microsoft.com/en-us/resources/samples/active-directory-dotnet-webapp-openidconnect/ 

    Best Regards,

    Brando

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, May 9, 2018 7:07 AM

All replies

  • User283571144 posted

    Hi pathipati,

    According to your description , I suggest you could follow below steps to implement azure AD login in asp.net web form.

    1.Install the OWIN middleware NuGet packages from Nuget Package:

    Install-Package Microsoft.Owin.Security.OpenIdConnect
    Install-Package Microsoft.Owin.Security.Cookies
    Install-Package Microsoft.Owin.Host.SystemWeb

    2.Right-click on the project's root folder: > Add > New Item... > OWIN Startup class. Name it Startup.cs

    3.Add OWIN and Microsoft.IdentityModel references to Startup.cs:

    using Microsoft.Owin;
    using Owin;
    using Microsoft.IdentityModel.Protocols.OpenIdConnect;
    using Microsoft.IdentityModel.Tokens;
    using Microsoft.Owin.Security;
    using Microsoft.Owin.Security.Cookies;
    using Microsoft.Owin.Security.OpenIdConnect;
    using Microsoft.Owin.Security.Notifications;

    4.Replace Startup class with the code below:

    public class Startup
    {
        // The Client ID is used by the application to uniquely identify itself to Azure AD.
        string clientId = System.Configuration.ConfigurationManager.AppSettings["ClientId"];
    
        // RedirectUri is the URL where the user will be redirected to after they sign in.
        string redirectUri = System.Configuration.ConfigurationManager.AppSettings["RedirectUri"];
    
        // Tenant is the tenant ID (e.g. contoso.onmicrosoft.com, or 'common' for multi-tenant)
        static string tenant = System.Configuration.ConfigurationManager.AppSettings["Tenant"];
    
        // Authority is the URL for authority, composed by Azure Active Directory v2 endpoint and the tenant name (e.g. https://login.microsoftonline.com/contoso.onmicrosoft.com/v2.0)
        string authority = String.Format(System.Globalization.CultureInfo.InvariantCulture, System.Configuration.ConfigurationManager.AppSettings["Authority"], tenant);
    
        /// <summary>
        /// Configure OWIN to use OpenIdConnect 
        /// </summary>
        /// <param name="app"></param>
        public void Configuration(IAppBuilder app)
        {
            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
    
            app.UseCookieAuthentication(new CookieAuthenticationOptions());
            app.UseOpenIdConnectAuthentication(
                new OpenIdConnectAuthenticationOptions
                {
                    // Sets the ClientId, authority, RedirectUri as obtained from web.config
                    ClientId = clientId,
                    Authority = authority,
                    RedirectUri = redirectUri,
                    // PostLogoutRedirectUri is the page that users will be redirected to after sign-out. In this case, it is using the home page
                    PostLogoutRedirectUri = redirectUri,
                    Scope = OpenIdConnectScope.OpenIdProfile,
                    // ResponseType is set to request the id_token - which contains basic information about the signed-in user
                    ResponseType = OpenIdConnectResponseType.IdToken,
                    // ValidateIssuer set to false to allow personal and work accounts from any organization to sign in to your application
                    // To only allow users from a single organizations, set ValidateIssuer to true and 'tenant' setting in web.config to the tenant name
                    // To allow users from only a list of specific organizations, set ValidateIssuer to true and use ValidIssuers parameter 
                    TokenValidationParameters = new TokenValidationParameters()
                    {
                        ValidateIssuer = false
                    },
                    // OpenIdConnectAuthenticationNotifications configures OWIN to send notification of failed authentications to OnAuthenticationFailed method
                    Notifications = new OpenIdConnectAuthenticationNotifications
                    {
                        AuthenticationFailed = OnAuthenticationFailed
                    }
                }
            );
        }
    
        /// <summary>
        /// Handle failed authentication requests by redirecting the user to the home page with an error in the query string
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        private Task OnAuthenticationFailed(AuthenticationFailedNotification<OpenIdConnectMessage, OpenIdConnectAuthenticationOptions> context)
        {
            context.HandleResponse();
            context.Response.Redirect("/?errormessage=" + context.Exception.Message);
            return Task.FromResult(0);
        }
    }

    Add the parameter value as below:

    <add key="ClientId" value="Enter_the_Application_Id_here" />
    <add key="redirectUri" value="Enter_the_Redirect_URL_here" />
    <add key="Tenant" value="common" />
    <add key="Authority" value="https://login.microsoftonline.com/{0}/v2.0" />

    5.Add Login and logout button in the aspx page.

        <asp:Button ID="Login" runat="server" Text="Button" OnClick="Login_Click" />
        <asp:Button ID="Loginout" runat="server" Text="Button"  OnClick="Loginout_Click"  />
        <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>

    Code-behind:

            protected void Page_Load(object sender, EventArgs e)
            {
                if (Request.IsAuthenticated)
                {
                    Label1.Text =  System.Security.Claims.ClaimsPrincipal.Current.FindFirst("name").Value;
                }
            }
    
            protected void Login_Click(object sender, EventArgs e)
            {
    
                Context.GetOwinContext().Authentication.Challenge(
        new AuthenticationProperties { RedirectUri = "/" },
        OpenIdConnectAuthenticationDefaults.AuthenticationType);
            }
    
            protected void Loginout_Click(object sender, EventArgs e)
            {
                Context.GetOwinContext().Authentication.SignOut(
                   OpenIdConnectAuthenticationDefaults.AuthenticationType,
                   CookieAuthenticationDefaults.AuthenticationType);
            }

    More details about how to create azure AD in portal and get the ClientId,Authority,RedirectUri, you could refer to below article.

    https://azure.microsoft.com/en-us/resources/samples/active-directory-dotnet-webapp-openidconnect/ 

    Best Regards,

    Brando

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, May 9, 2018 7:07 AM
  • User430178104 posted

    Hi Brando,

    Thanks for your valuable response.

    1) The above example is working fine until the authentication. after authentication it is redirected to my website and showing #405 error. Please let me know if there are any other settings required. 

    2) After redirecting to my website i need to read barrier token from Azure. is it possible?

    Wednesday, May 9, 2018 12:55 PM
  • User430178104 posted
    Now I have resolved the 405 error but I am not getting the token
    Thursday, May 10, 2018 1:54 AM
  • User283571144 posted

    Hi pathipati,

    After redirecting to my website i need to read barrier token from Azure. is it possible?

    As far as I know,  there are multiple kinds of tokens which we could read from Azure.

    For example: Id token, access token, refresh token...

    Normally, we will get the id  token or access token.

    ID token :

    The ID token is a form of sign-in security token that your app receives when performing authentication using OpenID Connect. They are represented as JWTs, and contain claims that you can use for signing the user into your app.

    Access token:

    Upon successful authentication, Azure AD returns an access token, which can be used to access protected resources. 

    More details about azure AD token, I suggest you could refer to below article.

    https://docs.microsoft.com/en-us/azure/active-directory/develop/active-directory-token-and-claims#access-tokens 

    Could you please tell me which kinds of token you want to get from azure AD?

    Best Regards,

    Brando

    Friday, May 11, 2018 7:08 AM