【问题标题】:How to get access token in Web Api OAuth?如何在 Web Api OAuth 中获取访问令牌?
【发布时间】:2015-07-21 09:00:59
【问题描述】:

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

基本上,调用以下控制器动作:

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(); 

现在,此返回 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 更改为任何其他操作,我会收到由调用 uri 引起的 "invalid_request" 错误,这与 redirect_uri 不同。

那么,客户端应用如何获取访问令牌?

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

【问题讨论】:

    标签: c# asp.net-mvc authentication oauth asp.net-web-api2


    【解决方案1】:

    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 。添加控制器

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

    4。现在根据令牌检查授权

    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);  
               }  
    
    
           }  
    

    【讨论】:

    • 我被困在 WebApp.Start。客户端应该在 web api 中吗?我有一个外部 api,我正在尝试生成访问令牌
    • 很好的例子我也想做同样的事情请在这里帮助我-stackoverflow.com/questions/45070290/…
    • 如何在 C# 中获取访问令牌? (在回复客户之前)。
    猜你喜欢
    • 2021-01-10
    • 1970-01-01
    • 2015-07-01
    • 2015-06-15
    • 2012-02-12
    • 1970-01-01
    • 1970-01-01
    • 2012-08-02
    • 2019-09-10
    相关资源
    最近更新 更多