当前位置: 首页 > 编程语言 > C#

如何在Asp.netMVC中编写OAuth2WebAPI客户端分享

时间:2023-04-10 15:41:26 C#

如何在Asp.netMVC中编写OAuth2WebAPI客户端我们开发了一套WebAPI(REST)受授权服务器。授权服务器已发布客户端ID和客户端密码。这些可用于获取访问令牌。可以在对资源服务器(RESTAPI)的后续调用中使用有效令牌。我想编写一个基于Web(Asp.netMVC5)的客户端,它将使用一个API。有没有我可以下载的nuget包来帮助我处理客户端OAuth2流程?任何人都可以指导我在OAuth2流程的客户端实现(用asp.netMVC编写)中的一个很好的例子吗?更新我可以使用下面的代码块获取访问令牌,但我想要的是“客户端凭据”oauth2流程,我不必在其中输入登录名和密码。我现在的代码是:publicclassStartup{publicvoidConfiguration(IAppBuilderapp){app.SetDefaultSignInAsAuthenticationType("ClientCookie");app.UseCookieAuthentication(newCookieAuthenticationOptions{AuthenticationMode=AuthenticationMode.Active,AuthenticationType="ClientCookie",CookieName=CookieAuthenticationDefaults.CookiePrefix+"ClientCookie",ExpireTimeSpan=TimeSpan.FromMinutes(5)});app.UseOpenIdConnectAuthentication(newOpenIdConnectAuthenticationOptions{AuthenticationMode=AuthenticationMode.Active,AuthenticationType=OpenIdConnectAuthenticationDefaults.AuthenticationType,SignInAsAuthenticationType=app.GetDefaultSignInAsAuthenticationType(),ClientId=ConfigurationManager.AppSettings["AuthServer:ClientId"],ClientSecret=ConfigurationManager.AppSettings["AuthServer:ClientSecret"],RedirectUri=ConfigurationManager.AppSettings["AuthServer:RedirectUrl"],Configuration=newOpenIdConnectConfiguration{AuthorizationEndpoint="https://identityserver.com/oauth2/authorize",TokenEndpoint="https://identityserver.com/oauth2/token"},//ResponseType="client_credentials",//不起作用ResponseType="token",Notifications=newOpenIdConnectAuthenticationNotifications{AuthenticationFailed=notification=>{if(string.Equals(notification.ProtocolMessage.Error,"access_denied",StringComparison.Ordinal)){notification.HandleResponse();}notification.Response.Redirect("/");}返回Task.FromResult(null);},AuthorizationCodeReceived=asyncnotification=>{using(varclient=newHttpClient()){//varconfiguration=awaitnotification.Options.ConfigurationManager.GetConfigurationAsync(notification.Request.CallCancelled);StringtokenEndPoint="https://identityserver.com/oauth2/token";//varrequest=newHttpRequestMessage(HttpMethod.Post,configuration.TokenEndpoint);varrequest=newHttpRequestMessage(HttpMethod.Post,tokenEndPoint);请求.Con帐篷=新的FormUrlEncodedContent(新字典{{OpenIdConnectParameterNames.ClientId,notification.Options.ClientId},{OpenIdConnectParameterNames.ClientSecret,notification.Options.ClientSecret},{OpenIdConnectParameterNames.Code,notification.ProtocolMessage.Code},{OpenIdConnectParameterNames.GrantType,“authorization_code"},{OpenIdConnectParameterNames.RedirectUri,notification.Options.RedirectUri}});varresponse=awaitclient.SendAsync(request,notification.Request.CallCancelled);响应.EnsureSuccessStatusCode();varpayload=JObject.Parse(awaitresponse.Content.ReadAsStringAsync());//将访问令牌添加到返回的ClaimsIdentity以使其更易于检索。notification.AuthenticationTicket.Identity.AddClaim(新声明(类型:OpenIdConnectParameterNames.AccessToken,值:payload.Value(OpenIdConnectParameterNames.AccessToken)));}}}});}}要支持客户端准予交付类型,您最好的选择可能是直接使用HttpClient:varrequest=newHttpRequestMessage(HttpMethod.Post,"http://server.com/token");request.Content=newFormUrlEncodedContent(newDictionary{{"client_id","yourclient_id"},{"client_secret","yourclient_secret"},{"grant_type","client_credentials"}});varresponse=awaitclient.SendAsync(request);响应.EnsureSuccessStatusCode();varpayload=JObject.Parse(awaitresponse.Content.ReadAsStringAsync());vartoken=payload.Value("access_token");对于交互式流程(比如授权码流程),有两种比较好的方法:以上是C#学习教程:HowtowriteOAuth2WebAPIclientinAsp.netMVC的内容,如果对你有用需要了解一下更多关于C#学习教程,希望大家多多关注。本文收集自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处: