首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Asp.Net Webforms中的令牌缓存不适用于Azure?

Asp.Net Webforms中的令牌缓存不适用于Azure?
EN

Stack Overflow用户
提问于 2021-06-23 06:35:58
回答 1查看 576关注 0票数 0

我想缓存令牌,然后从webform访问它。为此,我有如下代码

Startup.cs

代码语言:javascript
复制
namespace WebFormB2B
{
    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"];
    public const string BasicSignInScopes = "openid profile offline_access";

    // 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 = BasicSignInScopes + " "+"User.Read",
                // 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
                {
                    AuthorizationCodeReceived = OnAuthorizationCodeReceived,
                    AuthenticationFailed = OnAuthenticationFailed
                }
            }
        );// ;
    }
    private async Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedNotification context)
    {
        // Upon successful sign-in, get the access token and cache it by using MSAL.
        IConfidentialClientApplication clientApp = MsalAppBuilder.BuildConfidentialClientApplication( );
        AuthenticationResult result = await clientApp.AcquireTokenByAuthorizationCode(new[] { "User.Read" }, context.Code).ExecuteAsync();
    }
    /// <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);
    }
}

}

MSALAppbuilder

代码语言:javascript
复制
public static class MsalAppBuilder
{        // The Client ID is used by the application to uniquely identify itself to Azure AD.
  static  string clientId = System.Configuration.ConfigurationManager.AppSettings["ClientId"];

    // RedirectUri is the URL where the user will be redirected to after they sign in.
    static 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"];

    static string Authority = string.Format(CultureInfo.InvariantCulture, "https://login.microsoftonline.com/{0}{1}", "common", "/v2.0");  //System.Configuration.ConfigurationManager.AppSettings["Authority"];
    public static string GetAccountId(this ClaimsPrincipal claimsPrincipal)
    {
        string oid = claimsPrincipal.GetObjectId();
        string tid = claimsPrincipal.GetTenantId();
        return $"{oid}.{tid}";
    }

    public static IConfidentialClientApplication BuildConfidentialClientApplication()
    {
        IConfidentialClientApplication clientapp = ConfidentialClientApplicationBuilder.Create(clientId)
              .WithClientSecret("XXXXXXXXXXXXX")
              .WithRedirectUri(redirectUri)
              .WithAuthority(new Uri( Authority))
              .Build();

        // After the ConfidentialClientApplication is created, we overwrite its default UserTokenCache serialization with our implementation
        IMsalTokenCacheProvider memoryTokenCacheProvider = CreateTokenCacheSerializer();
        memoryTokenCacheProvider.Initialize(clientapp.UserTokenCache);
        return clientapp;
    }

    public static async Task RemoveAccount()
    {
        IConfidentialClientApplication clientapp = ConfidentialClientApplicationBuilder.Create(clientId)
              .WithClientSecret("XXXXXXXXXXXXX")
              .WithRedirectUri(redirectUri)
              .WithAuthority(new Uri( Authority))
              .Build();

        // We only clear the user's tokens.
        IMsalTokenCacheProvider memoryTokenCacheProvider = CreateTokenCacheSerializer();
        memoryTokenCacheProvider.Initialize(clientapp.UserTokenCache);
        var userAccount = await clientapp.GetAccountAsync(ClaimsPrincipal.Current.GetAccountId());
        if (userAccount != null)
        {
            await clientapp.RemoveAsync(userAccount);
        }
    }


    private static IServiceProvider serviceProvider;

    private static IMsalTokenCacheProvider CreateTokenCacheSerializer()
    {
        if (serviceProvider == null)
        {
            // In memory token cache. Other forms of serialization are possible.
            // See https://github.com/AzureAD/microsoft-identity-web/wiki/asp-net 
            IServiceCollection services = new ServiceCollection();
            services.AddInMemoryTokenCaches();

            serviceProvider = services.BuildServiceProvider();
        }
        IMsalTokenCacheProvider msalTokenCacheProvider = serviceProvider.GetRequiredService<IMsalTokenCacheProvider>();
        return msalTokenCacheProvider;
    }

}

现在,从webform,我以这种方式访问

代码语言:javascript
复制
  private async Task method()
    {
        IConfidentialClientApplication app = MsalAppBuilder.BuildConfidentialClientApplication();
        AuthenticationResult result = null;
        var account = await app.GetAccountAsync(ClaimsPrincipal.Current.GetAccountId());
        // var accounts = await app.GetAccountsAsync();
        string[] scopes = { "User.Read" };
        result = await app.AcquireTokenSilent(scopes, account).ExecuteAsync().ConfigureAwait(false);
        // result = await app.AcquireTokenByAuthorizationCode((scopes).ExecuteAsync().ConfigureAwait(false);
    }

这个结算总是无效的。我在什么地方做错了吗?

我需要令牌,我需要传递给其他应用程序。另外,我可以在startup.cs文件中提到什么范围?就像这里一样,作用域= BasicSignInScopes +“"+"User.Read",

我使用Azure广告只是为了认证目的。

EN

回答 1

Stack Overflow用户

发布于 2021-08-08 03:53:19

IConfidentialClientApplication实例被创建并附加到MSALPerUserMemoryTokenCache实例,该实例是一个自定义缓存实现,它使用MemoryCache的共享实例来缓存令牌。当它获得访问令牌时,MSAL还将此令牌保存在其令牌缓存中。当项目的其余部分中的任何代码试图获取具有相同范围(Mail.Read)的MicrosoftGraph的访问令牌时,MSAL将返回缓存的令牌。

学习更多的这里

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68094697

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档