日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

WEBAPI 增加身份验证 (OAUTH 2.0方式)

發布時間:2023/12/4 编程问答 32 豆豆
生活随笔 收集整理的這篇文章主要介紹了 WEBAPI 增加身份验证 (OAUTH 2.0方式) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

1,在Webapi項目下添加如下引用:

Microsoft.AspNet.WebApi.Owin

Owin

Microsoft.Owin.Host.SystemWeb

Microsoft.Owin.Security.OAuth

Microsoft.Owin.Security.Cookies

Microsoft.AspNet.Identity.Owin

Microsoft.Owin.Cors

2, 在項目下新建Startup類,這個類將作為owin的啟動入口,添加下面的代碼

3,修改?Startup類中方法

1234567891011121314151617181920212223242526public?class?Startup{????public?void?Configuration(IAppBuilder app)????{????????// 有關如何配置應用程序的詳細信息,請訪問 http://go.microsoft.com/fwlink/?LinkID=316888????????ConfigAuth(app);????????HttpConfiguration config =?new?HttpConfiguration();????????WebApiConfig.Register(config);????????app.UseCors(CorsOptions.AllowAll);????????app.UseWebApi(config);????}????public?void?ConfigAuth(IAppBuilder app)????{????????OAuthAuthorizationServerOptions option =?new?OAuthAuthorizationServerOptions()????????{????????????AllowInsecureHttp =?true,????????????TokenEndpointPath =?new?PathString("/token"),?//獲取 access_token 授權服務請求地址????????????AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),?//access_token 過期時間????????????Provider =?new?SimpleAuthorizationServerProvider(),?//access_token 相關授權服務????????????RefreshTokenProvider =?new?SimpleRefreshTokenProvider()?//refresh_token 授權服務????????};????????app.UseOAuthAuthorizationServer(option);????????app.UseOAuthBearerAuthentication(new?OAuthBearerAuthenticationOptions());????}}

4, OAuth身份認證,新建SimpleAuthorizationServerProvider類

123456789101112131415161718192021222324public?class?SimpleAuthorizationServerProvider : OAuthAuthorizationServerProvider{????public?override?Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)????{????????context.Validated();????????return?Task.FromResult<object>(null);????}????public?override?async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)????{????????context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin",?new[] {?"*"?});????????AccountService accService =?new?AccountService();????????string?md5Pwd = LogHelper.MD5CryptoPasswd(context.Password);????????IList<object[]> ul = accService.Login(context.UserName, md5Pwd);????????if?(ul.Count() == 0)????????{????????????context.SetError("invalid_grant",?"The username or password is incorrect");????????????return;????????}????????var?identity =?new?ClaimsIdentity(context.Options.AuthenticationType);????????identity.AddClaim(new?Claim("sub", context.UserName));????????identity.AddClaim(new?Claim("role",?"user"));????????context.Validated(identity);????}}

5,?新建SimpleRefreshTokenProvider類

12345678910111213141516171819202122232425262728public?class?SimpleRefreshTokenProvider : AuthenticationTokenProvider{????private?static?ConcurrentDictionary<string,?string> _refreshTokens =?new?ConcurrentDictionary<string,?string>();????/// <summary>????/// 生成 refresh_token????/// </summary>????public?override?void?Create(AuthenticationTokenCreateContext context)????{????????context.Ticket.Properties.IssuedUtc = DateTime.UtcNow;????????context.Ticket.Properties.ExpiresUtc = DateTime.UtcNow.AddDays(60);????????context.SetToken(Guid.NewGuid().ToString("n"));????????_refreshTokens[context.Token] = context.SerializeTicket();????}????/// <summary>????/// 由 refresh_token 解析成 access_token????/// </summary>????public?override?void?Receive(AuthenticationTokenReceiveContext context)????{????????string?value;????????if?(_refreshTokens.TryRemove(context.Token,?out?value))????????{????????????context.DeserializeTicket(value);????????}????}}

6, 在要加驗證的接口上加上[Authorize]標記

12345678910[Authorize]public?class?EmployeeController : ApiController{????//查詢所有員工????[HttpGet]????public?IList<UC_Employee> GetAllEmps()????{  ????return?new?List<UC_Employee>();????}}

7,調用api程序

?

8,傳入參數,獲取token

9,傳入access_token

本文版權歸作者和博客園共有,歡迎轉載,但未經作者同意需保留此段聲明,且在文章頁面明顯位置給出原文連接。

作者:Lnice
出處:http://www.cnblogs.com/lnice 創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎

總結

以上是生活随笔為你收集整理的WEBAPI 增加身份验证 (OAUTH 2.0方式)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。