简体   繁体   English

在 MVC 客户端(IdentityServer)中自动获取 access_token

[英]Automatically get access_token in MVC client (IdentityServer)

I code “MVC Client” just as in “Creating an MVC client” https://identityserver4.readthedocs.io/en/latest/quickstarts/2_interactive_aspnetcore.html#creating-an-mvc-client My main goal is when access_token is expired to get new one with refresh_token.我在“创建 MVC 客户端”中编写“MVC 客户端”代码https://identityserver4.readthedocs.io/en/latest/quickstarts/2_interactive_aspnetcore.html#creating-an-mvc-client我的主要目标是 access_token 何时过期用 refresh_token 获得新的。 I need it not for API access but for “MVC Client” authentication/authorization.我不需要它用于 API 访问,而是用于“MVC 客户端”身份验证/授权。

So, I thought before “MVC Client” issues redirect to IdentityServer to its login page ( http://localhost:5000/connect/authorize?client_id=mvc&redirect_uri=bla , bla, bla) just intercept it and send instead of it just get new access_token (with refresh_token) w/o user need to enter his credentials.所以,我想在“MVC 客户端”问题重定向到 IdentityServer 到它的登录页面之前( http://localhost:5000/connect/authorize?client_id=mvc&redirect_uri=bla , bla, bla )只是拦截它并发送而不是它只是获取新的 access_token(带有 refresh_token),无需用户输入他的凭据。

So, I just need to get any event before “MVC Client” decides that access_token no longer valid and tries to redirect to IdentityServer login.因此,我只需要在“MVC 客户端”确定 access_token 不再有效并尝试重定向到 IdentityServer 登录之前获取任何事件。

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllersWithViews();

        JwtSecurityTokenHandler.DefaultMapInboundClaims = false;

        services.AddAuthentication(options =>
        {
            options.DefaultScheme = "Cookies";
            options.DefaultChallengeScheme = "oidc";

        })                
            .AddCookie("Cookies", options => {
                options.Cookie.Name = "MyCookie";
                options.Cookie.MaxAge = new TimeSpan(0, 0, 60);
                options.ExpireTimeSpan = new TimeSpan(0, 0, 60);
                options.SlidingExpiration = false;

                //options.Cookie.s ExpireTimeSpan   = new TimeSpan(0, 0, 1);


                options.Events = new Func<CookieAuthenticationEvents>(() =>
                {
                    var cookieAuthenticationEvents = new CookieAuthenticationEvents( );

                    var f = cookieAuthenticationEvents.OnRedirectToLogin;
                    var f1 = cookieAuthenticationEvents.OnValidatePrincipal;
                    var f2 = cookieAuthenticationEvents.OnSignedIn;

                    cookieAuthenticationEvents.OnRedirectToLogin = ( context ) =>
                    {
                        return f(context);
                    };
                    cookieAuthenticationEvents.OnValidatePrincipal = ( context ) =>
                    {
                        return f1(context);
                    };
                    cookieAuthenticationEvents.OnSignedIn = ( context ) =>
                    {
                        return f2(context);
                    };

                    return cookieAuthenticationEvents;
                }
                )( );
            })
            .AddOpenIdConnect("oidc", options =>
            {
                options.Authority = "http://localhost:5000";
                options.RequireHttpsMetadata = false;

                options.ClientId = "mvc";
                options.ClientSecret = "secret";
                options.ResponseType = "code";       
                options.SaveTokens = true;

                options.Scope.Add("email");
                options.Scope.Add("api1");
                options.Scope.Add("offline_access");


      //          options.Events = new Func<>


            options.Events = new Func<OpenIdConnectEvents>(() =>
            {
                var openIdConnectEvents = new OpenIdConnectEvents( );
                var f = openIdConnectEvents.OnAuthenticationFailed;
                var f1 = openIdConnectEvents.OnAccessDenied;
                var f2 = openIdConnectEvents.OnTokenValidated;
                var f3 = openIdConnectEvents.OnAccessDenied;
                openIdConnectEvents.OnAuthenticationFailed = ( context ) =>
                {
                    return f(context);
                };
                openIdConnectEvents.OnAccessDenied = ( context ) =>
                {
                    return f1(context);
                };
                openIdConnectEvents.OnTokenValidated = ( context ) =>
                {
                    return f2(context);
                };
                openIdConnectEvents.OnAccessDenied = ( context ) =>
                {
                    return f3(context);
                };

                return openIdConnectEvents;
            }
                )( );

            });
    }

On every line with "return f3(context);"在每一行都有“return f3(context);” I put break point with anticipation to hit it before getting to Login page of IdentityServer – no luck.我在进入 IdentityServer 的登录页面之前设置了断点,并期待击中它——不走运。

This is client config.这是客户端配置。

                new Client
            {
                ClientId = "mvc",
                ClientSecrets = { new Secret("secret".Sha256()) },

                AllowedGrantTypes = GrantTypes.Code,
                RequireConsent = false,
                RequirePkce = true,

                // where to redirect to after login
                RedirectUris = { "http://localhost:5002/signin-oidc" },

                // where to redirect to after logout
                PostLogoutRedirectUris = { "http://localhost:5002/signout-callback-oidc" },

                AllowedScopes = new List<string>
                {
                    IdentityServerConstants.StandardScopes.OpenId,
                    IdentityServerConstants.StandardScopes.Profile,
                    IdentityServerConstants.StandardScopes.Email,
                    "api1"
                },

                AlwaysIncludeUserClaimsInIdToken = true,
                AllowOfflineAccess = true,

                AccessTokenLifetime = 150,
                AuthorizationCodeLifetime = 150,
                UserSsoLifetime = 150
            }

How to do it - refresh token automatically w/o user interaction for MVC Client authentication (not for API access)怎么做 - 自动刷新令牌,无需用户交互以进行 MVC 客户端身份验证(不适用于 API 访问)

I've found a solution.我找到了解决方案。 Here it is: https://github.com/leastprivilege/AspNetCoreSecuritySamples/tree/aspnetcore21/AutomaticTokenManagement这里是: https://github.com/leastprivilege/AspNetCoreSecuritySamples/tree/aspnetcore21/AutomaticTokenManagement

The key point here is to override this method这里的重点是覆盖这个方法

public override async Task ValidatePrincipal ( CookieValidatePrincipalContext context )

from class从 class

Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationEvents

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 IdentityServer MVC 令牌到期 - IdentityServer MVC Token Expiration 请求access_token Instagram - Request the access_token Instagram 在MVC应用程序中获取访问令牌 - Get access token in MVC application 客户端应用程序如何使用从访问令牌中提取的范围和资源来限制 API - identityserver4 的访问 - How client application uses the scopes and resources extracted from access token to restrict the access of API - identityserver4 Web API授权access_token验证 - Web API authorization access_token validation Asp.net Web Api 2 - 如何从C#代码获取access_token - Asp.net Web Api 2 - how to get access_token from C# code IdentityServer3:OWIN Katana中间件抛出“ invalid_client”错误,因为它无法获得令牌 - IdentityServer3: OWIN Katana middleware is throwing “invalid_client” error as it cannot get a token 如何为IdentityServer3设置MVC客户端 - How to setup an MVC client for IdentityServer3 IdentityServer4用户管理与单独的MVC客户端(AspNetIdentity) - IdentityServer4 Usermanagement with separate MVC Client (AspNetIdentity) 在Axios的httpheader中使用typescript和webpack设置access_token - set access_token in httpheader in axios using typescript and webpack
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM