在服务器

时间:2017-01-29 19:12:24

标签: c# asp.net-mvc asp.net-web-api oauth-2.0 jwt

我正在通过OAuth bearer令牌保护Web API,因为这在本地工作正常,能够生成令牌,在服务器代码上托管后无法生成服务器上托管的令牌。

当我尝试服务器示例Url" api.somedemo.com/token"显示请求响应为找不到方法

但在本地" http://local:1234/token "相同的代码工作生成令牌。

我无法找到服务器上缺少哪些内容来生成承载令牌。

这里的代码。 来自控制器:

private BearerToken GetBearerToken(string userName, string password)
  {
            BearerToken token = null;

            FormUrlEncodedContent bearerTokenContent = OAuthClientWrapper.CreateBearerToken(userName, password);
            Uri tokenUri = new Uri("api.somedemo.com/token");
            token = OAuthClientWrapper.GetJwtToken(tokenUri, bearerTokenContent);

            return token;
        }

OAuthClientWrapper类:

public static FormUrlEncodedContent CreateBearerToken(string userName, string password)
        {
            var bearerTokenContent = new List<KeyValuePair<string, string>>
            {
                new KeyValuePair<string, string>("username", userName),
                new KeyValuePair<string, string>("password", password),
                new KeyValuePair<string, string>("grant_type", "password")
            };

            return new FormUrlEncodedContent(bearerTokenContent);
        }

GetJwtToken方法:

public static BearerToken GetJwtToken(Uri uri, FormUrlEncodedContent bearerTokenContent)
        {
            BearerToken token = null;

            try
            {
                using (var httpClient = new HttpClient())
                {
                    //Set the headers
                    httpClient.DefaultRequestHeaders.Accept.Clear();
                    httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));


                    using (HttpResponseMessage response = httpClient.PostAsync(uri, bearerTokenContent).Result)
                    {
                        if (response.IsSuccessStatusCode)
                        {
                            token = response.Content.ReadAsAsync<BearerToken>().Result;
                        }
                        else
                        {
                            var reasonPhrase = response.ReasonPhrase;
                            var result = response.Content.ReadAsStringAsync();
                            var errorMessage = string.Format("Error: {0} {1} for uri: {2}", reasonPhrase, result, uri.AbsoluteUri);
                            //Log the error message
                            token = null;
                        } //else
                    } //using
                }//using
            }//try
            catch (AggregateException aex)
            {

                throw aex;
            }//catch

            return token;
        } 

作为WebAPI启动类:

public partial class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=316888
            ConfigureAuth(app);
            app.UseOAuthAuthorizationServer(OAuthOptions);
            app.UseJwtBearerAuthentication(new MyJwtOptions());
        }
    }

Startupoverride:

 public partial class Startup
    {
        public static OAuthAuthorizationServerOptions OAuthOptions { get; private set; }


        // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app)
        {

            int tokenExpiration = Convert.ToInt32(ConfigurationManager.AppSettings["TokenExpiration"]);

            OAuthOptions = new OAuthAuthorizationServerOptions
            {
                 AllowInsecureHttp = true,
                TokenEndpointPath = new PathString("/Token"),
                 Provider = new ApplicationOAuthProvider(),
                //AccessTokenFormat = new JwtFormat(audience, new SymmetricKeyIssuerSecurityTokenProvider(issuer, signingKey)),
                AccessTokenFormat = new MyJwtFormat(),
                RefreshTokenProvider = new ApplicationRefreshTokenProvider(),
                AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(tokenExpiration)

            };
            // Token Generation
            app.UseOAuthAuthorizationServer(OAuthOptions);
            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
        }
    }

应用程序OAuthProviderClass:

public class ApplicationOAuthProvider : OAuthAuthorizationServerProvider
    {
        private readonly string _publicClientId;
        IHttpClientWrapper _HttpClientWrapper = null;
        private IEndPoints _ConfigsProviders = null;


        public ApplicationOAuthProvider()
        {
            _HttpClientWrapper = new HttpClientWrapper();
            _ConfigsProviders = new EndPoints();
        }

        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            try
            {
                var isValidUser = false;
                context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });

                var url = string.Format("{0}/{1}/{2}", "someAPIBaseUrl", context.UserName, context.Password);
                //Getting user information if login is validated in json format.
                var returnValue = _HttpClientWrapper.GetStringAsync(url);

                var responseObject = JsonConvert.DeserializeObject<ResponseObject>(returnValue);
                if (responseObject.Status==true)
                {
                    isValidUser = true;
                }

                if (!isValidUser)
                {
                    context.SetError("invalid_grant", "The user name or password is incorrect.");
                    return;
                }

                var identity = new ClaimsIdentity(context.Options.AuthenticationType);
                identity.AddClaim(new Claim("sub", context.UserName));
                context.Validated(identity);
            }
            catch (Exception ex)
            {

                throw ex;
            }

        }


        public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            context.Validated();
        }


        public override Task TokenEndpoint(OAuthTokenEndpointContext context)
        {
            foreach (KeyValuePair<string, string> property in context.Properties.Dictionary)
            {
                context.AdditionalResponseParameters.Add(property.Key, property.Value);
            }

            return Task.FromResult<object>(null);
        }

        public override Task ValidateClientRedirectUri(OAuthValidateClientRedirectUriContext context)
        {
            if (context.ClientId == _publicClientId)
            {
                Uri expectedRootUri = new Uri(context.Request.Uri, "/");

                if (expectedRootUri.AbsoluteUri == context.RedirectUri)
                {
                    context.Validated();
                }
            }

            return Task.FromResult<object>(null);
        }

        public static AuthenticationProperties CreateProperties(string userName)
        {
            IDictionary<string, string> data = new Dictionary<string, string>
            {
                { "userName", userName }
            };
            return new AuthenticationProperties(data);
        }

    }





   public MyJwtFormat()
            {
                _tokenIssuer = ConfigurationManager.AppSettings["TokenIssuer"];
                _tokenExpiration = Convert.ToInt32(ConfigurationManager.AppSettings["TokenExpiration"]);
            }

ConfigurationManager.AppSettings [&#34; TokenIssuer&#34;]给出&#34; localhost&#34;在服务器中也是。

请帮助解决此问题

预先谢谢你。

0 个答案:

没有答案