При проверке подлинности отказано в отображении внутри iframe с приложением MVC

Я создал приложение MVC, и на домашней странице у меня есть отчет панели мониторинга Power BI, поэтому я настроил конфигурацию Power BI и Azure AD в действии индекса, после вызова действия индекса оно проверит аутентификацию и перенаправит на перенаправление. Метод действия. В этом методе проверка подлинности была проверена, вызывается метод действия Power BI и отображается отчет.

Отчет на странице работает нормально, но если для него установлено значение Iframe, он не работает и показывает ошибку, указанную ниже.

Действие индексирования домашней страницы:

public ActionResult Index()
{
    var @params = new NameValueCollection
    {      
        //Azure AD will return an authorization code. 
        //See the Redirect class to see how "code" is used to AcquireTokenByAuthorizationCode
        {"response_type", "code"},
        //Client ID is used by the application to identify themselves to the users that they are requesting permissions from. 
        //You get the client id when you register your Azure app.
        {"resource", "https://analysis.windows.net/powerbi/api"},
        {"redirect_uri", "xxxx/home/Redirect."}
    };

    //Create sign-in query string
    var queryString = HttpUtility.ParseQueryString(string.Empty);
    queryString.Add(@params);

    string authorityUri = "https://login.windows.net/common/oauth2/authorize/";
    var authUri = String.Format("{0}?{1}", authorityUri, queryString);
    ViewBag.authUri = authUri;

    return View();
}

Метод действия переадресации:

public async Task<ActionResult> Redirect()
{
    string code = Request.Params["code"];

    if (code != null)  
    {
        AuthenticationContext AC = new AuthenticationContext("https://login.windows.net/common/oauth2/authorize", TC);
        ClientCredential cc = new ClientCredential("xxxxx", "xxxxxxx");

        AuthenticationResult AR = await AC.AcquireTokenByAuthorizationCodeAsync(code, new Uri("http://localhost:43333/home/redirect"), cc);

        //Set Session "authResult" index string to the AuthenticationResult
        Session["authResult"] = AR;
    } else {
        //Remove Session "authResult"
        Session["authResult"] = null;
    }

    return RedirectToAction("POWERBI", "Home");
}

Действие Power BI:

public async Task<ActionResult> POWERBI()
{
    AuthenticationResult authResult;
    authResult = (AuthenticationResult)Session["authResult"];
    var token = authResult.AccessToken;
    ViewBag.Token = token;
    var tokenCredentials = new TokenCredentials(token, "Bearer");

    // Create a Power BI Client object. It will be used to call Power BI APIs.
    using (var client = new PowerBIClient(new Uri(ApiUrl), tokenCredentials))
    {
        // Get a list of dashboards.
        var dashboards = await client.Dashboards.GetDashboardsInGroupAsync(GroupId);

        // Get the first report in the group.
        var dashboard = dashboards.Value.FirstOrDefault();
        //var dashboard = dashboards.Value.Where(w => w.Id == "DashboardId");

        if (dashboard == null)
        {
            return View(new EmbedConfig()
            {
                ErrorMessage = ""
            });
        }

        // Generate Embed Token.
        var generateTokenRequestParameters = new GenerateTokenRequest(accessLevel: "view");
        var tokenResponse = await client.Dashboards.GenerateTokenInGroupAsync(GroupId, dashboard.Id, generateTokenRequestParameters);

        if (tokenResponse == null)
        {
            return View(new EmbedConfig()
            {
                ErrorMessage = "."
            });
        }

        // Generate Embed Configuration.
        var embedConfig = new EmbedConfig()
        {
            EmbedToken = tokenResponse,
            EmbedUrl = dashboard.EmbedUrl,
            Id = dashboard.Id
        };

        return View(embedConfig);
    }   
}

На домашней странице внутри iframe:

<iframe src="@Url.Action("Index", "Home")" class="col-lg-12 col-md-12 col-sm-12" height="450">  </iframe>

ПРИМЕЧАНИЕ. - Функция отлично работает без iframe. - проблема при отображении отчета в Iframe.

Ошибка:

Отказался отображать URL-адрес в iframe, потому что он устанавливает параметры X-frame-options-to deny

error


person Mohamed Sahir    schedule 17.03.2018    source источник
comment
Он перенаправляет вас на вход внутри iframe. Но Azure AD не позволяет встраивать свою страницу входа. Вам нужно будет сделать это по-другому.   -  person juunas    schedule 17.03.2018
comment
@ да то же самое, можете ли вы сказать лучший подход к решению этой проблемы.   -  person Mohamed Sahir    schedule 17.03.2018
comment
Если у пользователя есть активный сеанс с вашим приложением и у него уже есть необходимый токен доступа, вы можете встроить его после этого. Но если пользователю требуется аутентификация, вы не можете ее встроить.   -  person juunas    schedule 17.03.2018


Ответы (1)


Сообщение об ошибке означает, что <iframe src>, который вы пытаетесь добавить на свой сайт, не позволяет разместить его в iframe. Он отправляет заголовок ответа:

X-Frame-Options: DENY

И браузер блокирует кадрирование. Хост-страница делает это для предотвращения атак с использованием кросс-фреймовых сценариев.

person Joe Wilson    schedule 17.03.2018