Skip to content

Commit

Permalink
Refactor additional oauth config for consistency
Browse files Browse the repository at this point in the history
  • Loading branch information
domaindrivendev committed Feb 21, 2018
1 parent 1f217e5 commit ff61147
Show file tree
Hide file tree
Showing 8 changed files with 121 additions and 59 deletions.
17 changes: 16 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -813,7 +813,22 @@ To get started, you should base your custom index.html on the [default version](

The swagger-ui has built-in support to participate in OAuth2.0 authorization flows. It interacts with authorization and/or token endpoints, as specified in the Swagger JSON, to obtain access tokens for subsequent API calls. See [Adding Security Definitions and Requirements](#add-security-definitions-and-requirements) for an example of adding OAuth2.0 metadata to the generated Swagger.

If you're Swagger endpoint includes the appropriate security metadata, the UI interaction should be automatically enabled:
If you're Swagger endpoint includes the appropriate security metadata, the UI interaction should be automatically enabled. However, you can further customize OAuth support in the UI with the following settings below. See https://github.com/swagger-api/swagger-ui/blob/v3.10.0/docs/usage/oauth2.md for more info:

```csharp
app.UseSwaggerUI(c =>
{
...

c.OAuthClientId("test-id");
c.OAuthClientSecret("test-secret");
c.OAuthRealm("test-realm");
c.OAuthAppName("test-app");
c.OAuthScopeSeparator(" ");
c.OAuthAdditionalQueryStringParams(new { foo = "bar" });
c.OAuthUseBasicAuthenticationWithAccessCodeGrant();
});
```

## Swashbuckle.AspNetCore.Cli ##

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,8 @@ private async void RespondWithIndexHtml(HttpResponse response)
{
{ "%(DocumentTitle)", _options.DocumentTitle },
{ "%(HeadContent)", _options.HeadContent },
{ "%(ConfigObject)", JsonConvert.SerializeObject(_options.ConfigObject) }
{ "%(ConfigObject)", JsonConvert.SerializeObject(_options.ConfigObject) },
{ "%(OAuthConfigObject)", JsonConvert.SerializeObject(_options.OAuthConfigObject) }
};
}
}
Expand Down
7 changes: 7 additions & 0 deletions src/Swashbuckle.AspNetCore.SwaggerUI/SwaggerUIOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -35,5 +35,12 @@ public class SwaggerUIOptions
{
urls = new object[] { }
});

/// <summary>
/// Gets the JavaScript config object, represented as JSON, that will be passed to the initOAuth method
/// </summary>
public JObject OAuthConfigObject { get; } = JObject.FromObject(new
{
});
}
}
92 changes: 68 additions & 24 deletions src/Swashbuckle.AspNetCore.SwaggerUI/SwaggerUIOptionsExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -171,30 +171,74 @@ public static void ValidatorUrl(this SwaggerUIOptions options, string url)
}

