簡體   English   中英

在ASP.NET WebForms中將OAuth與令牌一起使用Azure身份驗證不是MVC

[英]Azure Authentication using OAuth with token in ASP.NET WebForms NOT MVC

我想使用OAuth為我的WebForms實施Azure身份驗證(它對我有用)。 身份驗證后,我需要在服務器端進行驗證的令牌,它將在每個客戶端代碼中進行驗證。 但是認證后我沒有得到令牌

我已經創建了一個啟動類,並使用owin對其進行了配置,並且可以正確地進行身份驗證,但是在身份驗證之后卻無法獲取令牌。

創業班

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;
using System;
using System.Threading.Tasks;

[assembly: OwinStartup(typeof(Manager.Startup))]

namespace Manager
{
    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);
        }
    }
}

頁面加載

 protected void Page_Load(object sender, EventArgs e)
        {
            if (!Request.IsAuthenticated)
            {
                Context.GetOwinContext().Authentication.Challenge(new AuthenticationProperties { RedirectUri = "/" },
        OpenIdConnectAuthenticationDefaults.AuthenticationType);

// below codes are tested but all are giving null or empty string 

                var claimsIdentity = User.Identity as ClaimsIdentity;
                string str = claimsIdentity?.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Name)?.Value;
                string accessToken = claimsIdentity?.Claims.FirstOrDefault(c => c.Type == "access_token")?.Value;
                string idToken = claimsIdentity?.Claims.FirstOrDefault(c => c.Type == "id_token")?.Value;
                string refreshToken = claimsIdentity?.Claims.FirstOrDefault(c => c.Type == "refresh_token")?.Value;
                str = User.Identity.Name;
                GetTokenForApplication().Wait(); ;
            }

        }

預期結果是認證后的令牌認證后,實際結果未獲得令牌

令牌不會包含在ClaimsIdentity中。 使用OpenIdConnect協議在asp.net中獲取訪問令牌。 您需要重寫AuthorizationCodeReceived方法以獲得訪問令牌。

using System;
using System.Configuration;
using System.Threading.Tasks;
using Microsoft.Owin;
using Owin;
using Microsoft.IdentityModel.Protocols;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.Cookies;
using Microsoft.Owin.Security.OpenIdConnect;
using Microsoft.Owin.Security.Notifications;
using System.IdentityModel.Claims;
using ToDoGraphDemo.TokenStorage;
using System.Web;
using Microsoft.Identity.Client;

[assembly: OwinStartup(typeof(ToDoGraphDemo.Startup))]

namespace ToDoGraphDemo
{
    public class Startup
    {
        // The Client ID is used by the application to uniquely identify itself to Azure AD.
        string clientId = ConfigurationManager.AppSettings["ClientId"];
        // RedirectUri is the URL where the user will be redirected to after they sign in.
        string redirectUri = ConfigurationManager.AppSettings["RedirectUri"];
        // Tenant is the tenant ID (e.g. contoso.onmicrosoft.com, or 'common' for multi-tenant)
        static string tenant = 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, 
            ConfigurationManager.AppSettings["Authority"], tenant);
        // Scopes are the specific permissions we are requesting for the application.
        string scopes = ConfigurationManager.AppSettings["Scopes"];
        // ClientSecret is a password associated with the application in the authority. 
        // It is used to obtain an access token for the user on server-side apps.
        string clientSecret = ConfigurationManager.AppSettings["ClientSecret"];

        /// <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
            {
                ClientId = clientId,
                Authority = authority,
                RedirectUri = redirectUri,
                PostLogoutRedirectUri = redirectUri,
                Scope = "openid email profile offline_access " + scopes,

                // TokenValidationParameters allows you to control the users who are allowed to sign in
                // to your application. In this demo we only allow users associated with the specified tenant. 
                // If ValidateIssuer is set to false, anybody with a personal or work Microsoft account can 
                // sign in.
                TokenValidationParameters = new System.IdentityModel.Tokens.TokenValidationParameters()
                {
                    ValidateIssuer = true,
                    ValidIssuer = tenant
                },

                // OpenIdConnect event handlers/callbacks.
                Notifications = new OpenIdConnectAuthenticationNotifications
                {
                    AuthorizationCodeReceived = OnAuthorizationCodeReceived,
                    AuthenticationFailed = OnAuthenticationFailed
                }
            });
        }

        /// <summary>
        /// Handle authorization codes by creating a token cache then requesting and storing an access token
        /// for the user.
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        private async Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedNotification context)
        {
            string userId = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value;
            TokenCache userTokenCache = new SessionTokenCache(
                userId, context.OwinContext.Environment["System.Web.HttpContextBase"] as HttpContextBase).GetMsalCacheInstance();
            // A ConfidentialClientApplication is a server-side client application that can securely store a client secret,
            // which is not accessible by the user.
            ConfidentialClientApplication cca = new ConfidentialClientApplication(
                clientId, redirectUri, new ClientCredential(clientSecret), userTokenCache, null);
            string[] scopes = this.scopes.Split(new char[] { ' ' });

            AuthenticationResult result = await cca.AcquireTokenByAuthorizationCodeAsync(context.Code, scopes);
            var accessToken = result.AccessToken;
        }

        /// <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);
        }
    }
}

這是一個示例供您參考。

您的Page_Load使用錯誤的邏輯。 將注釋下的所有代碼(//以下代碼...)移至“ if!Request.IsAuthenticated”的“ else”子句。 if語句會將用戶重定向到AAD進行身份驗證。 驗證之后,再次執行該方法時,您將進入“ else”子句。 此外,當您進入“ else”子句時,id_token已通過驗證並轉換為ClaimsPrincipal。 id_token中出現的所有聲明都被轉換為其聲明包中的單個項目-只需遍歷該包以查看其中的內容(最好還是使用此示例 )。 您可以在Fiddler中看到網絡上正在發生的一切。

由於您僅在進行身份驗證(作用域= OpenIdProfile和responsetype = idToken),因此不會獲得任何刷新或訪問令牌。 僅當您的應用需要調用另一個API時才需要后者。 通過AAD保持會話cookie來完成刷新。 您還應該創建一個用戶authn cookie,該cookie與id_token同時有效,並在過期時重做身份驗證。 示例特定於WebForms。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM