草庐IT

c# - 如何在 Web Api OAuth 中获取访问 token ?

coder 2024-05-25 原文

我有一个 Web 应用程序,它生成链接以获取针对 Web API 2 的访问 token 。

基本上,调用以下 Controller 操作:

GetExternalLoginAccountController:

 ApplicationUser user = await UserManager.FindAsync(new UserLoginInfo(externalLogin.LoginProvider,
            externalLogin.ProviderKey));

        bool hasRegistered = user != null;

        if (hasRegistered)
        {
            Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie);

            ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(UserManager,
               OAuthDefaults.AuthenticationType);
            ClaimsIdentity cookieIdentity = await user.GenerateUserIdentityAsync(UserManager,
                CookieAuthenticationDefaults.AuthenticationType);

            AuthenticationProperties properties = ApplicationOAuthProvider.CreateProperties(user.UserName);
            Authentication.SignIn(properties, oAuthIdentity, cookieIdentity);
        }
        else
        {
      // as user is not registered, this block is hit
            IEnumerable<Claim> claims = externalLogin.GetClaims();
            ClaimsIdentity identity = new ClaimsIdentity(claims, OAuthDefaults.AuthenticationType);
            Authentication.SignIn(identity);
        }

        return Ok(); 

现在,这个 return Ok 行只是返回到我的 Web API 基本 url 并在此之后添加一个标记:

https://localhost:44301/#access_token=iPl1MSgnjI3oXgDxuCH9_t5I1SsELUH-v_vNXdehGpNWsCWsQaX7csWWadWRq4H2uZ0BB8zZm2s0xOI8TSOfgzH7QbFVko4Ui8jM5SylhPgkC7eiQG-kChDfa5HMlxKF1JvRg9Kvs40rPGqsC22uel-Gi2QZlrMh_5M0NT06QOOMv4bDTAFljKw9clsMiHidX4TPfQ6UmhROMIo8FcBDlAfH7wZbSQZjFAWm4Mub-oMoUxUOzAVxJrjGiM9gxwk4iqLqGbcFVl6AncJnFO_YDtmWH_sRBvmbfzpQ6GiB10eyY-hA_L-sWtQbX8IPPtOKuWGbyg0_MfaWBfAJfUiNjH6_VjcOfPEdwUPEvbnR8vw&token_type=bearer&expires_in=1209600&state=Qvlzg__CCwjCjaqEOInQw0__FprOykwROuAciRgDlIQ1

就是这样。

如何从 URL 中获取这些参数并进行处理?

如果我将基本 URL 更改为任何其他操作,我会收到 "invalid_request" 错误,这是由调用 uri 与 redirect_uri 不同引起的。

那么,客户端应用程序如何获取访问 token ?

任何帮助或澄清都会非常有帮助。

最佳答案

1。为 token 创建类

public class Token  
   {  
       [JsonProperty("access_token")]  
       public string AccessToken { get; set; }  

       [JsonProperty("token_type")]  
       public string TokenType { get; set; }  

       [JsonProperty("expires_in")]  
       public int ExpiresIn { get; set; }  

       [JsonProperty("refresh_token")]  
       public string RefreshToken { get; set; }  
   } 

2。启动类

   [assembly: OwinStartup(typeof(ProjectName.API.Startup))]
   namespace ProjectName.API
{
   public class Startup  
    {  
        public void Configuration(IAppBuilder app)  
        {  
            var oauthProvider = new OAuthAuthorizationServerProvider  
            {  
                OnGrantResourceOwnerCredentials = async context =>  
                {  
                    if (context.UserName == "xyz" && context.Password == "xyz@123")  
                    {  
                        var claimsIdentity = new ClaimsIdentity(context.Options.AuthenticationType);  
                        claimsIdentity.AddClaim(new Claim("user", context.UserName));  
                        context.Validated(claimsIdentity);  
                        return;  
                    }  
                    context.Rejected();  
                },  
                OnValidateClientAuthentication = async context =>  
                {  
                    string clientId;  
                    string clientSecret;  
                    if (context.TryGetBasicCredentials(out clientId, out clientSecret))  
                    {  
                        if (clientId == "xyz" && clientSecret == "secretKey")  
                        {  
                            context.Validated();  
                        }  
                    }  
                }  
            };  
            var oauthOptions = new OAuthAuthorizationServerOptions  
            {  
                AllowInsecureHttp = true,  
                TokenEndpointPath = new PathString("/accesstoken"),  
                Provider = oauthProvider,  
                AuthorizationCodeExpireTimeSpan= TimeSpan.FromMinutes(1),  
                AccessTokenExpireTimeSpan=TimeSpan.FromMinutes(3),  
                SystemClock= new SystemClock()  

            };  
            app.UseOAuthAuthorizationServer(oauthOptions);  
            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());  

            var config = new HttpConfiguration();  
            config.MapHttpAttributeRoutes();  
            app.UseWebApi(config);  
        }  
    }  
}

3 。添加 Controller

[Authorize]  
   public class TestController : ApiController  
   {  
       [Route("test")]  
       public HttpResponseMessage Get()  
       {  
           return Request.CreateResponse(HttpStatusCode.OK, "hello !");  
       }  
   }  

4。现在根据 token 检查授权

static void Main()  
       {  
           string baseAddress = "http://localhost:/";  

           // Start OWIN host     
           using (WebApp.Start<Startup>(url: baseAddress))  
           {  
               var client = new HttpClient();  
               var response = client.GetAsync(baseAddress + "test").Result;  
               Console.WriteLine(response);  

               Console.WriteLine();  

               var authorizationHeader = Convert.ToBase64String(Encoding.UTF8.GetBytes("xyz:secretKey"));  
               client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", authorizationHeader);  

               var form = new Dictionary<string, string>  
               {  
                   {"grant_type", "password"},  
                   {"username", "xyz"},  
                   {"password", "xyz@123"},  
               };  

               var tokenResponse = client.PostAsync(baseAddress + "accesstoken", new FormUrlEncodedContent(form)).Result;  
               var token = tokenResponse.Content.ReadAsAsync<Token>(new[] { new JsonMediaTypeFormatter() }).Result;  

               Console.WriteLine("Token issued is: {0}", token.AccessToken);  

               Console.WriteLine();  

               client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token.AccessToken);  
               var authorizedResponse = client.GetAsync(baseAddress + "test").Result;  
               Console.WriteLine(authorizedResponse);  
               Console.WriteLine(authorizedResponse.Content.ReadAsStringAsync().Result);  
           }  


       }  

关于c# - 如何在 Web Api OAuth 中获取访问 token ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30157814/

