locked
ASP .Net Identity login *Authorization" RRS feed

  • Question

  • User-1437298086 posted

    hello,

    I have implemented Identity authication into my Web Application.

    Below is the login code..it all works fine..logs in etc and saves the User and roles into the DB tables it automatically creates. My Question is, how do I set up authorization on each page....I dont want pages to be accessible unless the user is logged in. I know how to use the IsInRole for access to certain controls on a page if the user is logged in but like I said, if the user is not logged in then I do not want them to be able to access certain pages. I am not using ASP.Net Core...I cant since the client does not have that installed on their server. I am using FrameWork 4.6. I know in Core you just put [Authorize] at the top of the form code etc.....

    Login Code (working)

    -----------------------

    protected void LogIn(object sender, EventArgs e)
    {
    if (IsValid)
    {
    // Validate the user password
    var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>();
    var signinManager = Context.GetOwinContext().GetUserManager<ApplicationSignInManager>();

    // This doen't count login failures towards account lockout
    // To enable password failures to trigger lockout, change to shouldLockout: true
    var result = signinManager.PasswordSignIn(Email.Text, Password.Text, RememberMe.Checked, shouldLockout: false);

    switch (result)
    {
    case SignInStatus.Success:
    IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);
    break;
    case SignInStatus.LockedOut:
    Response.Redirect("/Account/Lockout");
    break;
    case SignInStatus.RequiresVerification:
    Response.Redirect(String.Format("/Account/TwoFactorAuthenticationSignIn?ReturnUrl={0}&RememberMe={1}",
    Request.QueryString["ReturnUrl"],
    RememberMe.Checked),
    true);
    break;
    case SignInStatus.Failure:
    default:
    FailureText.Text = "Invalid login attempt";
    ErrorMessage.Visible = true;
    break;
    }
    }
    }

    Partial ASPX page that I only want a logged in user to be able to access

    ----------------------------------------------

    <%@ Page Title="TCN IMS" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="TCN_IMS._Default" %>

    <asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
    <div class="hometitle">
    Welcome to the TCN Invoicing Management System<br />

    Select an application below
    </div>
    <br />

    <hr />
    <table border="0" style="width:100%">
    <tr>
    <td>
    <div class="HomeGroupContainer">
    <div id="HeaderUsage" class="grad4 bold">
    <span id="HeaderUsageName" class="homeOptionHeaders">TCN Usage</span>
    </div>
    <br />
    <asp:Button ID="btnHomePage" runat="server" Text="View Usage" class="homeButton" OnClick="btnTCNUsage"/>
    </div>
    </td>
    <td>
    <div class="HomeGroupContainer">
    <div id="HeaderProjections" class="grad4 bold">
    <span id="HeaderProjectionsName" class="homeOptionHeaders">Projections</span>
    </div>
    <br />
    <asp:Button ID="btnProjectionsPage" runat="server" Text="View Projections" class="homeButton" OnClick="btnProjections" />
    </div>
    </td>

    Monday, January 27, 2020 10:14 PM

All replies

  • User-719153870 posted

    Hi grjoseph,

    I dont want pages to be accessible unless the user is logged in.

    Actually this can be done by the User.Identity.IsAuthenticated, please follow the doc Adding ASP.NET Identity to an Empty or Existing Web Forms Project.

    Also, please check below demo:

    Index.aspx:

    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
    </head>
    <body>
        <form id="form1" runat="server">
            <div>
                <asp:Button runat="server" OnClick="SignOut" Text="Log out" />
            </div>
        </form>
    </body>
    </html>

    Index.cs:

    using Microsoft.AspNet.Identity;
    using System;
    using System.Web;
    
    
            protected void Page_Load(object sender, EventArgs e)
            {
                if (!IsPostBack)
                {
                    if (User.Identity.IsAuthenticated)
                    {
                        string str = string.Format("Hello {0}!!", User.Identity.GetUserName());
                        Response.Write(str);
                    }
                    else
                    {
                        Response.Redirect("~/Login.aspx");
                    }
                }
            }
    
            protected void SignOut(object sender, EventArgs e)
            {
                var authenticationManager = HttpContext.Current.GetOwinContext().Authentication;
                authenticationManager.SignOut();
                Response.Redirect("~/Login.aspx");
            }

    The Login and Register code you can find in the above doc.

    Below is the result of this demo:

    Hope this could help.

    Best Regard,

    Yang Shen

    Tuesday, January 28, 2020 5:06 AM
  • User-1437298086 posted

    thank you very much.....that is what I was looking for and did see that before I got your response.

    I am having another issue though but it does not happen on my laptop (dev env). when I copy the code over to the customer site with their own DB..I get a 

    Could not find stored procedure 'dbo.aspnet_CheckSchemaVersion'.

    Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

    Exception Details: System.Data.SqlClient.SqlException: Could not find stored procedure 'dbo.aspnet_CheckSchemaVersion'.

    I have no clue as to why. this error only happens when I am doing the checks in the code for the Authenticated and isinrole etc......again, this all works fine locally but not on the customer site. I do not really have much access to their DB either.

    <% if (Context.User.Identity.IsAuthenticated && (Context.User.IsInRole("Admin") || Context.User.IsInRole("Manager") || Context.User.IsInRole("User"))) {%>

    I noticed that the application automatically creates the ASPnet tables required for using the ASP.net identity login etc and it created those in the Table which my connection string referenced so all that works fine and it also automatically created those tables on the Client side Database.

    any thoughts here?

    also I noticed in my dev environment i did not require the <add name="LocalSqlServer" connectionString in my web.config but for some reason I require it on the Client web server..I Added it there and set the connection string to the same one that the application uses and it got rid of that error at least.

    thanks,

    Gerard

    Tuesday, January 28, 2020 7:51 PM
  • User-719153870 posted

    Hi grjoseph,

    Could not find stored procedure 'dbo.aspnet_CheckSchemaVersion'.

    This seems a common issue that many people met, you can refer to Could not find stored procedure 'dbo.aspnet_CheckSchemaVersion' see if we can solve the problem.

    In the above thread, it says "This error mostly occurs when you didn't enabled Roles in your asp.net mvc project At starting before aspnet identity table automatically created.".

    The solution is to simply run 'aspnet_regsql.exe' executable file which you can find by pressing Windows Key + r and put below command in that %windir%\Microsoft.NET\Framework\v4.0.30319 and Hit enter then find 'aspnet_regsql.exe' file.

    Hope this could help.

    Best Regard,

    Yang Shen

    Wednesday, January 29, 2020 1:23 AM