Simple Membership Admin Accout - c#

I am working on my first ASP.Net MVC 4 application and now stuck with one simple use case.
I need to authenticate one single user (Admin) so that he/she can log in to admin area to perform certain tasks. Though the ASP.Net internet project template has Account controller using simple membership but that seems to have much more than what I actually need. For instance, I don't really need the user registration functionality and user roles. My requirements are fairly simple, just to store one single user in database, give him the options to update his info like password, email etc and grant him access to admin area (admin controller and actions).
What I can't figure out is
Are simple membership or other asp.net membership provider my only options for this simple scenario.
If not what other option do I have in order to use [Authorize] to secure admin actions

You can build a custom method to grab the user and their stored role, then evaluate it in your controller. So, for instance:
public ActionResult GetAdminPage()
{
var loggedInUserName = HttpContext.User.Identity.Name;
var user = somesortofproviderlookupmethod(loggedInUserName);
// Assume user is a bool and is true
if (user)
{
return view("AdminPage");
}
}
The only thing I'm not sure of is whether or not HttpContext.User requires membership. Perhaps someone can shed some light. If so, perhaps you could send the username from the view, but then of course you're trusting the client. So how you are doing user authentication would change this answer somewhat.
Personally, I like membership. It's clean, easy, fast and can be scaled nicely if you end up having additional requirements. Doing something like this would be even easier with membership, since then you can actually use Roles.GetRolesForUser(); and only return the admin view if they contain the role you are looking for.

Related

RESTful API Design - same path diffrent roles

I´m currently working on a RESTful API, which has to give access to two diffrent Roles: Admin and User. (I'm wokring with Azure AD App Roles)
My Problem is that I don't understand how I can design the controller logic.
For example I want both (admin and user) to access the endpoint /books, but the admin is allowed to see all books and the user is only allowed to see his books.
What is the best practice to give both the allowed access? I thought of splitting it into two enpoints like this:
/books -> with annotation [Authorize(Roles="Admin")]
/user/{id}/books -> with annotation [Authorize(Roles="User")]
Thanks for helping!
Best regards
I think this sample may be of some help. And if you need sample written by other languages, you can refer to this document to find a suitable one.
And on your case, I think the most important thing is to find out the way to execute the right query and make the query result return to correct user.
So if you set a specific url for each user(I don't think this a good idea to expose user id in the request link), or you hide the user role/id into the token which contained in request header, you all need to write logic code to check which query method need to run. For example, hit domain:port/books with an access token, then your filter catch this request and decode the token to know the user id and user role, and maybe can save them in the session, then your controller may check the value stored in session and choose a right query to get the books information.

User only can register after Admin approval

I am setting up a new mvc5 project in c# in which I am using Identity Framework and Open ID. which means a new user can register via a third party i.e. Google,Facebook,Microsoft.
So this part is done. Now I want to restrict users, means when a user will be trying to register an approval will be sent to the Admin. If the Admin accepts only then the user can register. Is there any way to do that?
Check out a combination of Authorization Policies/ Role Based Security. When any user registers via a third party, the code which handles the registration does all the relevant record keeping for the new user, and gives them a role of, say, "Unapproved User". You can create as set of Controllers/ Views etc which that user can view (perhaps a profile page, landing page with generic information, or maybe just a disclaimer page which tells them they need to wait to be approved).
From there when the Admin approves the user, the code which handles the approval changes the role to "Approved User". This then allows them to access the full site.
I can't tell if you are using classic Asp.Net with mvc 5 or Asp.Net core but the concepts are similar (except for the auth policy stuff) in both.
Essentially you decorate the controllers/ actions you want protected with:
[Authorize("ApprovedUser")]
public class MyProtectedController
{
}
[Authorize("UnapprovedUser")]
public class MyUnprotectedController
{
}
For more info:
https://learn.microsoft.com/en-us/aspnet/core/security/authorization/roles?view=aspnetcore-2.2

Is it valid enough to use sessions to maintain logged in user data in MVC Application

I am working on ASP.net MVC web Application. Here, in this i am implementing windows authentication. I have made necessary configurations in the web.config file to make it work
By using windows authentication, i was able to get the logged in user name . By using it as parameter, i am querying database to get the role for logged in user.
In my application, i have two roles. Admin and Normal User. I need to display some of the pages content based on the role of user logged in.
Can i use sessions in MVC to carry this information in every page and display the content
For example: in Global.asax
protected void Session_Start(object sender, EventArgs e)
{
Query database....
if( role="Admin")
{
Session["UserType"]="Adimn";
}
else
{
Session["UserType"]="NormalUser";
}
}
like this.. Then in each page, i will check this role and based on that i will hide/show some of the functionalities to the user
Is this the right approach to do this. IF not, what are the alternative ways of doing it.
Please suggest..
You should use HttpContext.User.Identity to get current user. You can get user name and user roles:
var uName = HttpContext.User.Identity.Name;
var isAdmin = HttpContext.User.IsInRole("Admin");
As any caching approach it have positive and negative sides. Your call if you are ok with solution. Some pro/cons below.
Pros:
less requests to DB
faster pages (again you need to just load session state)
Cons:
cache invalidation is complex problem: i.e. you may not know if particular user is no longer admin
leaking session due to bugs in your site allows elevation of privileges (just need to have session ID, not need for admin credentials).

Custom User and Roles with ASP.NET MVC3

I have a ASP.NET MVC site with a CAS server set up as the authentication type. I also have a separate database with a Users table and a Roles table (with a User being related to one or more roles). A User is only able to log into the system if the Username is both in the User table and on the CAS system. I have this solution working.
My problem is i now need some form of trigger on User.IsAuthenticated so i can track the current User (from my database), without the possibility that i am trying to allow tracking of a User that has logged out. What I've been thinking is i need to add the User to the HttpContext but i am not sure how to trigger the clearing of the User if the CAS session times out or if the User Logs out.
I also wish to have some functionality such as User.IsInRole (again using my database, not ASP.NET) but am not sure how to go about implementing this. I suppose if i can successfully add the User to the HttpContext then a IsInRole method would simply be a User.Roles.Contains(string role) method but how can that then be used if i wish, for example, to use a method with the DataAnnotation [Authorize(role = "ExampleRole")].
I have looked at questions such as How do I create a custom membership provider for ASP.NET MVC 2? but this doesn't work for me (possibly to do with me using the CAS authentication?)
Any guidance or background reading would be appreciated as i'm really not sure where i should even start. I have read up on GenericPrinciple, IPrinciple and IIdentity but I'm struggling to see how i can apply them to my current project.
Ended up with a custom Authorise Attribute that uses the CAS logon to check the user exists in my database. It also checks the roles of that user. I also used a static class to save the current user in the session with a logout method that abandons the session when the user logs out.
I have kind of a two parter for you. This link does a really good job of explaining how to replace the HttpContext User with your own object: http://bradygaster.com/custom-authentication-with-mvc-3.0
His approach uses MVC filters, but you can also catch the Authentication event in the Global.asax file. Using the forms system with your own implementation can be trivial or not depending on what you're doing, but it boils down to calling FormsAuthentication.SetAuthCookie and .SignOut, amidst your own logic.
public static void FormsLogin(this User user, bool persist)
{
FormsAuthentication.SetAuthCookie(user.DisplayName, persist);
user.AddHistory("Login event.", HistoryType.Login, "SYSTEM");
Users.OnUserLogin(user);
SetLastActivity(user);
}
public static void FormsLogout(this User user)
{
FormsAuthentication.SignOut();
}
Lastly, once you've got the login stuff working out, you can use your own more complex permission system by making a custom Auth Attribute. I remember piecing this together from some other answers and articles but I can't seem to find the sources at the moment, I will try and edit with sources for credit where it's due, if I find them. For now, all I can offer is this gist which offers up one of the attributes I use: https://gist.github.com/1959509
Keep in mind the only really relevant part there is the override of OnAuthorization, which does the actual work.

Asp.net Login - Working with user data

I'm making a simple page and i need a login interface for users.
I want users to login to the page and when he is logged in he gets alot of data from the database that is signed to him alone. I did this before using very simple datatable holding the username, crypted password and the uid. When the user logged in the site i set the uid into a session so i could use it when i was selecting from the database..
This is probably not a safe way....easy to crack ?
Better way would be using the asp.net login id...?
What is the best way to do this, should i have all the user info in the ASPNETDB.MDF, and does that database work when i deploy the site on a server ?
Can i use ASP.NET Configuration when i have deployed ?
[Edit]
How can i use the asp.net login to get the userid of the current logged user so i can do sql querys for him ?
I think you should read more on "ASP.NET authentication" - regarding how to implement user login/logout/get userid etc. And on "ASP.NET authorization" - regarding security and access and come back with certain questions. There's standard mechanism for this.
Start with MSDN:
http://msdn.microsoft.com/en-us/library/eeyk640h.aspx
http://msdn.microsoft.com/en-us/library/wce3kxhd.aspx
The ASP.NET membership provider will likely be your best approach as it handles all of the basic plumbing which you need. The tables are quick to setup with the ASP.NET SQL Server Setup Wizard (C:\Windows\Microsoft.NET\Framework\v2.0.50727\Aspnet_regsql.exe) and the combination of the Configuration pages and out of the box login controls will get you up and running quickly. I would recommend going down this path.
Regarding one of your specific questions, the logged in user's Id is stored in the ProviderUserKey. This is the value which maps to the UserId in the membership tables like aspnet_Users and others. Here's how you get the value:
using System.Web.Security;
//ProviderUserKey is an object.
//You will likely want to convert to string or Guid
MembershipUser user = Membership.GetUser();
Object userId = user.ProviderUserKey;
There really is nothing wrong with the way you are doing it, although there are easier methods to do it.
If you are creating a login hash, and storing it in session, the users have no access to that data.
When you create a session state, all that gets sent down in a cookie is a GUID that refers to their own session, and not any of the actual data. Because of this, you can generally assume the data is protected and users can't get access to anyone else's data.

Categories