为什么我的asp.net身份-用户将自动注销 [英] Why my asp.net identity -user will log out automatically

查看:85
本文介绍了为什么我的asp.net身份-用户将自动注销的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有asp.net MVC和asp.net WebApi的项目.

I have a project that have asp.net MVC and asp.net WebApi.

我不知道为什么用户会自动注销,例如,当我关闭浏览器时,并且15分钟后,我看到我需要再次登录,并且在将用户重定向到银行网站以进行付款之后,银行网站再次将用户重定向到我的网站需要再次登录.

I don't know why User log out automatically, for example when I close browser and after 15 minutes I see that I need to login again and after I redirect user to bank website for payment when the bank website redirect user again to my web site it need to login again.

我使用asp.net身份验证cookie,下面是我的 StartUp.cs 文件代码:

I use asp.net identity authentication cookie, below is in my StartUp.cs file code:

public class Startup
{
    public string Issuer { get; set; }
    public void Configuration(IAppBuilder app)
    {
        Issuer = "http://localhost:37993/";

        ConfigureOAuthTokenGeneration(app);
        ConfigureOAuthTokenConsumption(app);

        app.UseCors(CorsOptions.AllowAll);

        GlobalConfiguration.Configure(WebApiConfig.Register);
        AreaRegistration.RegisterAllAreas();
        //app.UseWebApi(GlobalConfiguration.Configuration);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        //app.UseMvc(RouteConfig.RegisterRoutes);

        //ConfigureWebApi(GlobalConfiguration.Configuration);

    }
    private void ConfigureOAuthTokenGeneration(IAppBuilder app)
    {
        app.CreatePerOwinContext(() => new LeitnerContext());
        app.CreatePerOwinContext<LeitnerUserManager>(LeitnerUserManager.Create);
        app.CreatePerOwinContext<LeitnerRoleManager>(LeitnerRoleManager.Create);

        // Plugin the OAuth bearer JSON Web Token tokens generation and Consumption will be here

        app.UseCookieAuthentication(new CookieAuthenticationOptions()
        {
            AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
            LoginPath = new Microsoft.Owin.PathString("/User/Login"),
            ExpireTimeSpan = TimeSpan.FromDays(15),
            Provider = new CookieAuthenticationProvider
            {
                OnApplyRedirect = ctx =>
                {
                    if (!IsForApi(ctx.Request))
                    {
                        ctx.Response.Redirect(ctx.RedirectUri);
                    }
                }
            }
        });
        OAuthAuthorizationServerOptions options = new OAuthAuthorizationServerOptions()
        {
            AllowInsecureHttp = true,
            TokenEndpointPath = new PathString("/api/token"),
            AccessTokenExpireTimeSpan = TimeSpan.FromDays(15),
            Provider = new LeitnerOAuthProvider(),
            AccessTokenFormat = new LeitnerJwtFormat(Issuer),
        };
        app.UseOAuthAuthorizationServer(options);
        //app.UseJwtBearerAuthentication(options);
        //app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
        //app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

    }

    private bool IsForApi(IOwinRequest request)
    {
        IHeaderDictionary headers = request.Headers;
        return ((headers != null) && ((headers["Accept"] == "application/json") || (request.Path.StartsWithSegments(new PathString("/api")))));
    }

    private void ConfigureOAuthTokenConsumption(IAppBuilder app)
    {
        var a = AudiencesStore.AudiencesList["LeitnerAudience"];
        string audienceId = a.ClientId;// ConfigurationManager.AppSettings["as:AudienceId"];
        byte[] audienceSecret = TextEncodings.Base64Url.Decode(a.Base64Secret/*ConfigurationManager.AppSettings["as:AudienceSecret"]*/);

        // Api controllers with an [Authorize] attribute will be validated with JWT
        app.UseJwtBearerAuthentication(
            new JwtBearerAuthenticationOptions
            {
                AuthenticationMode = AuthenticationMode.Active,
                AllowedAudiences = new[] { audienceId },
                IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[]
                {
                    new SymmetricKeyIssuerSecurityTokenProvider(Issuer, audienceSecret)
                }
            });
    }
}

有人知道为什么存在这个问题吗?

Does anyone know why this problem is there?

推荐答案

用户注销的原因是由于表单身份验证数据和视图状态数据的验证错误.发生这种情况的原因可能有多种,包括在托管服务中使用Web场.您应在项目 webconfig 中选中<machineKey>.

The reason for users logging off is because of error in the validation of forms-authentication data and view-state data. It could happen for different reasons including using web farm in hosting services.You should check <machineKey> in your project webconfig.

如果webconfig中没有<machineKey>,请尝试在webconfig中的<system.web>之后添加这段代码:

If you don't have <machineKey> in your webconfig, try adding this piece of code after <system.web> in your webconfig:

<machineKey
      validationKey="someValue"
      decryptionKey="someValue"
      validation="SHA1" decryption="AES"/>

有一些在线工具可用于生成机器密钥.您可以检查

There are some online tools from where you can generate machine key. You can check this and this.

您可以从 查看全文

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