对应的应用场景是:为自家的网站开发手机 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
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
· SQL Server 2025 AI相关能力初探