简体   繁体   中英

OAuth Bearer Token Not Working for WebApi

I have gone through a lot of docs but it seems my problem is strange. I have configured Oauth but I am not able to get the bearer token back. whenever I hit api to get the token, I get 200 but nothing back in response(I am expecting bearer token). Below is the config:

 public partial class Startup
{
    public void ConfigureAuth(IAppBuilder app)
    {
        OAuthAuthorizationServerOptions oAuthOptions = new OAuthAuthorizationServerOptions
        {
            AllowInsecureHttp = true,
            TokenEndpointPath = new PathString("/token"),
            AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(20),
            Provider = new ApplicationOAuthProvider()
        };
        app.UseOAuthAuthorizationServer(oAuthOptions);
        app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions
        {
            Provider = new OAuthBearerAuthenticationProvider()
        });

        HttpConfiguration config = new HttpConfiguration();
        //config.Filters.Add(new );
        //config.MapHttpAttributeRoutes();
        // There can be multiple exception loggers. (By default, no exception loggers are registered.)
        //config.Services.Replace(typeof(IExceptionHandler), new GlobalExceptionHandler());
        WebApiConfig.Register(config);
        //enable cors origin requests
        app.UseCors(CorsOptions.AllowAll);
        app.UseWebApi(config);            
    }
}


 public static class WebApiConfig
{
    /// <summary>
    /// 
    /// </summary>
    /// <param name="config"></param>
    public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services
        // Configure Web API to use only bearer token authentication.
        config.SuppressDefaultHostAuthentication();
        config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));

        // Web API routes
        config.MapHttpAttributeRoutes();
        config.Filters.Add(new HostAuthenticationAttribute("bearer")); //added this
        config.Filters.Add(new AuthorizeAttribute());
        config.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{id}", new { id = RouteParameter.Optional }
        );

        var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().First();
        jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();

    }

public class ApplicationOAuthProvider : OAuthAuthorizationServerProvider
{
    public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
    {
        context.Validated();
    }

    public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
    {
        var form = await context.Request.ReadFormAsync();
        if (myvalidationexpression)
        {
            var identity = new ClaimsIdentity(context.Options.AuthenticationType);
            identity.AddClaim(new Claim(ClaimTypes.Role, "AuthorizedUser"));
            context.Validated(identity);
        }
        else
        {
            context.SetError("invalid_grant", "Provided username and password is incorrect");
        }
    }
}

Now when I launch the APi and hit /token, I get this as below:

API Request

I think that code you have written in WebApiConfig.cs to suppress host authentication and some other code is creating the issue. I have a working example for bearer token generation in web API, which is working properly and generating token.

WebApiConfig.cs file code:

      public static class WebApiConfig
        {
            public static void Register(HttpConfiguration config)
            {
                // Web API configuration and services

                // Web API routes
                config.MapHttpAttributeRoutes();

                config.Routes.MapHttpRoute(
                    name: "DefaultApi",
                    routeTemplate: "api/{controller}/{id}",
                    defaults: new { id = RouteParameter.Optional }
                );
            }
        }

Startup.cs Code:

[assembly: OwinStartup(typeof(WebAPI.Startup))]
namespace WebAPI
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            HttpConfiguration config = new HttpConfiguration();
            ConfigureOAuth(app);
            WebApiConfig.Register(config);
            app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);


        }
        public void ConfigureOAuth(IAppBuilder app)
        {
            OAuthAuthorizationServerOptions
             OAuthServerOptions = new OAuthAuthorizationServerOptions()
             {
                 AllowInsecureHttp = true,
                 TokenEndpointPath = new PathString("/token"),
                 AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(60),
                 Provider=new ApplicationOAuthProvider(),
                 //AuthenticationMode = AuthenticationMode.Active
             };
            app.UseOAuthAuthorizationServer(OAuthServerOptions);
            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions {
                Provider = new OAuthBearerAuthenticationProvider()
            }
            );
        }
    }
}

Controller to check authorization call after adding bearer token in the request.

 public class TokenTestController : ApiController
    {
        [Authorize]
        public IHttpActionResult Authorize()
        {
            return Ok("Authorized");
        }

    }

install the following package

Microsoft.Owin.Host.SystemWeb

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM