Frage

We have a public SharePoint 2013 Website and wanted to implement a custom form where anonymous users can contact us. We implemented a custom Visual WebPart and work when logged on the site but anonymous user was unable to submit this form and asks for credentials. If not logged in, the error 401 UNAUTHORIZED is observed

My ascx code:

<asp:LinkButton Text="" ID="txtEnviar" runat="server" CssClass="form--submit [ bt bt--bkg-transparent bt--submit ]" OnClick="txtEnviar_Click">
<span>
    <asp:Literal Text="Enviar" ID="ltrEnviar" runat="server" />
    <svg class="bt__arrow__svg" width="10px" height="14px" viewBox="0 0 10 14" xml:space="preserve">
        <polyline class="bt__arrow__path" fill="none" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" points="1.3,1.3 8.7,7 1.3,12.7" />
    </svg>
</span>

My code behind:

protected void txtEnviar_Click(object sender, EventArgs e)
{
SPSite site = SPContext.Current.Site;
using (SPWeb oWeb = site.RootWeb)
{
    SPList oList = oWeb.Lists["Email - Fale Conosco"];
    oWeb.AllowUnsafeUpdates = true;
    SPListItem oSPListItem = oList.Items.Add();
    oSPListItem["Title"] = txtNome.Text;
    oSPListItem["E-mail"] = txtEmail.Text;
    oSPListItem["Telefone"] = TextBox1.Text;
    oSPListItem["Mensagem"] = txtMensagens.Text;
    oSPListItem["Empresa"] = ddlEmpresa.Text;

    oSPListItem.Update();
    oWeb.AllowUnsafeUpdates = false;
}...
}
War es hilfreich?

Lösung

Your code behind is running as the current user. Since anonymous users do not have permission to add items to your list you get access denied.

The solution to this is generally to use SPSecurity.RunWithElevatedPrivileges, this will run the small block of code as the web app account which will generally have the correct permissions to add items to a list.

protected void txtEnviar_Click(object sender, EventArgs e)
{
    var id = SPContext.Current.Site.ID;

    SPSecurity.RunWithElevatedPrivileges(delegate()
    {
        using(SPSite site = new SPSite(id)
        {
            using (SPWeb oWeb = site.RootWeb)
            {
                SPList oList = oWeb.Lists["Email - Fale Conosco"];

                oWeb.AllowUnsafeUpdates = true;

                SPListItem oSPListItem = oList.Items.Add();
                oSPListItem["Title"] = txtNome.Text;
                oSPListItem["E-mail"] = txtEmail.Text;
                oSPListItem["Telefone"] = TextBox1.Text;
                oSPListItem["Mensagem"] = txtMensagens.Text;
                oSPListItem["Empresa"] = ddlEmpresa.Text;

                oSPListItem.Update();
                oWeb.AllowUnsafeUpdates = false;
            }
        }
    }
}

Since you are running code with more permissions than the anonymous user normally has be sure to double check that there are no unintended consequences.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit sharepoint.stackexchange
scroll top