Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/36.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网络身份验证_C#_Asp.net_Asp.net Mvc_Asp.net Identity - Fatal编程技术网

C# asp网络身份验证

C# asp网络身份验证,c#,asp.net,asp.net-mvc,asp.net-identity,C#,Asp.net,Asp.net Mvc,Asp.net Identity,我在asp.net identity中遇到“缓存”问题,当我更改密码、名称或任何声明时,我必须重新启动应用程序以验证更改 我在SecurityContext中有这个 public class SecurityContext : IdentityDbContext<IdentityUser> { public SecurityContext() : base("Db") { } protected override void OnMod

我在asp.net identity中遇到“缓存”问题,当我更改密码、名称或任何声明时,我必须重新启动应用程序以验证更改

我在SecurityContext中有这个

public class SecurityContext : IdentityDbContext<IdentityUser>
{
    public SecurityContext()
        : base("Db")
    {
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.HasDefaultSchema("security");

        base.OnModelCreating(modelBuilder);

        modelBuilder.Entity<IdentityUser>()
            .ToTable("_Users");
        modelBuilder.Entity<IdentityRole>()
            .ToTable("_Roles");
        modelBuilder.Entity<IdentityUserRole>()
            .ToTable("_UsersRoles");
        modelBuilder.Entity<IdentityUserClaim>()
            .ToTable("_UsersClaims");
        modelBuilder.Entity<IdentityUserLogin>()
            .ToTable("_UsersLogins");
    }
}
公共类SecurityContext:IdentityDbContext
{
公共安全上下文()
:基准(“Db”)
{
}
模型创建时受保护的覆盖无效(DbModelBuilder modelBuilder)
{
HasDefaultSchema(“安全性”);
基于模型创建(modelBuilder);
modelBuilder.Entity()
.ToTable(“用户”);
modelBuilder.Entity()
.ToTable(“_角色”);
modelBuilder.Entity()
.ToTable(“_UsersRoles”);
modelBuilder.Entity()
.ToTable(“_UsersClaims”);
modelBuilder.Entity()
.ToTable(“_UsersLogins”);
}
}
登录:

public class ApplicationOAuthProvider : OAuthAuthorizationServerProvider
{
    private readonly string _PublicClientId;
    private readonly Func<UserManager<IdentityUser>> _UserManagerFactory;
    private readonly Func<RoleManager<IdentityRole>> _RoleManagerFactory;

    #region Constructors
    public ApplicationOAuthProvider(string publicClientId,
        Func<UserManager<IdentityUser>> userManagerFactory,
        Func<RoleManager<IdentityRole>> roleManagerFactory
        )
    {
        if (publicClientId == null)
            throw new ArgumentNullException("publicClientId");
        _PublicClientId = publicClientId;

        if (userManagerFactory == null)
            throw new ArgumentNullException("userManagerFactory");
        _UserManagerFactory = userManagerFactory;

        if (roleManagerFactory == null)
            throw new ArgumentNullException("roleManagerFactory");
        _RoleManagerFactory = roleManagerFactory;

    }
    #endregion Constructors

    #region GrantResourceOwnerCredentials
    public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
    {
        using (var userManager = _UserManagerFactory())
        {
            using (var roleManager = _RoleManagerFactory())
            {
                var user = await userManager.FindAsync(context.UserName, context.Password);
                if (user == null)
                {
                    context.SetError("invalid_grant", "The user name or password is incorrect.");
                    return;
                }
                // Start Login success
                var oAuthIdentity = await userManager.CreateIdentityAsync(user, context.Options.AuthenticationType);
                var cookiesIdentity = await userManager.CreateIdentityAsync(user, CookieAuthenticationDefaults.AuthenticationType);
                // Claims
                cookiesIdentity.AddClaim(new Claim(XpClaimTypes.Application, _SessionData.ApplicationName));
                // Properties
                var properties = CreateProperties(user, roleManager);
                var ticket = new AuthenticationTicket(oAuthIdentity, properties);
                context.Validated(ticket);
                context.Request.Context.Authentication.SignIn(cookiesIdentity);
                // End Login success
            }
        }
    }
    #endregion GrantResourceOwnerCredentials
}
公共类ApplicationAuthProvider:OAuthAuthorizationServerProvider
{
私有只读字符串_PublicClientId;
私有只读函数\u UserManagerFactory;
私有只读Func_RoleManager工厂;
#区域构造函数
public applicationAuthProvider(字符串publicClientId,
Func userManagerFactory,
Func RoleManager工厂
)
{
if(publicClientId==null)
抛出新ArgumentNullException(“publicClientId”);
_PublicClientId=PublicClientId;
if(userManagerFactory==null)
抛出新ArgumentNullException(“userManagerFactory”);
_UserManagerFactory=UserManagerFactory;
如果(RoleManager工厂==null)
抛出新ArgumentNullException(“RoleManager工厂”);
_RoleManager工厂=RoleManager工厂;
}
#端域构造函数
#区域GrantResourceOwnerCredentials
公共重写异步任务GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentials上下文)
{
使用(var userManager=\u UserManagerFactory())
{
使用(var roleManager=\u RoleManagerFactory())
{
var user=await userManager.FindAsync(context.UserName,context.Password);
if(user==null)
{
SetError(“无效的授权”,“用户名或密码不正确”);
返回;
}
//开始登录成功
var oAuthIdentity=await userManager.CreateIdentityAsync(user,context.Options.AuthenticationType);
var cookiesIdentity=await userManager.CreateIdentityAsync(用户,CookieAuthenticationDefaults.AuthenticationType);
//主张
AddClaim(新的声明(XpClaimTypes.Application,_SessionData.ApplicationName));
//性质
var properties=CreateProperties(用户、角色管理者);
var票证=新的身份验证票证(oAuthIdentity,属性);
上下文。已验证(票证);
context.Request.context.Authentication.sign(cookiesIdentity);
//结束登录成功
}
}
}
#endregion GrantResourceOwnerCredentials
}
排除其他方法

