【问题标题】:OWIN-Getting dbo.AspNetUser Id in Web API controller. User.Identity.GetUserId() is nullOWIN-在 Web API 控制器中获取 dbo.AspNetUser Id。 User.Identity.GetUserId() 为空
【发布时间】:2016-07-29 01:51:24
【问题描述】:

我正在尝试获取对身份框架分配给我的用户的 ID 的引用,以便我可以在我的 sql 数据库中将其设为外键,它目前返回为 null:

我的 Startup.cs:

  public class Startup
  {
    public void Configuration(IAppBuilder app)
    {
        HttpConfiguration config = new HttpConfiguration();

        ConfigureOAuth(app);

        config.Routes.MapHttpRoute("DefaultAPI",
            "api/{controller}/{id}",
            new { id = RouteParameter.Optional });

        config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));

        app.UseCors(CorsOptions.AllowAll);
        app.UseWebApi(config); 
    }

    private void ConfigureOAuth(IAppBuilder app)
    {
        OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
        {
            AllowInsecureHttp = true,
            TokenEndpointPath = new PathString("/token"),
            AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
            Provider = new SimpleAuthorizationServerProvider()
        };

        app.UseOAuthAuthorizationServer(OAuthServerOptions);
        app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
    }
}

SimpleAuthorizationServerProvider:

 public class SimpleAuthorizationServerProvider : OAuthAuthorizationServerProvider 
{
    public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
    {
        context.Validated();
    }

    public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
    {

        //context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });

        using (AuthRepository _repo = new AuthRepository())
        {
            IdentityUser user = await _repo.FindUser(context.UserName, context.Password);

            if (user == null)
            {
                context.SetError("invalid_grant", "The user name or password is incorrect.");
                return;
            }
        }

        var identity = new ClaimsIdentity(context.Options.AuthenticationType);
        identity.AddClaim(new Claim("sub", context.UserName));
        identity.AddClaim(new Claim("role", "user"));
        identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));

        context.Validated(identity);

    }
}

AuthRespository.cs:

 public class AuthRepository : IDisposable
{
    private AuthContext _ctx;
    private UserManager<IdentityUser> _userManager;

    public AuthRepository()
    {
        _ctx = new AuthContext();
        _userManager = new UserManager<IdentityUser>(new UserStore<IdentityUser>(_ctx));
    }

    public async Task<IdentityResult> RegisterUser(UserModel userModel)
    {
        IdentityUser user = new IdentityUser
        {
            UserName = userModel.UserName
        };

        var result = await _userManager.CreateAsync(user, userModel.Password);

        return result;
    }

    public async Task<IdentityUser> FindUser(string userName, string password)
    {
        IdentityUser user = await _userManager.FindAsync(userName, password);

        return user;
    }

    public void Dispose()
    {
        _ctx.Dispose();
        _userManager.Dispose();

    }
}

UserModel.cs:

 public class UserModel
{

    [Required]
    [Display(Name = "User name")]
    public string UserName { get; set; }

    [Required]
    [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
    [DataType(DataType.Password)]
    [Display(Name = "Password")]
    public string Password { get; set; }

    [DataType(DataType.Password)]
    [Display(Name = "Confirm password")]
    [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
    public string ConfirmPassword { get; set; }

}

当控制流进入 GrantResourceOwnerCredentials context.UserName 已正确设置但 context.ClientId 为空时。我怎样才能得到这条信息?

编辑:

我在代码行中看到了:

 using (AuthRepository _repo = new AuthRepository())
        {
            IdentityUser user = await _repo.FindUser(context.UserName, context.Password);

            if (user == null)
            {
                context.SetError("invalid_grant", "The user name or password is incorrect.");
                return;
            }
        }

user.Id 是我正在寻找的确切 ID。但我不允许将其分配给 context.ClientId。有什么想法吗?

【问题讨论】:

  • 您的请求中是否存在 client_id?
  • 检查我在底部所做的编辑,它不在上下文中
  • 查看此链接。 msdn.microsoft.com/en-us/library/… 您不能在 GrantResourceOwnerCredentials 内的 ClientId 中传递值,因为它是私有集。如果你想在你的 ClientId 中有价值,它应该出现在你的请求中

标签: c# asp.net-web-api oauth-2.0 asp.net-identity


【解决方案1】:

通过获取 User.Id 属性并手动将其设置为我的身份中的 SID 声明来解决此问题。它并不完美,但无论如何它都是同一个 ID。

【讨论】:

    猜你喜欢
    • 2013-10-30
    • 2016-06-04
    • 1970-01-01
    • 2023-03-12
    • 1970-01-01
    • 2021-04-08
    • 1970-01-01
    • 1970-01-01
    • 2013-11-19
    相关资源
    最近更新 更多