public void EnableSwaggerUi(string routeTemplate, Action <SwaggerUiConfig> configure = null) { SecurityScheme secScheme = null; var config = new SwaggerUiConfig(_config.DiscoveryPaths(_route), _config.GetRootUrl); if (configure != null) { if (_config.ApiKeyScheme != null) { secScheme = _config.ApiKeyScheme.Build(); config.ApiKeySupport(secScheme.name, secScheme.@in); } configure(config); } _httpConfig.Routes.MapHttpRoute( name: "swagger_ui" + routeTemplate, routeTemplate: routeTemplate, defaults: null, constraints: new { assetPath = @".+" }, handler: new SwaggerUiHandler(config) ); if (routeTemplate == DefaultRouteTemplate) { _httpConfig.Routes.MapHttpRoute( name: "swagger_ui_shortcut", routeTemplate: "swagger", defaults: null, constraints: new { uriResolution = new HttpRouteDirectionConstraint(HttpRouteDirection.UriResolution) }, handler: new RedirectHandler(_config.GetRootUrl, "swagger/ui/index")); } }
/// <summary> /// Add one or more "securityDefinitions", describing how your API is protected, to the generated Swagger /// </summary> /// <param name="swaggerGenOptions">The swagger gen options.</param> /// <param name="name">A unique name for the scheme, as per the Swagger spec.</param> /// <param name="securityScheme"> /// A description of the scheme - can be an instance of BasicAuthScheme, ApiKeyScheme or /// OAuth2Scheme /// </param> public static void AddSecurityDefinition( this SwaggerGenOptions swaggerGenOptions, string name, SecurityScheme securityScheme) { swaggerGenOptions.SwaggerGeneratorOptions.SecurityDefinitions.Add(name, securityScheme); }
public IAuthenticationHandler GetAuthenticator(SecurityScheme scheme) { return(scheme.Type.ToLowerInvariant() switch { "jwt" => (IAuthenticationHandler)_serviceProvider.GetService(typeof(JwtAuthenticationHandler)), _ => (IAuthenticationHandler)_serviceProvider.GetService(typeof(JwtAuthenticationHandler)) });
/// <summary> /// Add documentation pertinent to OpenId authentication on the endpoint /// </summary> /// <param name="endpointInfo"></param> /// <param name="url">A valid url to refer the client</param> /// <param name="description"></param> /// <returns></returns> public static Endpoint WithOpenIdConnectAuthentication(this Endpoint endpointInfo, string authorizationUrl, string flow, string tokenUrl, string openIdConnectUrl, string description = null, string refreshUrl = null, params string[] scopes) { string securityKey = "openIdConnect"; var flowspec = new Flow() { AuthorizationUrl = authorizationUrl, TokenUrl = tokenUrl, RefreshUrl = refreshUrl, Scopes = scopes }; var oauth2 = MatchFlow(flowspec, flow); var security = new SecurityScheme() { Type = "openIdConnect", OpenIdConnectUrl = openIdConnectUrl, Flows = oauth2, Name = securityKey, Description = description }; return(SaveAuthentication(endpointInfo, securityKey, security)); }
public override object ReadJson( JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { JObject jsonObject = JObject.Load(reader); SecurityScheme scheme = null; string type = jsonObject["type"].ToString(); switch (type) { case "apiKey": scheme = new ApiKeyScheme(); break; case "oauth2": scheme = new OAuth2Scheme(); break; case "basic": scheme = new BasicAuthScheme(); break; default: throw new ArgumentException($"Unexpected security scheme '{type}'"); } serializer.Populate(jsonObject.CreateReader(), scheme); return(scheme); }
public void InitializeSecuritySchemeWithRecordSuccess() { // Arrange IEdmRecordExpression record = new EdmRecordExpression( new EdmPropertyConstructor("Authorization", new EdmStringConstant("DelegatedWork")), new EdmPropertyConstructor("RequiredScopes", new EdmCollectionExpression( new EdmStringConstant("User.ReadAll"), new EdmStringConstant("User.WriteAll")))); SecurityScheme securityScheme = new SecurityScheme(); Assert.Null(securityScheme.Authorization); Assert.Null(securityScheme.RequiredScopes); // Act securityScheme.Initialize(record); // Assert Assert.NotNull(securityScheme.Authorization); Assert.Equal("DelegatedWork", securityScheme.Authorization); Assert.NotNull(securityScheme.RequiredScopes); Assert.Equal(2, securityScheme.RequiredScopes.Count); Assert.Equal(new[] { "User.ReadAll", "User.WriteAll" }, securityScheme.RequiredScopes); }
protected Security(string name, SecurityScheme securityType, OpenApiSecuritySchemeType type, OpenApiSecurityApiKeyLocation @in) { Name = name; SecurityType = securityType; Type = type; In = @in; }
public void Should_AbleToSetSecurityDefinition() { var securityScheme = new SecurityScheme(); var swaggerRoot = GetBasicSwaggerRootBuilder().SecurityDefinition("name", securityScheme).Build(); Assert.True(swaggerRoot.SecurityDefinitions.ContainsKey("name")); Assert.Equal(securityScheme, swaggerRoot.SecurityDefinitions["name"]); }
/// <summary> /// Add a Security scheme definitions that can be used across the specification. /// </summary> /// <param name="name"> /// The name. /// </param> /// <param name="scheme"> /// The scheme. /// </param> /// <returns> /// The <see cref="SwaggerRootBuilder"/>. /// </returns> public SwaggerRootBuilder SecurityDefinition(string name, SecurityScheme scheme) { if (this.securityDefinitions == null) { this.securityDefinitions = new Dictionary <string, SecurityScheme>(); } this.securityDefinitions.Add(name, scheme); return(this); }
public OpenApiSecurityScheme GetSecuritySchemaByType(SecurityScheme securityScheme) { var schema = Securities.Where(a => a.SecurityType == securityScheme); if (schema.Any()) { return(schema.First().OpenApiSecurityScheme()); } return(Securities.First(a => a.SecurityType == SecurityScheme.Basic).OpenApiSecurityScheme()); }
/// <summary> /// Add documentation pertinent to custom key authentication on the endpoint /// </summary> /// <param name="endpointInfo"></param> /// <param name="name"></param> /// <param name="location">Plausible values are cookie, header and query</param> /// <param name="description"></param> /// <returns></returns> public static Endpoint WithApiKeyAuthentication(this Endpoint endpointInfo, string name, string location, string description = null) { var security = new SecurityScheme() { Type = "apiKey", Name = name, In = location, Description = description }; return(SaveAuthentication(endpointInfo, name, security)); }
private Dictionary <string, SecurityScheme> GetSecurityDefinitions() { var securityScheme = new SecurityScheme { type = "Https", description = "Please enter into field the word 'Basic' following by space and Authorization" }; return(new Dictionary <string, SecurityScheme> { { "Basic", securityScheme } }); }
/// <summary> /// Saves the Security Schemes on the Cache Dictionary also returns the key used. /// </summary> /// <param name="securityScheme"></param> /// <returns></returns> internal static string GetOrSaveSecurity(SecurityScheme securityScheme) { string key = securityScheme.Name; if (SchemaCache.SecurityCache.ContainsKey(key)) { return(key); } SchemaCache.SecurityCache[key] = securityScheme; return(key); }
public static SecurityScheme LoadSecurityScheme(ParseNode node) { var mapNode = node.CheckMapNode("securityScheme"); var securityScheme = new SecurityScheme(); foreach (var property in mapNode) { property.ParseField(securityScheme, SecuritySchemeFixedFields, SecuritySchemePatternFields); } return(securityScheme); }
/// <summary> /// Add documentation pertinent to basic authentication on the endpoint /// </summary> /// <param name="endpointInfo"></param> /// <param name="description"></param> /// <returns></returns> public static Endpoint WithBasicAuthentication(this Endpoint endpointInfo, string description = null) { string securityKey = "basic"; var security = new SecurityScheme() { Type = "http", Scheme = "basic", Name = securityKey, Description = description }; return(SaveAuthentication(endpointInfo, securityKey, security)); }
public static SecurityRequirement LoadSecurityRequirement(ParseNode node) { var mapNode = node.CheckMapNode("security"); var obj = new SecurityRequirement(); foreach (var property in mapNode) { var scheme = SecurityScheme.LoadByReference(new ValueNode(mapNode.Context, property.Name)); obj.Schemes.Add(scheme, property.Value.CreateSimpleList <string>(n2 => n2.GetScalarValue())); } return(obj); }
/// <summary> /// Add documentation pertinent to bearer (jwt) authentication on the endpoint /// </summary> /// <param name="endpointInfo"></param> /// <param name="bearerFormat">The format of the bearer</param> /// <param name="description"></param> /// <returns></returns> public static Endpoint WithBearerAuthentication(this Endpoint endpointInfo, string bearerFormat, string description = null) { string securityKey = "bearer"; var security = new SecurityScheme() { Type = "http", Scheme = "bearer", Name = securityKey, BearerFormat = bearerFormat, Description = description }; return(SaveAuthentication(endpointInfo, securityKey, security)); }
public SecurityScheme Build(IDictionary <string, object> dynamicRaml) { var securityScheme = new SecurityScheme(); new BasicInfoBuilder().Set(dynamicRaml, securityScheme); securityScheme.DescribedBy = dynamicRaml.ContainsKey("describedBy") ? new SecuritySchemeDescriptorBuilder().Build((IDictionary <string, object>)dynamicRaml["describedBy"]) : null; securityScheme.Settings = dynamicRaml.ContainsKey("settings") ? new SecuritySettingsBuilder().Build((IDictionary <string, object>)dynamicRaml["settings"]) : null; return(securityScheme); }
public static Security GetSecurity(RamlDocument ramlDocument) { if (ramlDocument.SecuritySchemes == null || !ramlDocument.SecuritySchemes.Any()) { return(null); } SecurityScheme securityScheme = null; if (IsTypeDefined(ramlDocument, OAuth2Type)) { securityScheme = GetSchemeWithType(ramlDocument, OAuth2Type); } else if (AreOAuth2EndpointsDefined(ramlDocument)) { securityScheme = GetSchemeWithOAuth2EndpointsDefined(ramlDocument); } else if (IsTypeDefined(ramlDocument, OAuth1Type)) { securityScheme = GetSchemeWithType(ramlDocument, OAuth1Type); } if (securityScheme == null || (securityScheme.Settings == null && securityScheme.DescribedBy == null)) { return(new Security()); } var settings = securityScheme.Settings; var schemeDescriptor = securityScheme.DescribedBy; return(new Security { AccessTokenUri = settings == null ? null : settings.AccessTokenUri, AuthorizationGrants = settings == null ? null : settings.AuthorizationGrants.ToArray(), AuthorizationUri = settings == null ? null : settings.AuthorizationUri, Scopes = settings == null ? null : settings.Scopes.ToArray(), RequestTokenUri = settings == null ? null : settings.RequestTokenUri, TokenCredentialsUri = settings == null ? null : settings.TokenCredentialsUri, Headers = schemeDescriptor == null || schemeDescriptor.Headers == null ? new List <GeneratorParameter>() : ParametersMapper.Map(schemeDescriptor.Headers).ToList(), QueryParameters = schemeDescriptor == null || schemeDescriptor.QueryParameters == null ? new List <GeneratorParameter>() : ParametersMapper.Map(schemeDescriptor.QueryParameters).ToList() }); }
private Dictionary <string, SecurityScheme> CreateSecurityDefinitions() { var secDefs = new Dictionary <string, SecurityScheme>(); var securityScheme = new SecurityScheme() { Type = SecuritySchemes.Oauth2, AuthorizationUrl = oauthUrl, Flow = Oauth2Flows.Implicit, Scopes = new Dictionary <string, string> { { "read", "Read privilege." }, { "write", "Write privilege." }, } }; secDefs.Add("Oauth2", securityScheme); return(secDefs); }
public void UseOAuth1(string authorizationUri, string requestTokenUri, string tokenCredentialsUri, SecuritySchemeDescriptor securitySchemeDescriptor) { securityType = "oauth_1_0"; var securitySettings = new SecuritySettings { AuthorizationUri = authorizationUri, RequestTokenUri = requestTokenUri, TokenCredentialsUri = tokenCredentialsUri }; securityScheme = new SecurityScheme { DescribedBy = securitySchemeDescriptor, Settings = securitySettings, Type = new Dictionary <string, IDictionary <string, string> > { { "OAuth 1.0", null } } }; }
public static SecurityRequirement LoadSecurityRequirement(ParseNode node) { var mapNode = node.CheckMapNode("security"); var obj = new SecurityRequirement(); foreach (var property in mapNode) { var scheme = SecurityScheme.LoadByReference(new ValueNode(mapNode.Context, property.Name)); if (scheme != null) { obj.Schemes.Add(scheme, property.Value.CreateSimpleList <string>(n2 => n2.GetScalarValue())); } else { node.Context.ParseErrors.Add(new OpenApiError(node.Context.GetLocation(), $"Scheme {property.Name} is not found")); } } return(obj); }
public void UseOAuth2(string authorizationUri, string accessTokenUri, IEnumerable <string> authorizationGrants, IEnumerable <string> scopes, SecuritySchemeDescriptor securitySchemeDescriptor) { securityType = "oauth_2_0"; var securitySettings = new SecuritySettings { AuthorizationUri = authorizationUri, AccessTokenUri = accessTokenUri, AuthorizationGrants = authorizationGrants, Scopes = scopes }; securityScheme = new SecurityScheme { DescribedBy = securitySchemeDescriptor, Settings = securitySettings, Type = new Dictionary <string, IDictionary <string, string> > { { "OAuth 2.0", null } } }; }
private static SecurityScheme ParseSecurityScheme(JsonProperty definition) { SecurityScheme scheme = new SecurityScheme() { Name = definition.Name }; foreach (JsonProperty property in definition.Value.EnumerateObject()) { if (property.Name == IanvsMeta.E_CONFIG_SEC_SCHEME_TYPE) { scheme.Type = property.Value.GetString(); } if (property.Name == IanvsMeta.E_CONFIG_SEC_SCHEME_IN) { scheme.In = property.Value.GetString(); } if (property.Name == IanvsMeta.E_CONFIG_SEC_SCHEME_BEARER_FORMAT) { scheme.BearerFormat = property.Value.GetString(); } if (property.Name == IanvsMeta.E_CONFIG_SEC_SCHEME_OPEN_ID_CONNECT_URL) { scheme.OpenIdConnectUrl = property.Value.GetString(); } if (property.Name == IanvsMeta.E_CONFIG_SEC_SCHEME_ISSUER) { scheme.Issuer = property.Value.GetString(); } if (property.Name == IanvsMeta.E_CONFIG_SEC_SCHEME_AUDIENCES) { scheme.Audiences = new string[property.Value.GetArrayLength()]; for (int i = 0; i < scheme.Audiences.Length; i++) { scheme.Audiences[i] = property.Value[i].GetString(); } } } return(scheme); }
public static void WriteSecurityScheme(IParseNodeWriter writer, SecurityScheme securityScheme) { writer.WriteStartMap(); writer.WriteStringProperty("type", securityScheme.Type); switch (securityScheme.Type) { case "http": writer.WriteStringProperty("scheme", securityScheme.Scheme); writer.WriteStringProperty("bearerFormat", securityScheme.BearerFormat); break; case "oauth2": //writer.WriteStringProperty("scheme", this.Scheme); //TODO: case "apiKey": writer.WriteStringProperty("in", securityScheme.In); writer.WriteStringProperty("name", securityScheme.Name); break; } writer.WriteExtensions(securityScheme.Extensions); writer.WriteEndMap(); }
public void AddSecurityDefinition(string name, SecurityScheme securityScheme) { _swaggerGeneratorSettings.SecurityDefinitions.Add(name, securityScheme); }
/// <summary> /// Creates a new client security description /// </summary> public OAuthClientSecurityDescription(ICredentialProvider credentialProvider, SecurityScheme scheme, String realm) { this.CredentialProvider = credentialProvider; this.Mode = scheme; this.AuthRealm = realm; this.PreemptiveAuthentication = true; }
/// <summary> /// Create a new endpoint description /// </summary> public OAuthClientDescription(String endpoint, String realm, ICredentialProvider credentialProvider, SecurityScheme scheme) { this.Endpoint = new List <IRestClientEndpointDescription>() { new OAuthRestClientEndpointDescription(endpoint) }; this.Binding = new OAuthClientBindingDescription(new OAuthClientSecurityDescription(credentialProvider, scheme, realm)); }
public void AddSecurityDefinition(string name, SecurityScheme securityScheme) { _swaggerProviderOptions.SecurityDefinitions.Add(name, securityScheme); }
public ParametrizedSecurityScheme(string name, SecurityScheme securityScheme, Settings settings) { Name = name; SecurityScheme = securityScheme; Settings = settings; }