How to get authorization code with OWIN, OAuth and Web API?

11,356

A crucial thing to remember when using the OAuth2 authorization server built in Katana is that its authorization endpoint is pass-through by default: you must provide your own /authorize endpoint (using MVC or Nancy for instance) or directly render your consent form in OAuthAuthorizationServerProvider.AuthorizationEndpoint.

You can take a look at the official documentation for a complete walkthrough indicating how you can implement your own MVC controller and your own authorization endpoint.

Share:
11,356

Related videos on Youtube

DotNetMatt
Author by

DotNetMatt

Updated on June 04, 2022

Comments

  • DotNetMatt
    DotNetMatt almost 2 years

    I followed this post: Token Based Authentication using ASP.NET Web API 2, Owin, and Identity. Now, I have a Web API standalone "server" able to successfully authenticate users and returns an Access Token when I send username/password to it. Then, I can use the Access Token to access protected data (in the blog post, I can access the Orders).

    For now, the client from which I sent username/password to get the Access Token is a Console app.

    I want to add a bit more complexity and before getting the Access Token, I would like to get an Authorization Code. But I cannot find any example on how to do it. From what I read, I should send a GET request structured like this:

    /authorize?response_type=code&client_id=< ClientID>

    This is what I am doing from my console app:

    using (var client = new HttpClient())
    {
        var response = await client.GetAsync("http://localhost:63828/authorize?response_type=code&client_id=" + Guid.NewGuid());
    
        var responseString = response.Content.ReadAsStringAsync().Result;
    }
    

    But I get an error message:

    The resource cannot be found.

    [HttpException]: The controller for path '/authorize' was not found or does not implement IController. at System.Web.Mvc.DefaultControllerFactory.GetControllerInstance(RequestContext requestContext, Type controllerType) at System.Web.Mvc.DefaultControllerFactory.CreateController(RequestContext requestContext, String controllerName) at System.Web.Mvc.MvcHandler.ProcessRequestInit(HttpContextBase httpContext, IController& controller, IControllerFactory& factory) at System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) at System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state) at System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData) at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)

    This is the content of the Startup.cs file in the Web API project:

    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            HttpConfiguration config = new HttpConfiguration();
    
            ConfigureOAuth(app);
    
            WebApiConfig.Register(config);
            app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
            app.UseWebApi(config);
        }
    
        public void ConfigureOAuth(IAppBuilder app)
        {
            OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
            {
                AllowInsecureHttp = true,
                TokenEndpointPath = new PathString("/token"),
                AuthorizeEndpointPath = new PathString("/authorize"),
                ApplicationCanDisplayErrors = true,
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
                Provider = new SimpleAuthorizationServerProvider()
            };
    
            // Token Generation
            app.UseOAuthAuthorizationServer(OAuthServerOptions);
            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
        }
    }
    

    What I find weird is that I defined the "/authorize" endpoint but it is not accessible... The "/token" endpoint is accessible and I did not do anything special for this.

    Any idea how I can overcome this?

    • foyss
      foyss over 4 years
      Did you ever manage to get the authorization code from your authorization endpoint? If so, how?
  • Kévin Chalet
    Kévin Chalet over 8 years
    For a complete sample, you can also take a look at this Nancy client/server demo. It doesn't use OAuthAuthorizationServerMiddleware but a much more elaborated fork targeting OpenID Connect but you should get the idea.