Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/257.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 用户界面中的OWIN Web API授权_C#_Asp.net Mvc_Asp.net Mvc 4_Asp.net Web Api - Fatal编程技术网

C# 用户界面中的OWIN Web API授权

C# 用户界面中的OWIN Web API授权,c#,asp.net-mvc,asp.net-mvc-4,asp.net-web-api,C#,Asp.net Mvc,Asp.net Mvc 4,Asp.net Web Api,我在MVC和WebAPI中准备用户界面。通过OWIN在Web API中进行授权是正确的。在登录方法中,您可以看到我只是登录到Web API,并获取一些信息令牌等。但是否可以从Web API导入此自动化并将其添加到MVC中的接口?如果是,怎么做 例如:mvcUI.User=WebAPI.User *我还想在mvcUI中使用[Authorize]索赔 使用的WebAPiaAuthorizationHelper代码: public static class WebApiAuthorizationH

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

例如:mvcUI.User=WebAPI.User

*我还想在mvcUI中使用[Authorize]索赔

使用的WebAPiaAuthorizationHelper代码:

 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; }
        }

    }
public静态类webapiaauthorizationhelper
{
公共静态字符串GetToken(字符串url、字符串用户名、字符串密码)
{
var pairs=新列表
{
新的KeyValuePair(“授权类型”、“密码”),
新的KeyValuePair(“用户名”,用户名),
新的KeyValuePair(“密码”,Password)
};
var内容=新FormUrlEncodedContent(成对);
ServicePointManager.ServerCertificateValidationCallback+=(发件人、证书、链、sslPolicyErrors)=>true;
使用(var client=new HttpClient())
{
var response=client.PostAsync(url+“Token”,content).Result;
返回response.Content.ReadAsStringAsync().Result;
}
}
公共静态字符串调用API(字符串url、字符串令牌)
{
ServicePointManager.ServerCertificateValidationCallback+=(发件人、证书、链、sslPolicyErrors)=>true;
使用(var client=new HttpClient())
{
如果(!string.IsNullOrWhiteSpace(标记))
{
var t=JsonConvert.DeserializeObject(令牌);
client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.Add(“授权”、“承载人”+t.access\u令牌);
}
var response=client.GetAsync(url).Result;
返回response.Content.ReadAsStringAsync().Result;
}
}
类令牌
{
公共字符串访问\u令牌{get;set;}
公共字符串标记\u类型{get;set;}
{get;set;}中的公共int过期
公共字符串用户名{get;set;}
[JsonProperty(“.已发行”)]
发出的公共字符串{get;set;}
[JsonProperty(“.expires”)]
公共字符串过期{get;set;}
}
}

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

我的客户识别服务

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;
   }
 }
Providers/applicationAuthProvider.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);
     }
public override异步任务GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext)
{
CustomIdentityService_CustomIdentityService=新CustomIdentityService();
ClaimsIdentity oAuthIdentity=等待user.generateSerialIdentityAsync(userManager,OAuthDefaults.AuthenticationType);
ClaimSideEntity cookiesIdentity=Wait user.GenerateUserIdentity异步(userManager,CookieAuthenticationDefaults.AuthenticationType);
//添加自定义索赔代码
字符串fooInfo=_customIdentityService.fooInfo(user.Id));
oAuthIdentity.AddClaim(新索赔(“fooInfo”,fooInfo));
AuthenticationProperties=CreateProperties(user.UserName,fooInfo);
}
公共静态身份验证属性CreateProperties(字符串用户名、字符串fooInfo)
{
IDictionary data=新字典
{
{“fooInfo”,fooInfo},
{“用户名”,用户名}
};
返回新的AuthenticationProperties(数据);
}

我想我们也有类似的设置。您可以通过在MVC端解码令牌、读取其声明以及在MVC端添加使用cookie身份验证来实现所需。将相同的令牌值存储在MVC端的cookie中,然后您将能够使用[Authorize]属性。当@Verthosa write时,安全性由cookie完成,但不直接由jwt令牌完成。我找到了解决方案,但您的答案是正确的