例如,changePassword的方法:

    #region Password
    [HttpPut]
    [Authorize(Roles = AccountRoles.Superadministrador + "," + AccountRoles.Administrador)]
    public async Task<IHttpActionResult> Password(SetPasswordBindingModel model)
    {
        if (!ModelState.IsValid)
            return BadRequest(ModelState);

        var identity = await UserManager.FindByNameAsync((Thread.CurrentPrincipal.Identity as ClaimsIdentity).Name);
        var user = await UserManager.FindByIdAsync(model.Id);

        if (!(
            (identity.Roles.Any(x => x.Role.Name == AccountRoles.Superadministrador) && user.Roles.Any(x => x.Role.Name == AccountRoles.Administrador)) ||
            (identity.Roles.Any(x => x.Role.Name == AccountRoles.Administrador) && user.Roles.Any(x => x.Role.Name == AccountRoles.Usuario))
        ))
            throw new AuthenticationException();

        // Delete password
        {
            var result = await UserManager.RemovePasswordAsync(model.Id);
            var errorResult = GetErrorResult(result);
            if (errorResult != null)
                return errorResult;
        }

        // Add password
        {
            var result = await UserManager.AddPasswordAsync(model.Id, model.Password);
            var errorResult = GetErrorResult(result);
            if (errorResult != null)
                return errorResult;
        }

        return Ok();
    }
    #endregion Password
#地区密码
[HttpPut]
[授权(角色=AccountRoles.SuperAdministrator+,“+AccountRoles.Administrator)]
公共异步任务密码(SetPasswordBindingModel)
{
如果(!ModelState.IsValid)
返回请求(ModelState);
var identity=await UserManager.FindByNameAsync((Thread.CurrentPrincipal.identity as ClaimsIdentity).Name);
var user=await UserManager.FindByIdAsync(model.Id);
如果((
(identity.Roles.Any(x=>x.Role.Name==AccountRoles.SuperAdministrator)和&user.Roles.Any(x=>x.Role.Name==AccountRoles.Administrator))||
(identity.Roles.Any(x=>x.Role.Name==AccountRoles.Administrador)和&user.Roles.Any(x=>x.Role.Name==AccountRoles.Usuario))
))
抛出新的AuthenticationException();
//删除密码
{
var result=await UserManager.RemovePasswordAsync(model.Id);
var errorResult=GetErrorResult(结果);
if(errorResult!=null)
返回错误结果;
}
//添加密码
{
var result=await UserManager.AddPasswordAsync(model.Id,model.Password);
var errorResult=GetErrorResult(结果);
if(errorResult!=null)
返回错误结果;
}
返回Ok();
}
#端域密码

以下是我遵循的步骤:

  • 登录应用程序
  • 更改密码
  • 注销应用程序
  • 使用新密码登录(表中的更改是否正确)
  • 密码错误
  • 使用旧密码登录(表中的旧密码不存在)
  • 登录成功
  • 重新启动应用程序
  • 新密码现在有效
当我更改asp.net标识的BBDD中的任何值时,也会出现相同的问题

有什么想法吗


谢谢

如果我没有记错的话,我会添加相同的问题,因为每次调用时,其中一个上下文都被持久化,而另一个上下文被重新创建

如果选中,则数据库中的值可能不正确,可能是
ApplicationAuthProvider


尝试为
ApplicationAuthProvider上的每个调用重新创建上下文

我不确定是否了解您的问题。请您重新表述这个问题好吗?我遵循了以下步骤:登录应用程序更改密码注销应用程序使用新密码登录(表中的密码已更改,更改是否正确)使用旧密码登录错误(表中的旧密码不存在)登录成功重新启动应用程序新密码现在有效我执行了以下步骤您是说