/// <summary>
/// Enable OAuth2 UI Interactions. See swagger-ui project for more info.
/// </summary>
/// <param name="options"></param>
/// <param name="clientId">Default clientId</param>
/// <param name="clientSecret">Default clientId</param>
/// <param name="realm">Realm query parameter (for oauth1) added to authorizationUrl and tokenUrl</param>
/// <param name="appName">Application name, displayed in authorization popup</param>
/// <param name="scopeSeparator">Scope separator for passing scopes, encoded before calling, default value is a space (encoded value %20)</param>
/// <param name="useBasicAuthenticationWithAccessCodeGrant">Only activated for the accessCode flow. During the authorization_code request to the tokenUrl, pass the Client Password using the HTTP Basic Authentication scheme (Authorization header with Basic base64encoded[client_id:client_secret])</param>
public static void ConfigureOAuth2(
this SwaggerUIOptions options,
string clientId,
string clientSecret = null,
string realm = null,
string appName = "",
string scopeSeparator = " ",
bool useBasicAuthenticationWithAccessCodeGrant = false)
{
options.ConfigObject["OAuth2ClientId"] = clientId;
options.ConfigObject["OAuth2ClientSecret"] = clientSecret ?? "na"; //swagger-ui needs a value
options.ConfigObject["OAuth2Realm"] = realm ?? "na"; //swagger-ui needs a value
options.ConfigObject["OAuth2AppName"] = appName;
options.ConfigObject["OAuth2ScopeSeparator"] = scopeSeparator;
options.ConfigObject["OAuth2UseBasicAuthenticationWithAccessCodeGrant"] = useBasicAuthenticationWithAccessCodeGrant;
/// Default clientId
/// </summary>
/// <param name="options"></param>
/// <param name="value"></param>
public static void OAuthClientId(this SwaggerUIOptions options, string value)
{
options.OAuthConfigObject["clientId"] = value;
}

/// <summary>
/// Default clientSecret
/// </summary>
/// <param name="options"></param>
/// <param name="value"></param>
public static void OAuthClientSecret(this SwaggerUIOptions options, string value)
{
options.OAuthConfigObject["clientSecret"] = value;
}

/// <summary>
/// realm query parameter (for oauth1) added to authorizationUrl and tokenUrl
/// </summary>
/// <param name="options"></param>
/// <param name="value"></param>
public static void OAuthRealm(this SwaggerUIOptions options, string value)
{
options.OAuthConfigObject["realm"] = value;
}

/// <summary>
/// Application name, displayed in authorization popup
/// </summary>
/// <param name="options"></param>
/// <param name="value"></param>
public static void OAuthAppName(this SwaggerUIOptions options, string value)
{
options.OAuthConfigObject["appName"] = value;
}

/// <summary>
/// Scope separator for passing scopes, encoded before calling, default value is a space (encoded value %20)
/// </summary>
/// <param name="options"></param>
/// <param name="value"></param>
public static void OAuthScopeSeparator(this SwaggerUIOptions options, string value)
{
options.OAuthConfigObject["scopeSeparator"] = value;
}

/// <summary>
/// Additional query parameters added to authorizationUrl and tokenUrl
/// </summary>
/// <param name="options"></param>
/// <param name="value"></param>
public static void OAuthAdditionalQueryStringParams(this SwaggerUIOptions options, object value)
{
options.OAuthConfigObject["additionalQueryStringParams"] = JObject.FromObject(value);
}

/// <summary>
/// Only activated for the accessCode flow. During the authorization_code request to the tokenUrl,
/// pass the Client Password using the HTTP Basic Authentication scheme (Authorization header with
/// Basic base64encoded[client_id:client_secret]). The default is false
/// </summary>
/// <param name="options"></param>
public static void OAuthUseBasicAuthenticationWithAccessCodeGrant(this SwaggerUIOptions options)
{
options.OAuthConfigObject["useBasicAuthenticationWithAccessCodeGrant"] = true;
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,7 @@
</PropertyGroup>

<ItemGroup>
<EmbeddedResource Include="bower_components\swagger-ui\dist\**\*.png" />
<EmbeddedResource Include="bower_components\swagger-ui\dist\**\*.css" />
<EmbeddedResource Include="bower_components\swagger-ui\dist\**\oauth2-redirect.html" />
<EmbeddedResource Include="bower_components\swagger-ui\dist\**\swagger-ui-bundle.js" />
<EmbeddedResource Include="bower_components\swagger-ui\dist\**\swagger-ui-standalone-preset.js" />
<EmbeddedResource Include="bower_components\swagger-ui\dist\**\*.*" Exclude="bower_components\swagger-ui\dist\**\*.map" />
<EmbeddedResource Include="index.html" />
</ItemGroup>

Expand All @@ -32,9 +28,4 @@
<PackageReference Include="Microsoft.Extensions.FileProviders.Embedded" Version="1.0.1" />
<PackageReference Include="Newtonsoft.Json" Version="9.0.1" />
</ItemGroup>

<ItemGroup Condition=" '$(TargetFramework)' == 'netstandard1.6' ">
<PackageReference Include="System.Xml.XPath" Version="4.0.0" />
</ItemGroup>

</Project>
35 changes: 15 additions & 20 deletions src/Swashbuckle.AspNetCore.SwaggerUI/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -71,26 +71,21 @@
<script src="./swagger-ui-bundle.js"> </script>
<script src="./swagger-ui-standalone-preset.js"> </script>
<script>
window.onload = function() {
var configObject = JSON.parse('%(ConfigObject)');

// Apply mandatory parameters
configObject.dom_id = "#swagger-ui";
configObject.presets = [SwaggerUIBundle.presets.apis, SwaggerUIStandalonePreset];
configObject.layout = "StandaloneLayout";

// Build a system
const ui = SwaggerUIBundle(configObject);
ui.initOAuth({
clientId: configObject.OAuth2ClientId,
clientSecret: configObject.OAuth2ClientSecret,
realm: configObject.OAuth2Realm,
appName: configObject.OAuth2AppName,
scopeSeparator: configObject.OAuth2ScopeSeparator,
useBasicAuthenticationWithAccessCodeGrant: configObject.useBasicAuthenticationWithAccessCodeGrant
});
window.ui = ui;
}
window.onload = function () {
var configObject = JSON.parse('%(ConfigObject)');
var oauthConfigObject = JSON.parse('%(OAuthConfigObject)');

// Apply mandatory parameters
configObject.dom_id = "#swagger-ui";
configObject.presets = [SwaggerUIBundle.presets.apis, SwaggerUIStandalonePreset];
configObject.layout = "StandaloneLayout";

// Build a system
const ui = SwaggerUIBundle(configObject);

// Apply OAuth config
ui.initOAuth(oauthConfigObject);
}
</script>
</body>

Expand Down
6 changes: 3 additions & 3 deletions test/WebSites/OAuth2Integration/AuthServer/Config.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,9 @@ internal static IEnumerable<Client> Clients()
AllowAccessTokensViaBrowser = true,
AllowedGrantTypes = GrantTypes.Implicit,
AllowedScopes = new[] { "readAccess", "writeAccess" },
ClientId = "swagger-ui",
ClientName = "Swagger UI",
ClientSecrets = new[] { new Secret("swagger-ui-secret".Sha256()) },
ClientId = "test-id",
ClientName = "test-app",
ClientSecrets = new[] { new Secret("test-secret".Sha256()) },
RedirectUris = new[] { "http://localhost:50581/resource-server/swagger/oauth2-redirect.html" }
};
}
Expand Down
9 changes: 9 additions & 0 deletions test/WebSites/OAuth2Integration/Startup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,15 @@ public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerF
{
c.SwaggerEndpoint("/resource-server/swagger/v1/swagger.json", "My API V1");
c.OAuth2RedirectUrl("http://localhost:50581/resource-server/swagger/oauth2-redirect.html");
// Additional OAuth settings (See https://github.com/swagger-api/swagger-ui/blob/v3.10.0/docs/usage/oauth2.md)
c.OAuthClientId("test-id");
c.OAuthClientSecret("test-secret");
c.OAuthRealm("test-realm");
c.OAuthAppName("test-app");
c.OAuthScopeSeparator(" ");
c.OAuthAdditionalQueryStringParams(new { foo = "bar" });
c.OAuthUseBasicAuthenticationWithAccessCodeGrant();
});
});
}
Expand Down

0 comments on commit ff61147

Please sign in to comment.