Create User Roles In Asp.net Web Application project - c#

I need guidance from all of you experts for a simple task.
i'm working on my final year project which is a web based application.
In this application i have to create several users which will do different taks for example accountant will manage fee and admin will manage teacher and student accounts and so on.
i'm working hard on this and I've learned simple authentication.
I'm able to authorize users based on their user names and allow them to access specific pages or specific folder having multiple pages.
I'm doing this by using form authentication.
but
now as i want to create user role and assign different roles to different users so that I don't have to add each and every user name in web config file.
please suggest me the easiest way to do this. is there any book, or article or youtube video from where i can learn it ?
I've searched stack overflow and msdn but i'm unable to understand.
I'm waiting for your suggestions,
thanks in advance.
I'm nor working in MVC.
I'm using .net 4.5, visual studio 2012 and sql server 2014

You can attach roles to your user in this way:
in globl.asax add the following event, read the roles to assign to the logged user, create a new GenericPincipal and assign it to the user.
protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
var app = (HttpApplication) sender;
var ctx = app.Context;
if (ctx.User != null)
{
//Read the roles from database for current user, create a new Principal, attach the principal to the user (im using EF)
using (var context = new BackendDbContext())
{
var user = context.Set<User>().Find(Convert.ToInt32(ctx.User.Identity.Name));
var identity = new GenericIdentity(user.UserId.ToString());
var principal = new GenericPrincipal(
identity,
new[] {user.UserRoleId.ToString()});
ctx.User = principal;
}
}
}

Related

Generating an Identity User with Roles (From Web API to MVC Application)

Currently developing a couple of applications (MVC and Web API) where my MVC application will send the request to the API to get authenticated and "login". I've got it working so that all my MVC application has to do is store the bearer token from the Web API and attach it anytime it needs to make a request for data.
At this point in the program we are looking to start working with Authorization and some security trimming to limit which users can make certain requests to the API and which users are able to see certain pages on the MVC application. In order to do this on both ends I need to get the Roles from my API and impersonate the Identity user on the MVC side since they are technically already logged in. My problem right now is probably kind of simple, but I can't figure out how to declare the Roles when I generate an identity user. Right now I just need a test case that we can explicitly declare and then I can grab it later once we start passing Roles from the API.
Any idea how to make a functioning example out of this with Roles?
private IdentityUser GenerateIdentityUser(string IdNum, string userN)
{
var newUser = new IdentityUser
{
Id = IdNum,
UserName = userN,
// Roles =
SecurityStamp = DateTime.Now.Ticks.ToString()
};
return newUser;
}
The Roles property in the IdentityUser has a private setter (see codeplex source code). The constructor for IdentityUser always creates an empty list of roles, so that it won't be null.
To set a role you'll need to add the following line after initializing your newUser object:
newUser.Roles.Add(new IdentityUserRole {UserId = newUser.Id, RoleId = "your role id"});

BOX: Add Collaboration to a folder using AppUser user token

