2016-04-07 11 views
1

IDのフレームワークが自分のユーザーを割り当てるIDへの参照を取得しようとしていますので、SQLデータベースに外部キーを作成できます。現在nullに戻ります: enter image description hereOWIN- Web APIコントローラのdbo.AspNetUser IDの取得。 User.Identity.GetUserId()が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; } 

} 

制御フローがcontext.UserNameが正しく設定されているが、context.ClientIdがnull GrantResourceOwnerCredentialsに入りました。この情報はどのように入手できますか?

編集:

私はコードの行であることを参照してください。

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に割り当てることは許されていません。何か案は?

+0

リクエストにclient_idは存在しますか? – dan

+0

下の方の編集を確認してください。文脈にはありません – Pipeline

+0

このリンクを参照してください。 https://msdn.microsoft.com/en-us/library/microsoft.owin.security.oauth.oauthgrantresourceownercredentialscontext.clientid(v=vs.113).aspx#P:Microsoft.Owin.Security.OAuth.OAuthGrantResourceOwnerCredentialsContext.ClientId GrantResourceOwnerCredentials内のClientIdはプライベートセットであるため、値を渡すことはできません。 あなたのClientIdに価値を持たせたい場合、それはあなたの要求に存在するはずです – dan

答えて

0

これを回避するには、User.Idプロパティを取得し、手動でこれを自分のIDのSIDクレームに設定します。それは完璧ではありませんが、とにかく同じIDです。

+0

この仲間をどう解決しましたか? –

関連する問題