posts - 609,  comments - 13,  views - 64万
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

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

客户端获取Token:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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() 方法即可。代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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);
        }

  

使用:

1
2
3
4
5
6
7
8
9
10
11
12
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

posted on   邢帅杰  阅读(3320)  评论(3编辑  收藏  举报
编辑推荐:
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
阅读排行:
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
· SQL Server 2025 AI相关能力初探
点击右上角即可分享
微信分享提示