zoukankan      html  css  js  c++  java
  • 使用Resource Owner Password Credentials Grant授权发放Token

    对应的应用场景是:为自家的网站开发手机 App(非第三方 App),只需用户在 App 上登录,无需用户对 App 所能访问的数据进行授权。

    客户端获取Token:

    public string GetAccessToken(string UserName, string UserPwd)
    {
        if (UserName == "xsj" && UserPwd == "123456")
        {
            HttpClient _httpClient = new HttpClient();
            _httpClient.BaseAddress = new Uri("http://localhost:61659");
            _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.ASCII.GetBytes(UserName + ":" + UserPwd)));
            var parameters = new Dictionary<string, string>();
            parameters.Add("grant_type", "password");
            parameters.Add("username", UserName);
            parameters.Add("password", UserPwd);
            string result = _httpClient.PostAsync("/Token", new FormUrlEncodedContent(parameters)).Result.Content.ReadAsStringAsync().Result;
        }
        return "";
    }
    

        

    基于 Owin OAuth, 针对 Resource Owner Password Credentials Grant 的授权方式,只需重载 OAuthAuthorizationServerProvider.GrantResourceOwnerCredentials() 方法即可。代码如下:

    public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
            {
                //验证context.UserName与context.Password //调用后台的登录服务验证用户名与密码
                var oAuthIdentity = new ClaimsIdentity(context.Options.AuthenticationType);
    
                var props = new AuthenticationProperties(new Dictionary<string, string> { { "client_id", context.ClientId } });
    
                oAuthIdentity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
    
                var ticket = new AuthenticationTicket(oAuthIdentity, props);
    
                context.Validated(ticket);
    
                await base.GrantResourceOwnerCredentials(context);
            }
    

      

    使用:

    public string Call_WebAPI_By_Resource_Owner_Password_Credentials_Grant()
    {
        string token = await GetAccessToken("xsj", "123456");
        if (token != "")
        {
            HttpClient _httpClient = new HttpClient();
            _httpClient.BaseAddress = new Uri("http://localhost:61659");
            _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
            return _httpClient.GetAsync("/UserInfo/GetCurrent")).Content.ReadAsStringAsync());
        }
        return "";
    }
    

    参考:http://www.cnblogs.com/dudu/tag/OAuth/
    https://github.com/feiyit/MvcApiSecurity

  • 相关阅读:
    PHP的垃圾回收机制
    python使用httpHandler处理请求案例
    使用python中urllib.request.Request()来构建ua
    Pillow《转载》
    python数据格式化之pprint
    使用Mechanize实现自动化表单处理
    beautifulSoup《转》
    Python3网络爬虫(四):使用User Agent和代理IP隐藏身份《转》
    python urllib和urllib3包使用
    使用Mechanize实现自动化表单处理
  • 原文地址:https://www.cnblogs.com/xsj1989/p/5690929.html
Copyright © 2011-2022 走看看