有关c# - 如何在 Web Api OAuth 中获取访问 token ?的更多相关文章

  1. ruby - 为什么我可以在 Ruby 中使用 Object#send 访问私有(private)/ protected 方法? - 2

    类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc

  2. ruby - 如何在 Ruby 中顺序创建 PI - 2

    出于纯粹的兴趣,我很好奇如何按顺序创建PI,而不是在过程结果之后生成数字,而是让数字在过程本身生成时显示。如果是这种情况,那么数字可以自行产生,我可以对以前看到的数字实现垃圾收集,从而创建一个无限系列。结果只是在Pi系列之后每秒生成一个数字。这是我通过互联网筛选的结果:这是流行的计算机友好算法,类机器算法:defarccot(x,unity)xpow=unity/xn=1sign=1sum=0loopdoterm=xpow/nbreakifterm==0sum+=sign*(xpow/n)xpow/=x*xn+=2sign=-signendsumenddefcalc_pi(digits

  3. ruby - 如何在 buildr 项目中使用 Ruby 代码? - 2

    如何在buildr项目中使用Ruby?我在很多不同的项目中使用过Ruby、JRuby、Java和Clojure。我目前正在使用我的标准Ruby开发一个模拟应用程序,我想尝试使用Clojure后端(我确实喜欢功能代码)以及JRubygui和测试套件。我还可以看到在未来的不同项目中使用Scala作为后端。我想我要为我的项目尝试一下buildr(http://buildr.apache.org/),但我注意到buildr似乎没有设置为在项目中使用JRuby代码本身!这看起来有点傻,因为该工具旨在统一通用的JVM语言并且是在ruby中构建的。除了将输出的jar包含在一个独特的、仅限ruby​​

  4. ruby - 什么是填充的 Base64 编码字符串以及如何在 ruby​​ 中生成它们? - 2

    我正在使用的第三方API的文档状态:"[O]urAPIonlyacceptspaddedBase64encodedstrings."什么是“填充的Base64编码字符串”以及如何在Ruby中生成它们。下面的代码是我第一次尝试创建转换为Base64的JSON格式数据。xa=Base64.encode64(a.to_json) 最佳答案 他们说的padding其实就是Base64本身的一部分。它是末尾的“=”和“==”。Base64将3个字节的数据包编码为4个编码字符。所以如果你的输入数据有长度n和n%3=1=>"=="末尾用于填充n%

  5. ruby-on-rails - 如何在 ruby​​ 中使用两个参数异步运行 exe? - 2

    exe应该在我打开页面时运行。异步进程需要运行。有什么方法可以在ruby​​中使用两个参数异步运行exe吗?我已经尝试过ruby​​命令-system()、exec()但它正在等待过程完成。我需要用参数启动exe,无需等待进程完成是否有任何ruby​​gems会支持我的问题? 最佳答案 您可以使用Process.spawn和Process.wait2:pid=Process.spawn'your.exe','--option'#Later...pid,status=Process.wait2pid您的程序将作为解释器的子进程执行。除

  6. ruby-on-rails - 在混合/模块中覆盖模型的属性访问器 - 2

    我有一个包含模块的模型。我想在模块中覆盖模型的访问器方法。例如:classBlah这显然行不通。有什么想法可以实现吗? 最佳答案 您的代码看起来是正确的。我们正在毫无困难地使用这个确切的模式。如果我没记错的话,Rails使用#method_missing作为属性setter,因此您的模块将优先,阻止ActiveRecord的setter。如果您正在使用ActiveSupport::Concern(参见thisblogpost),那么您的实例方法需要进入一个特殊的模块:classBlah

  7. ruby - 如何在续集中重新加载表模式? - 2

    鉴于我有以下迁移:Sequel.migrationdoupdoalter_table:usersdoadd_column:is_admin,:default=>falseend#SequelrunsaDESCRIBEtablestatement,whenthemodelisloaded.#Atthispoint,itdoesnotknowthatusershaveais_adminflag.#Soitfails.@user=User.find(:email=>"admin@fancy-startup.example")@user.is_admin=true@user.save!ende

  8. ruby - 续集在添加关联时访问many_to_many连接表 - 2

    我正在使用Sequel构建一个愿望list系统。我有一个wishlists和itemstable和一个items_wishlists连接表(该名称是续集选择的名称)。items_wishlists表还有一个用于facebookid的额外列(因此我可以存储opengraph操作),这是一个NOTNULL列。我还有Wishlist和Item具有续集many_to_many关联的模型已建立。Wishlist类也有:selectmany_to_many关联的选项设置为select:[:items.*,:items_wishlists__facebook_action_id].有没有一种方法可以

  9. ruby - 如何在 Ruby 中拆分参数字符串 Bash 样式? - 2

    我正在为一个项目制作一个简单的shell,我希望像在Bash中一样解析参数字符串。foobar"helloworld"fooz应该变成:["foo","bar","helloworld","fooz"]等等。到目前为止,我一直在使用CSV::parse_line,将列分隔符设置为""和.compact输出。问题是我现在必须选择是要支持单引号还是双引号。CSV不支持超过一个分隔符。Python有一个名为shlex的模块:>>>shlex.split("Test'helloworld'foo")['Test','helloworld','foo']>>>shlex.split('Test"

  10. ruby - 如何在 Lion 上安装 Xcode 4.6,需要用 RVM 升级 ruby - 2

    我实际上是在尝试使用RVM在我的OSX10.7.5上更新ruby,并在输入以下命令后:rvminstallruby我得到了以下回复:Searchingforbinaryrubies,thismighttakesometime.Checkingrequirementsforosx.Installingrequirementsforosx.Updatingsystem.......Errorrunning'requirements_osx_brew_update_systemruby-2.0.0-p247',pleaseread/Users/username/.rvm/log/138121

随机推荐