Using created Login Page for authentication in ASP.NET MVC 4 - asp.net-mvc-4

I want to use my own Login Page for authentication, but it is giving me this error
Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.
Requested URL: /Account/PasswordLock
Anyone knows why?Here is my code, I created a new page called PasswordLock.aspx with a login tool in it. everything works fine with the original Login form, but not mine own.
<authentication mode="Forms">
<forms loginUrl="~/Account/PasswordLock" timeout="2880" />
</authentication>
while this will work fine
<authentication mode="Forms">
<forms loginUrl="~/Account/Login" timeout="2880" />
</authentication>
Thanks

In ASP.NET MVC, your URLs don't map to files; they map to actions. So, having a file at ~/Accounts/PasswordLock.aspx doesn't help. What you need is a route for that URL. The routes are usually set up in a file called RouteConfig, under the App_Start folder, executed by the Application_Start() method in Global.asax. The usual default route looks like this:
routes.MapRoute(
name: "default",
routeTemplate: "{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional });
This means that a URL that goes www.example.com/Accounts/PasswordLock will map to a controller called AccountsController, and a method on that controller called PasswordLock. This method should return a View which by default will be called PasswordLock.cshtml. Note that the new Razor v2 view engine uses .cshtml files rather than .aspx.
This is all pretty fundamental to ASP.NET MVC programming; it sounds rather like you're jumping in blindly. I'd strongly advise reading the tutorials at www.asp.net/mvc, particularly the ones on controllers and routing.

Related

Regarding Authorize attribute usage in ASP.Net MVC 4

when we decorate any action with Authorize attribute then how MVC redirect to login form because my login controller name could be different and also view name also could be different. login view also could be stored in different folder instead of shared folder.
so tell me how MVC engine understand that it need to load login form when face Authorize attribute ?
how MVC engine would know where login form template is stored because it location could be different instead of shared folder?
how MVC engine would know what is login controller name if my login controller name is different ?
please discuss 3 points i asked here in details. thanks
The AuthorizeAttribute is a filter, which means that it can execute before the associated controller action. The AuthorizeAttribute performs its main work in the OnAuthorization method. If the user fails authentication, an HttpUnauthorizedResult action result is returned which produced an HTTP 401 status code. In previous versions of ASP.NET MVC the user redirected to the application login page defined in the application's web.config:
<authentication mode="Forms">
<forms loginUrl="~/Account/LogOn" timeout="2880" />
</authentication>
In ASP.NET MVC 5, the redirection process is handled by OWIN middleware components. It redirects unauthenticated requests to a LoginPath value, which
defaults to "/Account/Login":
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType =
DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login")
});

BetterCMS with MVC4 Simple membership provider

I've set up BetterCMS in my MVC4 app. and it seems like it's working except I can't figure out how to configure it to use Simple Membership Provider that comes with MVC4 internet app.
http://www.devbridge.com/articles/better-cms-for-developers
please help!. thanks
EDIT: I've created my MVC4 app using Internet Template which comes with Simple Membership Provider already configured and working. I would like to have those members I've "registered" as BetterCMS users.
If you want to use Better CMS, use BetterCms.Module.Users module from NuGet with it's role provider, membership provider and UI for managing users. How to setup users module, you can read in BetterCMS wiki pages on Github
But if you still wish to use Better CMS with Simple Membership Provider, follow steps below. That's what I've done and it works fine for me.
Create an MVC 4 solution and select Internet template
Run the application and create a user
Install BetterCMS by following steps, explained in Better CMS github wiki, section "Project Setup".
Do not forget to remove default routes registration (routes.MapRoute(name: "Default" ....) from RouteConfig class.
Register routes below in the RouteConfig class. After that MVC home page can be reached by URL /home/:
routes.MapRoute("mvc-account-controller", "account/{action}/{id}", new
{
area = string.Empty,
controller = "Account",
action = "Login",
id = UrlParameter.Optional
});
routes.MapRoute("mvc-home-controller", "home/{action}/{id}", new
{
area = string.Empty,
controller = "Home",
action = "Index",
id = UrlParameter.Optional
});
Add role provider and membership provider to web.config (solution found here):
<roleManager enabled="true" defaultProvider="simple">
<providers>
<clear/>
<add name="simple" type="WebMatrix.WebData.SimpleRoleProvider, WebMatrix.WebData"/>
</providers>
</roleManager>
<membership defaultProvider="simple">
<providers>
<clear/>
<add name="simple" type="WebMatrix.WebData.SimpleMembershipProvider, WebMatrix.WebData"/>
</providers>
</membership>
Add LazyInitializer to global.asax as explained here
Remove [InitializeSimpleMembership] attribute from AccountController, because database connection is already initialized. Also, SMP2.Filters.InitializeSimpleMembershipAttribute class can also be deleted.
Create an admin role and assign it for user (it can be done using ASP.NET Configuration or directly in the database). For example, create role with name "Role1".
There are two ways to set up administrator roles for the user (you can read more in the Better CMS Github Wiki, topic "CMS configuration"):
Set your created role as full access role (cms.config, security section's fullAccessRoles attribute set to fullAccessRoles="Role1" )
Add roles mappings in the cms.config's security section:
<customRoles>
<add permission="BcmsEditContent" roles="Role1" />
<add permission="BcmsPublishContent" roles="Role1" />
<add permission="BcmsDeleteContent" roles="Role1" />
<add permission="BcmsAdministration" roles="Role1" />
</customRoles>
Run application. Go to url /account/login and log-in using admininstrator account, which was created in the 2nd step. Then go back to any CMS page, for example, root page (/).
Here you go, you're connected as administrator and CMS sidebar is availabe for web site editing.

How to extend a user's session in MVC 4 forms authentication via AJAX

I'm using Forms Authentication for an internal company website. I authenticate users against the local Active Directory server.
I have my Web.config file set up as follows:
<authentication mode="Forms">
<forms name=".ADAuthCookie" loginUrl="~/Login" timeout="30" slidingExpiration="true" protection="All" defaultUrl="/" />
</authentication>
This works fine as long as a user moves to a new page, or refreshes the page they're on. However, much of my UI is based on javascript templating and AJAX, so it's quite possible for a user to be working on a page for longer than 30 minutes.
So, how do I query and/or extend how much time they have remaining in their session via an AJAX call? I don't need help with the AJAX call, just what I'd put in a controller (such as /user/keepalive)

Authentication causing duplicate page rendering

Let me try to explain this in english :).
I'm having trouble with the authentication in Mvc. I use my layout page to login and to show the other partial views with content.
I decorated the login methods with <AllowAnonymous()> _ to let people login into the page and in my webConfig i have the following entry:
<authentication mode="Forms">
<forms loginUrl="~/" timeout="2880" />
</authentication>
What's happening is when the session expires, the partial view renders the entire page again and i get the entire page twice (one inside the content).
Any help?
You may checkout the following article from Phil Haack which illustrates a nice technique allowing you to prevent the forms authentication module to automatically redirect to the LogOn page but return 401 status code. This could be done conditionally only for AJAX requests. And since the server now returns 401 status code you could detect it on your client side AJAX call and act accordingly.
Thks for the answer, but i solved my problem with the following post :
C# MVC: How to override configured authentication redirect?

Logging with asp membership from any page?

Is it possible?
It means i hope to create the widget to paste it at different pages on a site(or even in the master mage) to give users ability to quick login. Is it possible or all pages when login accessable have to be enumerated like this:
<authentication mode="Forms">
<forms loginUrl="~/Account/LogOn" timeout="2880" />
</authentication>
As long as the page allows anonymous access, I don't see why this would be a problem. Just put a username/password field on the page and use the API to log them in:
if (Membership.ValidateUser(username, password))
{
FormsAuthentication.SetAuthCookie(username, true / false);
}
EDIT: You probably want to SSL any page with a password field on it.