用户界面中的OWIN Web API授权

时间:2017-08-02 06:45:35

标签: c# asp.net-mvc asp.net-mvc-4 asp.net-web-api

我在MVC和Web API中准备用户界面。通过OWIN在Web API中进行授权是正确的。在登录方法中,您可以看到我只是登录到Web API并且我获取了一些信息令牌等但是是否可以从Web API导入此自动化并将其添加到MVC中的接口?如果是的话怎么做?

例如:mvcUI.User = WebAPI.User

*我想在mvcUI中使用[授权],声明

enter image description here

使用了WebApiAuthorizationHelper代码:

 public static class WebApiAuthorizationHelper
    {

        public static string GetToken(string url, string userName, string password)
        {
            var pairs = new List<KeyValuePair<string, string>>
                    {
                        new KeyValuePair<string, string>( "grant_type", "password" ),
                        new KeyValuePair<string, string>( "username", userName ),
                        new KeyValuePair<string, string> ( "Password", password )
                    };
            var content = new FormUrlEncodedContent(pairs);
            ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;
            using (var client = new HttpClient())
            {
                var response = client.PostAsync(url + "Token", content).Result;
                return response.Content.ReadAsStringAsync().Result;
            }
        }

        public static string CallApi(string url, string token)
        {
            ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;
            using (var client = new HttpClient())
            {
                if (!string.IsNullOrWhiteSpace(token))
                {
                    var t = JsonConvert.DeserializeObject<Token>(token);

                    client.DefaultRequestHeaders.Clear();
                    client.DefaultRequestHeaders.Add("Authorization", "Bearer " + t.access_token);
                }
                var response = client.GetAsync(url).Result;
                return response.Content.ReadAsStringAsync().Result;
            }
        }

        class Token
        {
            public string access_token { get; set; }
            public string token_type { get; set; }
            public int expires_in { get; set; }
            public string userName { get; set; }
            [JsonProperty(".issued")]
            public string issued { get; set; }
            [JsonProperty(".expires")]
            public string expires { get; set; }
        }

    }

1 个答案:

答案 0 :(得分:2)

您可以在下面代码的令牌中添加信息。

我的CustomIdentityService

public class CustomIdentityService
{
   protected MyContext _context = new MyContext();

   public Guid FooInfo(Guid IdentityUserID)
   {
    return con.fooTable.Where(x => x.IdentityUserID == IdentityUserID).
    Select(us => new { us.fooData }).FirstOrDefault().fooData;
   }
 }

<强>提供商/ ApplicationOAuthProvider.cs

 public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
    {

    CustomIdentityService _customIdentityService = new CustomIdentityService();

    ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager,OAuthDefaults.AuthenticationType);
    ClaimsIdentity cookiesIdentity = await user.GenerateUserIdentityAsync(userManager,CookieAuthenticationDefaults.AuthenticationType);

    //Add custom claims code
    string fooInfo= _customIdentityService.FooInfo(user.Id));
    oAuthIdentity.AddClaim(new Claim("fooInfo", fooInfo));
    AuthenticationProperties properties = CreateProperties(user.UserName,fooInfo);

    }

  public static AuthenticationProperties CreateProperties(string userName,string fooInfo)
    {
       IDictionary<string, string> data = new Dictionary<string, string>
     {
        { "fooInfo", fooInfo },
        { "userName", userName }
     };
       return new AuthenticationProperties(data);
     }