none
Microsoft.Owin实现WebApi授权认证出现的问题,请帮看下. RRS feed

  • 问题

  • 我做了一个webapi的授权认证实例.分别为三个程序集,认证服务端,资源服务器,客户端

    我引用的主要dll.

    Microsoft.Owin

    Microsoft.Owin.Host.SystemWeb

    Microsoft.Owin.Security

    Microsoft.Owin.Security.Cookies

    Microsoft.Owin.Security.OAuth

    Microsoft.Owin系列dll 有 2.1 与 3.1 两个版本.

    我的问题是:当我在 2.1版本下测试如下代码一切正常,

    但是如果我升级dll为3.1时候就无法连接返回的错误消息是

            

    在 System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
    在 System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification)
    在 System.Threading.Tasks.Task`1.get_Result()
    在 Jurassic.WebApi.Demo.Controllers.ClientCredentialController.InitializeWebServerClient()

    主要实现代码如下:

    1.认证服务端的 Startup 如下:

    public partial class Startup
    {
            public void ConfigureAuth(IAppBuilder app)
            {
                app.UseOAuthAuthorizationServer(new OAuthAuthorizationServerOptions
                {
                    TokenEndpointPath = new PathString(Paths.TokenPath),
                    AllowInsecureHttp = true,
                    Provider = new OAuthAuthorizationServerProvider
                    {
                        OnValidateClientRedirectUri = ValidateClientRedirectUri,
                        OnValidateClientAuthentication = ValidateClientAuthentication,
                        OnGrantResourceOwnerCredentials = GrantResourceOwnerCredentials,
                        OnGrantClientCredentials = GrantClientCredetails
                    },
                    RefreshTokenProvider = new AuthenticationTokenProvider
                    {
                        OnCreate = CreateRefreshToken,
                        OnReceive = ReceiveRefreshToken,
                    }
                });
            }
    
            private Task ValidateClientRedirectUri(OAuthValidateClientRedirectUriContext context)
            {
                return Task.FromResult(0);
            }
    
            private Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
            {
                string clientId;
                string clientSecret;
                if (context.TryGetBasicCredentials(out clientId, out clientSecret) || context.TryGetFormCredentials(out clientId, out clientSecret))
                {
                    context.Validated();
                }
                return Task.FromResult(0);
            }
    
            private Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
            {
                var identity = new ClaimsIdentity(new GenericIdentity(context.UserName, OAuthDefaults.AuthenticationType), context.Scope.Select(x => new Claim("urn:oauth:scope", x)));
                context.Validated(identity);
                return Task.FromResult(0);
            }
    
            private Task GrantClientCredetails(OAuthGrantClientCredentialsContext context)
            {
                var identity = new ClaimsIdentity(
                    new GenericIdentity(context.ClientId, OAuthDefaults.AuthenticationType),
                    context.Scope.Select(x => new Claim("urn:oauth:scope", x)));
                context.Validated(identity);
                return Task.FromResult(0);
            }
    
    
            private readonly ConcurrentDictionary<string, string> _authenticationCodes = new ConcurrentDictionary<string, string>(StringComparer.Ordinal);
    
            private void CreateRefreshToken(AuthenticationTokenCreateContext context)
            {
                context.SetToken(context.SerializeTicket());
            }
    
            private void ReceiveRefreshToken(AuthenticationTokenReceiveContext context)
            {
                context.DeserializeTicket(context.Token);
            }        
    
    }



    2.资源服务器代码如下

    资源服务器启动类

    public partial class Startup
    {
    public void ConfigureAuth(IAppBuilder app)
    {
    app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
    }
    }

    授权的服务

    public class ResourcesController : ApiController { [Authorize] [HttpGet] public string GetData(string id) { return "测试服务资源" + id; } }



    3.客户端

     private static void AccessWebServer()
            {
                string clientId = "123";
                string clientSecret = "abc";
    
                //访问授权服务器
                HttpClient _httpClient = new HttpClient();
                _httpClient.BaseAddress = new Uri("http://localhost:123/");
                var parameters = new Dictionary<string, string>();
                parameters.Add("client_id", clientId);
                parameters.Add("client_secret", clientSecret);
                parameters.Add("grant_type", "client_credentials");
    
                var response = _httpClient.PostAsync("/OAuth/Token", new FormUrlEncodedContent(parameters)).Result;
                var responseValue = response.Content.ReadAsStringAsync();
                //获取token
                string _accessToken = JObject.Parse(responseValue.Result)["access_token"].Value<string>();
    
                //访问资源服务器
                HttpClient client = new HttpClient();
                client.BaseAddress = new Uri("http://localhost:456/");
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _accessToken);
                //
                string resStr = client.GetStringAsync("/api/Resources/GetData/参数ID").Result;
            }





    2017年8月15日 8:02

全部回复

  • 你好,

    根据你提供的错误信息,我没有得到一些有用的信息, 可以提供一下具体的错误信息吗?

    Best regards,

    Cole Wu


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    2017年8月21日 5:09
    版主