Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I implement an OAuth2 Authorization_Code Flow in Web Api using OWIN Middleware?

I'm trying to create a simple proof of concept OAuth enabled application but am stuck on the authorization code implementation. Everywhere I read seems like it goes in one way or another, never actually using the authorization code flow. I've been using the following resources for information:

  • https://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-31
  • https://aaronparecki.com/articles/2012/07/29/1/oauth2-simplified
  • http://www.asp.net/aspnet/overview/owin-and-katana/owin-oauth-20-authorization-server

I have setup web api and owin with a custom OAuthAuthorizationServerProvider to accept password grant types for refresh tokens and the ability to exchange a refresh token for an access token. This is working well, but I want to setup a scenario where I redirect a browser to the server to authorize and redirect back to the client with an authorization code. I then want the client to sent the authorization code to the token endpoint to get a refresh token

In the second link under Web Server Apps, I'm trying to get my web api app to surface an authorization code from a request like, http://127.0.0.1/auth?response_type=code&client_id=123&redirect_uri=http://validredirect.com&scope=access, but I keep getting a 404.

I've configured owin as follows:

var databaseContext = new AdnsfContext();

WebApp.Start(
    new StartOptions("http://127.0.0.1:7000"),
    appBuilder =>
    {
        var httpConfig = new HttpConfiguration();
        httpConfig.MapHttpAttributeRoutes();
        httpConfig.SuppressDefaultHostAuthentication();
        httpConfig.Filters.Add(new HostAuthenticationFilter("Bearer"));

        appBuilder
            .UseOAuthAuthorizationServer(new OAuthAuthorizationServerOptions
                {
                    AllowInsecureHttp = true,
                    ApplicationCanDisplayErrors = true,
                    AuthorizeEndpointPath = new PathString("/auth"),
                    TokenEndpointPath = new PathString("/token"),
                    AuthorizationCodeExpireTimeSpan = TimeSpan.FromMinutes(1),
                    AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(1),
                    Provider = new AuthServerProvider(),
                    AuthorizationCodeProvider = new AuthorizationCodeProvider(),
                    RefreshTokenProvider = new RefreshTokenProvider(),
                })
            .UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions
                {
                    AuthenticationMode = Microsoft.Owin.Security.AuthenticationMode.Active,
                    AuthenticationType = "Bearer",
                })
            .UseCors(CorsOptions.AllowAll)
            .UseWebApi(httpConfig);
    });

The pieces I've added to enable the authorization endpoint are the properties for the auth server options:

AuthorizeEndpointPath = new PathString("/auth"),
AuthorizationCodeExpireTimeSpan = TimeSpan.FromMinutes(1),
AuthorizationCodeProvider = new AuthorizationCodeProvider(),

The overrides in my implementation of the AuthorizationCodeProvider throw not implemented exceptions but it's currently not even hitting any breakpoints set in the code. One thing to note is that when I use postman to hit the auth endpoint, I get a server header back for HTTPAPI/2.0 which is different than if there simply isn't something surfaced at that endpoint, which means I must be sending the request incorrectly. Can anyone see a problem with my setup? Thanks in advance, I know that this is clearly my failing in understanding OWIN and OAuth.

like image 976
Joshua Belden Avatar asked Feb 26 '15 18:02

Joshua Belden


People also ask

How is OAuth flow implemented?

Step-by-stepCreate a log-in link with the app's client ID, redirect URL, state, and PKCE code challenge parameters. The user sees the authorization prompt and approves the request. The user is redirected back to the app's server with an auth code. The app exchanges the auth code for an access token.

How does OAuth2 work in Web API?

OAuth2 allows authorization without the external application getting the user's email address or password. Instead, the external application gets a token that authorizes access to the user's account. The user can revoke the token for one application without affecting access by any other application.


2 Answers

One thing to note with the OAuth2 authorization server built in Katana is that it's transparent: you must provide your own /auth endpoint (using MVC or Nancy for instance) or directly render your consent form in OAuthAuthorizationServerProvider.AuthorizationEndpoint

You can take a look at https://github.com/aspnet-contrib/AspNet.Security.OpenIdConnect.Server/tree/dev/samples/Mvc for a complete sample. It doesn't use the OAuth2 authorization server built in Katana but a much more elaborated fork targeting OpenID Connect but you should get the idea.

like image 84
Kévin Chalet Avatar answered Oct 17 '22 22:10

Kévin Chalet


Take a look at IdentityServer. It's based on Owin. There is also samples repository where you can find a lot of examples using selfdeployed and\or 3rd party identity providers.

I think that this one example is most appropriate for you.

like image 43
balbelias Avatar answered Oct 17 '22 22:10

balbelias