标签: asp.net-identity-2

如何在不使用角色的情况下使用ASP.NET WebAPI实现基于声明的授权?

我有一个使用声明的ASP.Net WebAPI 2应用程序.声明在标准Identity2 AspNetUsers表中存储为两个附加列:

CREATE TABLE [dbo].[AspNetUsers] (
    [Id]                   INT            IDENTITY (1, 1) NOT NULL,
    ....
    [SubjectId]            INT            DEFAULT ((0)) NOT NULL,
    [LocationId]           INT            DEFAULT ((0)) NOT NULL,
    CONSTRAINT [PK_dbo.AspNetUsers] PRIMARY KEY CLUSTERED ([Id] ASC)
);
Run Code Online (Sandbox Code Playgroud)

我修改了ApplicationUser类,如下所示:

public class ApplicationUser : IdentityUser<int, CustomUserLogin, CustomUserRole, CustomUserClaim>
    {
        public async Task<ClaimsIdentity> GenerateUserIdentityAsync(ApplicationUserManager manager, string authenticationType)
        {
            // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
            ClaimsIdentity userIdentity = await manager.CreateIdentityAsync(this, authenticationType);
            // Add custom user claims here
            userIdentity.AddClaim(new Claim("SubjectId", this.SubjectId.ToString())); …
Run Code Online (Sandbox Code Playgroud)

asp.net asp.net-mvc asp.net-authorization asp.net-web-api asp.net-identity-2

28
推荐指数
1
解决办法
1万
查看次数

访问AccountController外部的UserManager

我试图aspnetuser从不同的控制器(而不是accountcontroller)设置表中的列的值.我一直试图访问,UserManager但我不知道如何做到这一点.

到目前为止,我已经在控制器中尝试了以下内容我想用它:

    ApplicationUser u = UserManager.FindById(User.Identity.GetUserId());
    u.IsRegComplete = true;
    UserManager.Update(u);
Run Code Online (Sandbox Code Playgroud)

这不会编译(我想因为UserManager还没有实例化控制器)

我还尝试创建一个公共方法,AccountController以接受我想要更改值的值并在那里做,但我无法弄清楚如何调用它.

public void setIsRegComplete(Boolean setValue)
{
    ApplicationUser u = UserManager.FindById(User.Identity.GetUserId());
    u.IsRegComplete = setValue;
    UserManager.Update(u);

    return;
}
Run Code Online (Sandbox Code Playgroud)

如何访问和编辑帐户控制器之外的用户数据?

更新:

我尝试在其他控制器中实例化UserManager,如下所示:

    var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(db));
    ApplicationUser u = userManager.FindById(User.Identity.GetUserId());
Run Code Online (Sandbox Code Playgroud)

我的项目符合(有点兴奋),但当我运行代码时,我收到以下错误:

Additional information: The entity type ApplicationUser is not part of the model for the current context.
Run Code Online (Sandbox Code Playgroud)

更新2:

我已将该功能移至IdentityModel(不要问我在这里抓住吸管),如下所示:

   public class ApplicationUser : IdentityUser
    {
        public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager) …
Run Code Online (Sandbox Code Playgroud)

asp.net-mvc actioncontroller asp.net-mvc-5 asp.net-identity-2

28
推荐指数
2
解决办法
3万
查看次数

ASP.NET 5标识 - 自定义SignInManager

我有一个MVC 6项目(vNext),我正在玩ASP.NET身份.在我的情况下,我不想使用使用EF(SignInManager,UserManager,UserStore)的内置东西.我有一个外部数据库,我只想进行用户名/密码查找并返回一个有效的cookie.所以我开始写自己的课程.

public class MyUser
{
    public string Id { get; set; }
    public string UserName { get; set; }
    public string Password { get; set; }
    public string PasswordHash { get; set; }
}

public class MyUserStore : IUserStore<MyUser>, IUserPasswordStore<MyUser>
{
    ...
}
Run Code Online (Sandbox Code Playgroud)

MyUserStore课堂上我使用硬编码的用户列表作为我的商店(仅用于测试目的).我重写了一些方法只是为了从硬编码的商店中返回数据.

public class MyUserManager : UserManager<MyUser>
{
    public MyUserManager(
        IUserStore<MyUser> store,
        IOptions<IdentityOptions> optionsAccessor,
        IPasswordHasher<MyUser> passwordHasher,
        IEnumerable<IUserValidator<MyUser>> userValidators,
        IEnumerable<IPasswordValidator<MyUser>> passwordValidators,
        ILookupNormalizer keyNormalizer,
        IdentityErrorDescriber errors,
        IEnumerable<IUserTokenProvider<MyUser>> tokenProviders,
        ILoggerFactory logger,
        IHttpContextAccessor contextAccessor) :
        base(store, optionsAccessor, passwordHasher, userValidators, …
Run Code Online (Sandbox Code Playgroud)

c# asp.net-identity-2 asp.net-core-mvc asp.net-core

27
推荐指数
4
解决办法
2万
查看次数

如何使用ASP.NET Identity 2.0.1强制将角色更改传播给用户?

我已经阅读了这篇文章,虽然它解释了在一段时间间隔后角色更改最终会如何传播到用户cookie,但我仍然不明白我是如何强制立即更改用户角色的.

当我更改管理员角色时,是否真的必须签署用户?如果是这样 - 怎么样?如果我使用AuthenticationManager.SignOut();然后我签署自己(管理员),而不是用户,我想改变他们的角色.

目前我await UserManager.UpdateSecurityStampAsync(user.Id);用来生成一个新的安全标记,但它不起作用.当我以另一个用户身份登录时在另一个浏览器中刷新页面时,他的声明(包括安全标记)不会更改.

c# asp.net asp.net-mvc-5 asp.net-identity-2

26
推荐指数
1
解决办法
8944
查看次数

在默认MVC5应用程序中的帐户关联步骤中从外部提供商Google和Facebook获取电子邮件

显然,您可以通过在以下FacebookAuthenticationOptions对象中添加范围来向Facebook提供商执行此操作Startup.Auth.cs:

http://blogs.msdn.com/b/webdev/archive/2013/10/16/get-more-information-from-social-providers-used-in-the-vs-2013-project-templates.aspx

List<string> scope = new List<string>() { "email" };
var x = new FacebookAuthenticationOptions();
x.Scope.Add("email");
...
app.UseFacebookAuthentication(x);
Run Code Online (Sandbox Code Playgroud)

如何与Google提供商进行相同的操作?类/对象没有x.Scope属性GoogleAuthenticationOptions!

asp.net-mvc-5 asp.net-identity asp.net-identity-2

25
推荐指数
2
解决办法
2万
查看次数

如何在不查找AspNetUserRoles表的情况下在WebAPI方法中获取用户角色?

我有一个更新状态的存储过程.根据用户的角色,存储过程具有可能允许或不允许状态更改的代码.因此,我需要将角色名称传递给存储过程.我的角色名称存储在我的javascript代码中的客户端上,但当然我需要在服务器上进行第二次检查.每个用户只有三个角色中的一个,在请求更新状态时,我可以根据客户端的角色调用三种方法之一.这是我尝试过的.

我正在使用基于承载令牌的身份验证和ASP.NET Identity 2.1的WebApi,并且应用程序始终在浏览器中运行.我的用户已经设置了适当的角色.

我设置了一些代码来获取userId,然后转到AspNetUserRoles表以获取方法开头的角色.但是我注意到这需要大约500毫秒才能运行.作为替代方案,我正在考虑以下内容:

    [HttpPut]
    [Authorize(Roles = "Admin")]
    [Route("AdminUpdateStatus/{userTestId:int}/{userTestStatusId:int}")]
    public async Task<IHttpActionResult> AdminUpdateStatus(int userTestId, int userTestStatusId)
    {
        return await UpdateStatusMethod(userTestId, userTestStatusId, "Admin");
    }

    [HttpPut]
    [Authorize(Roles = "Student")]
    [Route("StudentUpdateStatus/{userTestId:int}/{userTestStatusId:int}")]
    public async Task<IHttpActionResult> StudentUpdateStatus(int userTestId, int userTestStatusId)
    {
        return await UpdateStatusMethod(userTestId, userTestStatusId, "Student");
    }

    [HttpPut]
    [Authorize(Roles = "Teacher")]
    [Route("TeacherUpdateStatus/{userTestId:int}/{userTestStatusId:int}")]
    public async Task<IHttpActionResult> TeacherUpdateStatus(int userTestId, int userTestStatusId)
    {
        return await UpdateStatusMethod(userTestId, userTestStatusId, "Teacher");
    }

    private async Task<IHttpActionResult> UpdateStatusMethod(int userTestId, int userTestStatusId, string roleName)
    {
        // Call the stored procedure here …
Run Code Online (Sandbox Code Playgroud)

asp.net asp.net-mvc asp.net-web-api asp.net-identity asp.net-identity-2

25
推荐指数
2
解决办法
1万
查看次数

Asp.Net Identity无需电子邮件即可保存用户

我想保存没有电子邮件的用户,如下所示:

var user = new ApplicationUser { UserName = model.Name };
var result = await UserManager.CreateAsync(user);
Run Code Online (Sandbox Code Playgroud)

但我得到错误"电子邮件不能为空或空".这有什么解决方案吗?或者这是不可能的?

c# asp.net-identity-2

25
推荐指数
5
解决办法
1万
查看次数

'Microsoft.Owin.IOwinContext'不包含'GetUserManager'的定义,也没有扩展方法?

从Asp.Net Identity 2.0示例复制以下代码.

private ApplicationUserManager _userManager;
public ApplicationUserManager UserManager
{
    get
    {
        return // Error 
          _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
    }
    private set
    {
        _userManager = value;
    }
}
Run Code Online (Sandbox Code Playgroud)

但是它会出现以下错误?

错误3'Microsoft.Owin.IOwinContext'不包含'GetUserManager'的定义,并且没有扩展方法'GetUserManager'接受类型为'Microsoft.Owin.IOwinContext'的第一个参数'(您是否缺少using指令或装配参考?)

更新:

Microsoft.AspNet.Identity.Owin.dll的版本2已存在于...\packages\Microsoft.AspNet.Identity.Owin.2.0.1\lib \net45中.

但是,HttpContext.GetOwinContext()我的项目和样本之间的视图定义是不同的.我项目的前三行是

#region Assembly Microsoft.Owin.Host.SystemWeb.dll, v2.0.0.0
// C:\......\packages\Microsoft.Owin.Host.SystemWeb.2.0.0\lib\net45\Microsoft.Owin.Host.SystemWeb.dll
#endregion

而样本是

#region Assembly Microsoft.Owin.Host.SystemWeb.dll, v2.1.0.0
// C:\....\sample\packages\Microsoft.Owin.Host.SystemWeb.2.1.0\lib\net45\Microsoft.Owin.Host.SystemWeb.dll
#endregion

但我已经使用Neget将所有Owin Nuget软件包更新到最新版本.

asp.net asp.net-mvc-5 asp.net-identity asp.net-identity-2

23
推荐指数
1
解决办法
1万
查看次数

如何自定义Asp.net Identity 2用户名已经采取的验证消息?

我如何自定义已经采用的Asp.net Identity 2用户名验证消息(名称XYZ已被采用.)?谢谢

asp.net asp.net-mvc asp.net-mvc-5 asp.net-identity asp.net-identity-2

22
推荐指数
2
解决办法
9646
查看次数

使旧会话Cookie无效 - ASP.Net标识

一家外部公司已经对我正在开发的ASP.NET MVC 5应用程序进行了一些渗透测试.

他们提出的问题描述如下

与会话管理链接的cookie称为AspNet.ApplicationCookie.手动输入时,应用程序会对用户进行身份验证.即使用户从应用程序注销,cookie仍然有效.这意味着,旧会话cookie可以在无限时间范围内用于有效身份验证.在插入旧值的那一刻,应用程序接受它并用新生成的cookie替换它.因此,如果攻击者获得对现有cookie之一的访问权限,则将创建有效会话,其访问权限与过去相同.

我们正在使用ASP.NEt Identity 2.2

这是我们在帐户控制器上的注销操作

 [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult LogOff()
    {
        AuthenticationManager.SignOut();
        return RedirectToAction("Login", "Account");
    }
Run Code Online (Sandbox Code Playgroud)

在startup.auth.cs中

 app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
            LoginPath = new PathString("/Account/Login"),
            ExpireTimeSpan = TimeSpan.FromHours(24.0),
            Provider = new CookieAuthenticationProvider
            {
                // Enables the application to validate the security stamp when the user logs in.
                // This is a security feature which is used when you change a password or add an external login to your account.  
                OnValidateIdentity = SecurityStampValidator
             .OnValidateIdentity<ApplicationUserManager, ApplicationUser, …
Run Code Online (Sandbox Code Playgroud)

asp.net-mvc owin asp.net-identity asp.net-identity-2

21
推荐指数
1
解决办法
8519
查看次数