Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/323.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/34.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 为什么我的asp.net身份-用户将自动注销_C#_Asp.net_Asp.net Mvc_Cookies_Asp.net Web Api2 - Fatal编程技术网

C# 为什么我的asp.net身份-用户将自动注销

C# 为什么我的asp.net身份-用户将自动注销,c#,asp.net,asp.net-mvc,cookies,asp.net-web-api2,C#,Asp.net,Asp.net Mvc,Cookies,Asp.net Web Api2,我有一个包含asp.NETMVC和asp.NETWebAPI的项目 我不知道用户为什么会自动注销,例如,当我关闭浏览器时,15分钟后我发现我需要再次登录,当我将用户重定向到银行网站进行付款时,当银行网站将用户重定向到我的网站时,它需要再次登录 我使用asp.net身份验证cookie,下面是我的StartUp.cs文件代码: public class Startup { public string Issuer { get; set; } public void Configur

我有一个包含asp.NETMVC和asp.NETWebAPI的项目

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

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

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)
                }
            });
    }
}
公共类启动
{
公共字符串颁发者{get;set;}
公共无效配置(IAppBuilder应用程序)
{
发行人=”http://localhost:37993/";
配置OAuthTokenGeneration(应用程序);
配置OAuthTokenConsumption(应用程序);
应用程序UseCors(CorsOptions.AllowAll);
GlobalConfiguration.Configure(WebApiConfig.Register);
RegisterAllAreas();
//app.UseWebApi(GlobalConfiguration.Configuration);
RouteConfig.RegisterRoutes(RouteTable.Routes);
//应用程序UseMvc(路由配置注册表);
//ConfigureWebApi(GlobalConfiguration.Configuration);
}
私有void配置OAuthTokenGeneration(IAppBuilder应用程序)
{
app.CreatePerOwinContext(()=>新LeitnerContext());
app.CreatePerOwinContext(LeitnerUserManager.Create);
app.CreatePerOwinContext(leitErrorManager.Create);
//插件OAuth承载JSON Web令牌的生成和使用将在此处显示
app.UseCookieAuthentication(新的CookieAuthenticationOptions()
{
AuthenticationType=DefaultAuthenticationTypes.ApplicationOkie,
LoginPath=new Microsoft.Owin.PathString(“/User/Login”),
ExpireTimeSpan=时间跨度从天(15)开始,
Provider=新CookieAuthenticationProvider
{
OnApplyRedirect=ctx=>
{
如果(!IsForApi(ctx.Request))
{
响应重定向(ctx.RedirectUri);
}
}
}
});
OAuthAuthorizationServerOptions=新的OAuthAuthorizationServerOptions()
{
AllowInsecureHttp=true,
TokenEndpointPath=新路径字符串(“/api/token”),
AccessTokenExpireTimeSpan=TimeSpan.FromDays(15),
Provider=新的LeitnerOAuthProvider(),
AccessTokenFormat=新的LeitnerJwtFormat(发卡机构),
};
app.useAuthAuthorizationServer(选项);
//app.UseJwtBearerAuthentication(选项);
//使用OAuthBeareAuthentication(新的OAuthBeareAuthenticationOptions());
//app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
}
私有bool IsForApi(IOwinRequest请求)
{
IHeaderDictionary headers=request.headers;
return((headers!=null)&&((headers[“Accept”]=“application/json”)| |(request.Path.StartsWithSegments(new-PathString(“/api””))));
}
私有void配置OAuthTokenConsumption(IAppBuilder应用程序)
{
var a=AudienceStore.AudiencesList[“LeitNeraAudience”];
字符串audenceId=a.ClientId;//ConfigurationManager.AppSettings[“as:audenceId”];
byte[]audencescret=textcodings.Base64Url.Decode(a.Base64Secret/*ConfigurationManager.AppSettings[“as:audencescret”]*/);
//具有[Authorize]属性的Api控制器将使用JWT进行验证
app.UseJwtBearerAuthentication(
新的JWTBeareAuthenticationOptions
{
AuthenticationMode=AuthenticationMode.Active,
AllowedAudients=new[]{audienceId},
IssuerSecurityTokenProviders=新的IIssuerSecurityTokenProvider[]
{
新的SymmetriceIsuerSecurityTokenProvider(发行人、AudienceCret)
}
});
}
}

有人知道为什么会出现这个问题吗?

可能您的
ExpireTimeSpan=TimeSpan.FromDays(15)
被忽略了

我使用的时间跨度如下:

Provider = new CookieAuthenticationProvider
          {
             OnValidateIdentity =  SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
                        validateInterval: TimeSpan.FromMinutes(15),
                        regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
          },
          SlidingExpiration = false,
          ExpireTimeSpan = TimeSpan.FromMinutes(30)

用户注销的原因是验证表单身份验证数据和视图状态数据时出错。发生这种情况的原因可能不同,包括在托管服务中使用web场。您应该在项目中检查
webconfig

如果您的
网络配置中没有
,请尝试在
网络配置中的
之后添加此代码:

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

有一些在线工具可以用来生成机器密钥。你可以检查一下

您可以从链接了解有关机器钥匙的更多信息

“15分钟后自动注销”就是由于该代码而发生的

TimeSpan.FromDays(15)
如果省略此代码,将得到所需的结果或 正常情况下,该值设置为60*24=1440(分钟-1天)。 所以通常的有效期是一天。
但您将其设置为15分钟,以便出现问题。

您的身份验证cookie在浏览器/fiddler中的外观如何?是否有可能是会话cookie?@mohsen,数据库中的securitystamp字段是否为空?你能证实吗once@Webrusterdb中的securitystamp是什么?我不知道asp.net identity是如何工作的。有没有教程可以正确学习它?我如何使用secutrystamp?@OndrejSvejdar我不知道。我怎么能看到cookie?@mohsen在您的sqlserver数据库中看到过,您将有一个关于securitystamp的专栏,检查其顺序是否正确,如果存在,值是多少我忘记了应用程序中使用的一些代码。。更新了答案。它清楚地显示了
TimeSpan.FromDays(15)
;这是15天,不是15分钟。
TimeSpan.FromDays(15)