Web API个人帐户注册用户

时间:2014-05-23 12:10:57

标签: asp.net asp.net-web-api asp.net-identity

我正在使用ASP.NET身份(个人帐户)开发ASP.NET Web API以进行身份​​验证/授权。我可以通过拨打/token URI来成功登录。

我想要的是在我的用户注册我的应用程序时自动登录。我可以使用以下代码在Register方法中登录用户来完成一半的任务:

ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(UserManager, OAuthDefaults.AuthenticationType);
ClaimsIdentity cookieIdentity = await user.GenerateUserIdentityAsync(UserManager,
CookieAuthenticationDefaults.AuthenticationType);

AuthenticationProperties properties = ApplicationOAuthProvider.CreateProperties(user.UserName);
Authentication.SignIn(properties, oAuthIdentity, cookieIdentity);

有没有办法可以返回相同的OAuth,就像我成功调用/token时获得的响应一样。有些事情如下:

{"access_token":"access-token","token_type":"bearer","expires_in":1209599,"userName":"username",".issued":"Sat, 22 Mar 2014 08:12:14 GMT",".expires":"Sat, 05 Apr 2014 08:12:14 GMT"}

1 个答案:

答案 0 :(得分:0)

实际上我刚才面临同样的问题,我以一种如此丑陋的方式处理它 - 在Inside Register方法中,我创建新用户之后又发出了另一个访问“/ token”的Web请求,并传递了最新的用户名和密码。

private string GetTokenForNewUser(string username, string password)
    {
        using (var client = new HttpClient())
        {
            var host = Request.RequestUri.Scheme + "://" + Request.RequestUri.Host + ":" + Request.RequestUri.Port;
            client.BaseAddress = new Uri(host);
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            Dictionary<string, string> credential = new Dictionary<string, string>();
            credential.Add("grant_type", "password");
            credential.Add("username", username);
            credential.Add("password", password);

            HttpResponseMessage response = client.PostAsync(host + "token", new FormUrlEncodedContent(credential)).Result;
            if (response.IsSuccessStatusCode)
            {
                return response.Content.ReadAsStringAsync().Result;
            }
        }
        //if we go this far, something error happens
        return string.Empty;
    }

我认为这不是一个好方法,但它只是有效。