ASP.NET中的令牌授权

时间:2020-03-10 15:20:17

标签: c# asp.net api swagger swashbuckle

我正在通过Swagger记录我的应用程序的API,该应用程序通过会话令牌(即通过用户名和密码进行验证)进行工作,该令牌在一定时间内生成,从而使用户可以浏览网站。我需要的是大张旗鼓地捕获此会话令牌并将其自动放置在其余API方法的请求的标头中,到目前为止,我唯一能做的就是将令牌作为参数传递,但是手动进行。这个想法是使其自动化。我保留了目前携带的SwaggerConfig.cs的配置。

public class SwaggerConfig
{

    public static void Register()
    {

        var thisAssembly = typeof(SwaggerConfig).Assembly;
        GlobalConfiguration.Configuration
            // HABILITAMOS SWAGGER.
            .EnableSwagger(c =>
                {
                    var baseDirectory = AppDomain.CurrentDomain.BaseDirectory + @"\bin\";
                    var commentsFileName = Assembly.GetExecutingAssembly().GetName().Name + ".xml";
                    var commentsFile = Path.Combine(baseDirectory, commentsFileName);
                    c.SingleApiVersion("v1", "API");
                    c.OperationFilter<AddRequiredHeaderParameter>();
                    c.PrettyPrint();
                    c.ApiKey("apikey")
                        .Description("API Key Authentication")
                        .Name("Bearer")
                        .In("header");
                    c.IgnoreObsoleteActions();
                    c.IgnoreObsoleteProperties();
                    c.DescribeAllEnumsAsStrings();
             .EnableSwaggerUi(c =>
                {   c.DocumentTitle("Documentación API");
                      c.EnableApiKeySupport("apikey", "header");
                });
    }
}

反过来,添加一个类以根据需要在哪里创建应用程序来验证

public class AddRequiredHeaderParameter : IOperationFilter
{
    public void Apply(Swashbuckle.Swagger.Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
    {
        if (operation.parameters == null)
            operation.parameters = new List<Parameter>();

        operation.parameters.Add(new Parameter
        {
            name = "AuthorizedClient",
            @in = "header",
            type = "intenger",
            description = "Aplicacion",
            required = true,
            @default = axaxax
        });

        operation.parameters.Add(new Parameter
        {
            name = "ClientKey",
            @in = "header",
            type = "string",
            description = "Cliente",
            required = true,
            @default = "bxbxbx"
        });

        operation.parameters.Add(new Parameter
        {
            name = "Authorization",
            @in = "header",
            type = "apikey",
            description = "Token de sesión",
        });
    }
}

0 个答案:

没有答案