Answered by:
Identity 2: Redirect to login page if user not logged in and enters URL directly

Question
-
User811468932 posted
I have a web site using Identity 2. I use vb.net
I am trying to stop people entering a URL on my web site and being directed to login page if not logged in. Currently, if you enter the URL the page deplys. In the old membership approach this could be done in web.config but that does not work with Identity.
I have read a few posts (mostly MVC) that talk about this but I cannot work out how to do it.
I believe I need to modify the code in Startup.Auth? I currently have basically the default start up
Public Sub ConfigureAuth(app As IAppBuilder) 'Configure the db context, user manager and signin manager to use a single instance per request app.CreatePerOwinContext(AddressOf ApplicationDbContext.Create) app.CreatePerOwinContext(Of ApplicationUserManager)(AddressOf ApplicationUserManager.Create) app.CreatePerOwinContext(Of ApplicationSignInManager)(AddressOf ApplicationSignInManager.Create) ' Enable the application to use a cookie to store information for the signed in user app.UseCookieAuthentication(New CookieAuthenticationOptions() With { .AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie, .Provider = New CookieAuthenticationProvider() With { .OnValidateIdentity = SecurityStampValidator.OnValidateIdentity(Of ApplicationUserManager, ApplicationRoleManager)( validateInterval:=TimeSpan.FromMinutes(120), regenerateIdentity:=Function(manager, user) user.GenerateUserIdentityAsync(manager))}, .LoginPath = New PathString("/Account/Login")}) ' Use a cookie to temporarily store information about a user logging in with a third party login provider app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie) app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5)) app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie) End Sub
Appreciate any help
Thank you
Thursday, May 17, 2018 4:09 AM
Answers
-
User283571144 posted
Hi michael_y,
As far as I know, the identity is not as same as form authentication.
We couldn't enable the form authentication to login user.
The identity user token is not as same as form authentication user ticket.
They are different things.
If you want to enable auto redirect unauthorized user to login page.
I suggest you could write logic in the master page's page load event to check the user is unauthorized.
More details, you could refer to below codes:
Master page:
In the master Page load event write this code, add a property named IsLoginRequired.
By using this property we could set the page is not required login by setting the IsLoginRequired to false.
Public m_bLoginRequired As Boolean = True Public Property IsLoginRequired As Boolean Get Return m_bLoginRequired End Get Set(ByVal value As Boolean) m_bLoginRequired = value End Set End Property
Then in Master page page load event we could check the user is login and the page require login.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load If IsLoginRequired = True Then If Not HttpContext.Current.User.Identity.IsAuthenticated Then Response.Redirect("/Account/Login.aspx") End If End If End Sub
Then in the login page:
We could modify the master page IsLoginRequired to false in Page_PreInit event:
Partial Public Class Login Inherits Page Protected Sub Page_PreInit(ByVal sender As Object, ByVal e As EventArgs) Handles Me.PreInit Dim masterpage As SiteMaster = CType((Page.Master), SiteMaster) masterpage.IsLoginRequired = False End Sub
Result:
Best Regards,
Brando
- Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
Friday, May 18, 2018 6:24 AM
All replies
-
User475983607 posted
Your question is not clear. The default behavior of ASP Identity using the "Individual Account" template in Visual Studio will redirect the browser to the login page if a secured resource is requested and the user is not authenticated.
Using the Web.Config to secure or allow anonymous access to folders has not changed.
Can you explain the problem you are trying to solve?
Thursday, May 17, 2018 11:05 AM -
User811468932 posted
Hi
Thanks for your prompt reply
I think I have confused myself. As the post title suggests I am trying to ensure that people can only see a web page if logged in. At the moment using a page URL will take you there logged in or not.
You say "The default behavior of ASP Identity using the "Individual Account" template in Visual Studio will redirect the browser to the login page if a secured resource is requested and the user is not authenticated." This is not happening
After reading numerous forum posts I came to the conclusion that denying login in web.config was no longer the approach. Looks like I got this wrong. So I added the following to the web.config
<authentication mode="Forms"> <forms loginUrl="/Account/Login.aspx" protection="All" path="/" timeout="180" name=".ASPXAUTH" defaultUrl="default.aspx" /> </authentication> <authorization> <deny users="?" /> </authorization>
However, I now get an error " the server is redirecting the request for this address in a way that will never complete." So far can't see the cause.
The error goes away when I remove deny users line.
Is this the correct approach?
Friday, May 18, 2018 1:29 AM -
User283571144 posted
Hi michael_y,
As far as I know, the identity is not as same as form authentication.
We couldn't enable the form authentication to login user.
The identity user token is not as same as form authentication user ticket.
They are different things.
If you want to enable auto redirect unauthorized user to login page.
I suggest you could write logic in the master page's page load event to check the user is unauthorized.
More details, you could refer to below codes:
Master page:
In the master Page load event write this code, add a property named IsLoginRequired.
By using this property we could set the page is not required login by setting the IsLoginRequired to false.
Public m_bLoginRequired As Boolean = True Public Property IsLoginRequired As Boolean Get Return m_bLoginRequired End Get Set(ByVal value As Boolean) m_bLoginRequired = value End Set End Property
Then in Master page page load event we could check the user is login and the page require login.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load If IsLoginRequired = True Then If Not HttpContext.Current.User.Identity.IsAuthenticated Then Response.Redirect("/Account/Login.aspx") End If End If End Sub
Then in the login page:
We could modify the master page IsLoginRequired to false in Page_PreInit event:
Partial Public Class Login Inherits Page Protected Sub Page_PreInit(ByVal sender As Object, ByVal e As EventArgs) Handles Me.PreInit Dim masterpage As SiteMaster = CType((Page.Master), SiteMaster) masterpage.IsLoginRequired = False End Sub
Result:
Best Regards,
Brando
- Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
Friday, May 18, 2018 6:24 AM -
User811468932 posted
Thanks so much Brando
Your explanation and the code you provided are excellent
I copied your code and it worked first time
I must admit that on the web how to determine how to do redirection is not very clear at all.
One forum will talk about Form authentication and the other will say implementing Identity "out of the box"
I had the standard Identity code but it required your logic to make it redirect
I hope your code helps others
Regards
Michael
Friday, May 18, 2018 7:56 AM