Asp.net Api中使用OAuth2.0实现“客户端验证”

时间:2021-12-15 22:04:09

public class MyOwnOAuthProvider:OAuthAuthorizationServerProvider { private static readonly Logger logger = LogManager.GetLogger("MyOwnOAuth"); /// <summary> /// 客户端认证 /// </summary> /// <param></param> /// <returns></returns> public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context) { string clientId; string clientSecret; //获取客户端传入的用户名和密码 context.TryGetFormCredentials(out clientId,out clientSecret); logger.Info("用户名:"+clientId+" 密码:"+clientSecret+" 登陆网站..."); //可以使用自己的数据验证,如通过数据库查询等方式 if (clientId == "MyOwnApp" && clientSecret == "ctmdsh!320") { context.Validated(clientId); } return base.ValidateClientAuthentication(context); } /// <summary> /// 方法中对客户端进行授权 授权后发放access token /// </summary> /// <param></param> /// <returns></returns> public override Task GrantClientCredentials(OAuthGrantClientCredentialsContext context) { var oAuthIdentity = new ClaimsIdentity(context.Options.AuthenticationType); oAuthIdentity.AddClaim(new Claim("MyOwnApp", "ljx")); //API中可以使用一下方法获取其中的值。 // var identity = (ClaimsIdentity)User.Identity; //var mayiAccount = identity.FindFirstValue("MyOwnApp"); var ticket = new AuthenticationTicket(oAuthIdentity,new AuthenticationProperties()); context.Validated(ticket); logger.Info("已对用户Ljx发放access_token..."); return base.GrantClientCredentials(context); } }

  

重载ValidateClientAuthentication方法,实现客户端验证,重载GrantClientCredentials方法,实现access_token的发放。

二。通过相关配置,设置自己创建的Provider为Authroize的处理类。
1.在App_start文件夹中找到Startup.Auth,找到OAuthOptions方法,修改对应的Provider完成配置:

OAuthOptions = new OAuthAuthorizationServerOptions { TokenEndpointPath = new PathString("/Token"), Provider = new MyOwnOAuthProvider(), // AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"), AccessTokenExpireTimeSpan = TimeSpan.FromDays(14), //在生产模式下设 AllowInsecureHttp = false AllowInsecureHttp = true };

  

MyOwnOAuthProvider处替换为我们自己创建的验证逻辑类即可。


三。在api中对controller或者action加入[Authorize]属性即可。

四。注意如果要实现跨域访问,需要在Startup.Auth文件的ConfigureAuth方法中加入

app.UseCors(CorsOptions.AllowAll);

  当然,,需要首先使用Nuget安装Microsoft.Owin.Cors的引用。

五。在客户端实现响应的调用。

1.设置$.ajax的提交之前的处理方法:

$(function () { $.ajaxSetup({ cache: false, beforeSend: function (xhr, option) { var opentId = "MyOwnApp"; var openSecret = "ctmdsh!320"; // alert("start"); $.ajax({ type: ‘post‘, async: false, url: hosturl + "token", data: { client_id: opentId, client_secret: openSecret, grant_type: "client_credentials" }, tokenSkip: true, success: function (data) { xhr.setRequestHeader("Authorization", "Bearer " + data.access_token); } }); } }, complete: function () { }, error: function (a) { if (typeof console.log === "function") { console.log(a.responseText); } } }); })

  

client_id指明用户,client_secret指明密码,grant_type: "client_credentials"指明验证方式。

2.在对应页面直接调用响应的API接口即可。

$(function () { $.ajax({ type:"get", url: "http://localhost:51067/api/values", success: function (data) { alert(data); } }); })

  





Asp.net Api中使用OAuth2.0实现“客户端验证”