I am building an integration between my organization back-end systems and BOX.
One of the scenarios is that when certain event is happening inside my organization there is a need to create a folder in BOX and add collaboration objects to that folder (connect groups to the folder).
I have no problem to create the folder but when trying to create the collaboration I am getting the following error:
Box.V2.Exceptions.BoxException: Bearer realm="Service", error="insufficient_scope", error_description="The request requires higher privileges than provided by the access token."
I am using BOX SDK for .Net to interact with BOX.
The application I created in BOX is assigned to use AppUser User Type and I provided all the scopes that BOX allows me (All scopes except "Manage enterprise" which is disabled).
The code that fails is (C#):
var privateKey = File.ReadAllText(Settings.JwtPrivateKeyFile);
var boxConfig = new BoxConfig(Settings.ClientID, Settings.ClientSecret, Settings.EnterpriseID, privateKey, Settings.JwtPrivateKeyPassword, Settings.JwtPublicKeyID);
var jwt = BoxJWTAuth(boxConfig);
var token = jwt.AdminToken();
var client = jwt.AdminClient(token);
var addRequest = new BoxCollaborationRequest(){
Item = new BoxRequestEntity() {
Id = folderId,
Type = BoxType.folder
},
AccessibleBy = new BoxCollaborationUserRequest(){
Type = BoxType.#group,
Id = groupId
},
Role = "viewer"
};
var api = client.CollaborationsManager;
var task = api.AddCollaborationAsync(addRequest);
task.Wait();
When running this code but replacing the Admin Token with Developer Token generated from the Box Applicaiton Edit Page it works.
Any help is appreciated
OK, I had long discussion with BOX Technical team and here is the conclusion: Using AppUser is not the right choice for my scenario because it is limited only to the folders it creates. There is no way to bypass it.
The solution is:
1. Configure the Application to use standard user
2. Create User with administrative rights that will be used by the API to do activities in BOX. I named this user "API User"
3. Follow the oAuth 2 tutorial to generate access token and refresh token that the API .Net application can use instead of generating token for the AppUser. the oAuth 2 tutorial can be found at https://www.box.com/blog/get-box-access-tokens-in-2-quick-steps/
If the app user is a member of the group(s) you want to be able to access the folder then you shouldn't need to set up a collaboration, the users should just have access.

How to get user name, email, etc. from MobileServiceUser?

After a lot of digging around I've got my WPF application signing users in via Azure Mobile Service. My Mobile Service is connected to an Azure Active Directory that I have set up. However, when I log the user in with MobileServiceClient.LoginAsync(...) the MobileServiceUser UserId is in an unreadable hash it seems. For example it looks like: "Aad:X3pvh6mmo2AgTyHdCA3Hwn6uBy91rXXXXXXXXXX". What exactly is this?
I'd like to grab the user's display name to use but I can't figure out how.
That is the userID of Azure Active Directory. You need to create a service to expose your AAD info through a service and retrieve the additional information using the access token you get from your user.
First:
ServiceUser user = this.User as ServiceUser;
var identities = await user.GetIdentitiesAsync();
var aad = identities.OfType<AzureActiveDirectoryCredentials>().FirstOrDefault();
var aadAccessToken = aad.AccessToken;
var aadObjectId = aad.ObjectId;
This will give you the access token and objectID , then you need to query the information through AAD graphy API.
https://msdn.microsoft.com/library/azure/dn151678.aspx
Look at the sample request part. You should provide the query with the access token you got and objectId.
Here is an alternative approach, after reading http://justazure.com/azure-active-directory-part-2-building-web-applications-azure-ad/ scroll to the section on Identity in .Net it talks how claims are a standard part of the framework. So once you get the credentials object like provided by #beast
var aad = identities.OfType<AzureActiveDirectoryCredentials>().FirstOrDefault();
You can actually grab a dictionary with the various properties. Examples of some the properties can be found at https://msdn.microsoft.com/en-us/library/system.identitymodel.claims.claimtypes(v=vs.110).aspx
So from there you can do the following:
if (aad != null)
{
var d = aad.Claims;
var email = d[ClaimTypes.Email];
}
I did this to pull the user id which was cross referenced in a table. FYI I am using App Service, but I believe the credentials object is the same in Mobile Service

MVC 5 - Roles - IsUserInRole and Adding user to role

In MVC4 i used Roles.IsUserInRole to check if a given user is in some role. However, with MVC5 i can't do it anymore...
At first, it asked me to enable RoleManager at the web.config but then i discovered that microsoft moved away from Web.Security to Microsoft.AspNet.Identity.
My question now is, with Microsoft.AspNet.Identity how do i do an action similar to Roles.IsUserInRole?
And/or create a relation between the Role and the User.
By the way, i'm still trying to understand the new authentication methods (ClaimsIdentity?).
You should read http://typecastexception.com/post/2014/04/20/ASPNET-MVC-and-Identity-20-Understanding-the-Basics.aspx for the basics of Identity 2.0!
There's also a complete demo project to get you started:
https://github.com/TypecastException/AspNet-Identity-2-With-Integer-Keys
If you take this as the basis for your Identity foundation you'll end up with something like this:
var userManager = HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>();
const string name = "YourUsername"
const string roleName = "Admin";
var user = userManager.FindByName(name);
//check for user roles
var rolesForUser = userManager.GetRoles(user.Id);
//if user is not in role, add him to it
if (!rolesForUser.Contains(role.Name))
{
userManager.AddToRole(user.Id, role.Name);
}
The post above was really helpful (Thanks Serv, would vote up if my reputation allowed me to). It helped me solve an issue I was having with a few minor changes to fit what I was trying to achieve. My particular problem was that I wanted to check in an MVC view if the current user was in a given role group. I also found that Roles.IsUserInRole was no longer working.
If you are doing this in a view, but using ASP.NET identity 2.0 instead of the simple membership provider offered by previous MVC versions, the following might be helpful as a 1-line solution:
bool isAdmin = HttpContext.Current.User.IsInRole("Admin");
You may then combine it with HTML to selectively show menu items (which is what I've been using it for) with something like this:
#if (isAdmin)
{
<li>#Html.ActionLink("Users", "List", "Account")</li>
}
This allows me to prevent access to the user management hyperlinks where the user is not a member of the 'Admin' role.

How to handle anonymous user in mvc application?

I am creating an Asp.NET MVC-4 application. In my application user can post their products. I want that whether user logged in or not [Anonymous] , he could post there products. For this i can use SessionId, but i am worry about if session expires that how can i detect the anonymous user.
I want to know about Migrating the Anonymous profile to logged in Userprofile. Please suggest me some good tutorials or resources or logic by which i can implement this.
http://msdn.microsoft.com/en-us/library/ewfkf772(v=vs.100).aspx has it all.
Use this to migrate rhe profiles in Global.asax
public void Profile_OnMigrateAnonymous(object sender, ProfileMigrateEventArgs args)
{
ProfileCommon anonymousProfile = Profile.GetProfile(args.AnonymousID);
Profile.ZipCode = anonymousProfile.ZipCode;
Profile.CityAndState = anonymousProfile.CityAndState;
Profile.StockSymbols = anonymousProfile.StockSymbols;
////////
// Delete the anonymous profile. If the anonymous ID is not
// needed in the rest of the site, remove the anonymous cookie.
ProfileManager.DeleteProfile(args.AnonymousID);
AnonymousIdentificationModule.ClearAnonymousIdentifier();
// Delete the user row that was created for the anonymous user.
Membership.DeleteUser(args.AnonymousID, true);
}

Categories