簡體   English   中英

OWIN-在Web API控制器中獲取dbo.AspNetUser Id。 User.Identity.GetUserId()為null

[英]OWIN-Getting dbo.AspNetUser Id in Web API controller. User.Identity.GetUserId() is null

我試圖引用Identity框架分配我的用戶的ID,這樣我就可以在我的sql db中創建一個外鍵,它當前返回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為null。 我怎樣才能得到這條信息?

編輯:

我在代碼行中看到了:

 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。 有任何想法嗎?

通過獲取User.Id屬性並在我的標識中手動將其設置為SID聲明來解決這個問題。 它並不完美,但無論如何它都是相同的ID。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM