Open Closed

missing antiforgery token on swagger abp9 #8335


User avatar
0
rcalv002 created
  • Template: app
  • Abp version: 9.0.0
  • Created ABP Studio Version: 0.9.11
  • Tiered: No
  • UI Framework: blazor-server
  • Theme: leptonx
  • Theme Style: system
  • Database Provider: ef
  • Database Management System: sqlserver
  • Separate Tenant Schema: Yes
  • Mobile Framework: maui
  • Public Website: Yes
  • Optional Modules:
    • GDPR
    • TextTemplateManagement
    • LanguageManagement
    • AuditLogging
    • SaaS
    • OpenIddictAdmin
  • Steps to reproduce the issue:

generate new app solution with abp studio Add a method to an appservice Execute method via swagger Receive antiforgery token error.

2024-11-22 11:36:09.728 -07:00 [WRN] The required antiforgery header value "RequestVerificationToken" is not present.
2024-11-22 11:36:09.729 -07:00 [INF] Authorization failed for the request at filter 'Volo.Abp.AspNetCore.Mvc.AntiForgery.AbpAutoValidateAntiforgeryTokenAuthorizationFilter'.
2024-11-22 11:36:09.730 -07:00 [INF] Executing StatusCodeResult, setting HTTP status code 400

Was this broken again with the move to 9?

similar to old post where this was already fixed in v4 https://abp.io/support/questions/554/REST-API-Antiforgery-Cookie-Error-After-POST-apiLogin---POST-apimyentity-Call-Sequence


5 Answer(s)
  • User Avatar
    0
    liangshiwei created
    Support Team Fullstack Developer

    We will fix the problem.

    https://github.com/abpframework/abp/issues/21443

    you can try

    add index.js to wwwroot/swagger/ui

    /* Source: https://gist.github.com/lamberta/3768814
     * Parse a string function definition and return a function object. Does not use eval.
     * @param {string} str
     * @return {function}
     *
     * Example:
     *  var f = function (x, y) { return x * y; };
     *  var g = parseFunction(f.toString());
     *  g(33, 3); //=> 99
     */
    function parseFunction(str) {
        if (!str) return void (0);
    
        var fn_body_idx = str.indexOf('{'),
            fn_body = str.substring(fn_body_idx + 1, str.lastIndexOf('}')),
            fn_declare = str.substring(0, fn_body_idx),
            fn_params = fn_declare.substring(fn_declare.indexOf('(') + 1, fn_declare.lastIndexOf(')')),
            args = fn_params.split(',');
    
        args.push(fn_body);
    
        function Fn() {
            return Function.apply(this, args);
        }
    
        Fn.prototype = Function.prototype;
    
        return new Fn();
    }
    
    window.onload = function () {
        var configObject = JSON.parse('{"urls":[{"url":"/swagger/v1/swagger.json","name":"Qa API"}],"deepLinking":false,"persistAuthorization":false,"displayOperationId":false,"defaultModelsExpandDepth":1,"defaultModelExpandDepth":1,"defaultModelRendering":"example","displayRequestDuration":false,"docExpansion":"list","showExtensions":false,"showCommonExtensions":false,"supportedSubmitMethods":["get","put","post","delete","options","head","patch","trace"],"tryItOutEnabled":false,"oidcSupportedFlows":["authorization_code"],"oidcSupportedScopes":["Qa"],"oidcDiscoveryEndpoint":"https://localhost:44303/.well-known/openid-configuration"}');
        var oauthConfigObject = JSON.parse('{"clientId":"Qa_Swagger","scopeSeparator":" ","scopes":[],"useBasicAuthenticationWithAccessCodeGrant":false,"usePkceWithAuthorizationCodeGrant":false}');
    
        // Workaround for https://github.com/swagger-api/swagger-ui/issues/5945
        configObject.urls.forEach(function (item) {
            if (item.url.startsWith("http") || item.url.startsWith("/")) return;
            item.url = window.location.href.replace("index.html", item.url).split('#')[0];
        });
    
        // If validatorUrl is not explicitly provided, disable the feature by setting to null
        if (!configObject.hasOwnProperty("validatorUrl"))
            configObject.validatorUrl = null
    
        // If oauth2RedirectUrl isn't specified, use the built-in default
        if (!configObject.hasOwnProperty("oauth2RedirectUrl"))
            configObject.oauth2RedirectUrl = (new URL("oauth2-redirect.html", window.location.href)).href;
    
        // Apply mandatory parameters
        configObject.dom_id = "#swagger-ui";
        configObject.presets = [SwaggerUIBundle.presets.apis, SwaggerUIStandalonePreset];
        configObject.layout = "StandaloneLayout";
    
        // Parse and add interceptor functions
        var interceptors = JSON.parse('{}');
        if (interceptors.RequestInterceptorFunction)
            configObject.requestInterceptor = parseFunction(interceptors.RequestInterceptorFunction);
        if (interceptors.ResponseInterceptorFunction)
            configObject.responseInterceptor = parseFunction(interceptors.ResponseInterceptorFunction);
    
        if (configObject.plugins) {
            configObject.plugins = configObject.plugins.map(eval);
        }
    
        // Begin Swagger UI call region
    
        const ui = abp.SwaggerUIBundle(configObject);
    
        ui.initOAuth(oauthConfigObject);
    
        // End Swagger UI call region
    
        window.ui = ui
    }
    
    app.UseSwagger();
    var resolver = app.ApplicationServices.GetService<ISwaggerHtmlResolver>();
    
     app.UseSwaggerUI(options =>
    {
        options.InjectJavascript("ui/abp.js");
        
        options.InjectJavascript("ui/abp.swagger.js");
        options.IndexStream = () => resolver?.Resolver();
        options.SwaggerEndpoint("/swagger/v1/swagger.json", "Qa API");
    
        var configuration = context.ServiceProvider.GetRequiredService<IConfiguration>();
        options.OAuthClientId(configuration["AuthServer:SwaggerClientId"]);
    });
    
  • User Avatar
    0
    russell.thompson created

    @liangshiwei Will this fix also work if we are still using abp 8.3.X but need to update our Swashbuckle.AspNetCore to 6.8.1?

  • User Avatar
    0
    liangshiwei created
    Support Team Fullstack Developer

    Hi,

    Will this fix also work if we are still using abp 8.3.X but need to update our Swashbuckle.AspNetCore to 6.8.1?

    Nope.

    The problem will fixed in the 9.0.x version.

  • User Avatar
    0
    Baytech created

    Hi, when will this be fixed? It is getting a little annoying that I have to add custom ABP code to fix ABP bugs whenever we upgrade our ABP version. Upgrading an ABP version and suddenly not being able to use Swagger is not ideal... feels like something that should have been caught before 9 went out.

  • User Avatar
    0
    liangshiwei created
    Support Team Fullstack Developer

    Hi,

    It will fixed in the 9.0.2 version. We will ensure that such a problem does not occur again.

Made with ❤️ on ABP v9.1.0-preview. Updated on December 13, 2024, 06:09