使用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

原文地址:https://www.cnblogs.com/xsj1989/p/5690929.html