I'm trying to deploy the validation logins for active directory groups. as shown below
// Control with groups restriction of the ad
[Authorize (Roles = "Financial, ADM")]
public class FinanceiroController: Controller
{
}
I'm using FormsAuthentication to login:
Principal User = autenticacao.Autenticar (login, password);
if (User! = null)
{
FormsAuthentication.SetAuthCookie (login, true);
}
the problem is that I can not access the same controller using a user q is the ADM group, someone help me?
Related
I need "admin approval" for login as user after the registration. I am doing it in asp.net MVC, using ms sql, visual studio. I am new to it,need help badly, how many way I can do it and whats the process to do that.
My thought: I made login Registration with email verify. Now I need to make admin verify.
Here is my database table :
Database: I made a registration table(Tbl_User), Approval Table(Tbl_Approval). I need to confirm admin approval while login:
var approval = dc.Tbl_Approval.Where(m => m.Tbl_User.EmailID == login.EmailID).FirstOrDefault();
if (!approval.ApprovalStatus)
{
ViewBag.Message = "Please wait for admin approval";
return View();
}
For this I need to insert the Tbl_User data into Tbl_Approval table which is previously empty. so I need the query in the controller action(for Tbl_Approval) to get the (Tbl_User)list into Tbl_Approval table and edit the Approval status. I tried this:-
public ActionResult List()
{
List<Tbl_User> userList = db.Tbl_User.ToList();
Tbl_Approval approval = new Tbl_Approval();
List<Tbl_Approval> approvalUserList = userList.Select(x => new Tbl_Approval { UserID = x.UserID }).ToList();
return View(approvalUserList);
}
Please help me on the controller action to get the(Tbl_User) list into the Tbl_Approval table. Also suggest me any other good way to do this task.
You can create the Action method for approval process. When admin approves any particular user, you need to pass that userId. I have used EntityFramework for the example.
Here is the code that should work
public ActionResult ApproveUser(int userId)
{
var user = context.Users.Find(userId);
if(user != null)
{
user.ApproveStatus = 1;
context.Entry(user).State = System.Data.Entity.EntityState.Modified;
context.SaveChanges();
}
return View();
}
TO solve this issue do the following i.e.
Add the status column in your login table and set the default approval status for all new sign ups as not approved.
Create a module for admin only in your web portal to view/approve the new sign ups.
Create designated actions with view pages in your new module to view and approve the signups.
I recommend creating a new controller for this new module that is accessible to the admin only and not to everyone else.
When the admin login the system show notifications to him so, he can open and go to this new module and perform approval actions.
When the admin performs the approval action update the approval status from not approve to approve.
I'm building a web app that is essentially a store, but I want to put in an easy way for the admin of the site to add new products. However I want to restrict this part of the site so only the admin can access it. I have no use for other users at this moment.
How do I make it so that anybody with the admin username and password can access these pages and it will persist to know that they are logged in? I already have a system in place that accepts a user input and then continues to the admin pages if it's correct. But the problem is if someone decides to just go directly to the pages like Admin/AddProduct. I'd need my app to know that they're not allowed to access the AddProduct page yet and redirect them back to the login.
Here's how you go about it Joey
You could do this easily by creating a CreateRoles method in your startup class. This helps check if the roles are created, and creates the roles if they aren't; on application startup. Like so.
private async Task CreateRoles(IServiceProvider serviceProvider)
{
//initializing custom roles
var RoleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>();
var UserManager = serviceProvider.GetRequiredService<UserManager<ApplicationUser>>();
string[] roleNames = { "Admin", "Store-Manager", "Member" };
IdentityResult roleResult;
foreach (var roleName in roleNames)
{
var roleExist = await RoleManager.RoleExistsAsync(roleName);
// ensure that the role does not exist
if (!roleExist)
{
//create the roles and seed them to the database:
roleResult = await RoleManager.CreateAsync(new IdentityRole(roleName));
}
}
// find the user with the admin email
var _user = await UserManager.FindByEmailAsync("admin#email.com");
// check if the user exists
if(_user == null)
{
//Here you could create the super admin who will maintain the web app
var poweruser = new ApplicationUser
{
UserName = "Admin",
Email = "admin#email.com",
};
string adminPassword = "p#$$w0rd";
var createPowerUser = await UserManager.CreateAsync(poweruser, adminPassword);
if (createPowerUser.Succeeded)
{
//here we tie the new user to the role
await UserManager.AddToRoleAsync(poweruser, "Admin");
}
}
}
and then you could call the await CreateRoles(serviceProvider); method from the Configure method in the Startup class.
ensure you have IServiceProvider as a parameter in the Configure class.
Question 2: "How do I make it so that anybody with the admin username and password can access these pages "
You can do this easily, like so.
[Authorize(Roles="Admin")]
public class ManageController : Controller
{
//....
Return View();
}
You can also use role-based authorization in the action method like so. Assign multiple roles, if you will
[Authorize(Roles="Admin")]
public IActionResult Index()
{
/*
.....
*/
}
While this works fine, for a much better practice, you might want to read about using policy based role checks. You can find it on the ASP.NET core documentation here, or this article I wrote about it here
Once you add ASP.NET Identity to your project you can implement Role based Authorization in your application. Basically it allows you to setup [Authorize(Roles = "Administrator")] attribute for contollers which shall be available for admin users only.
I have an existing ASP.NET application that uses LDAP for authentication and ASP.NET membership for authentication and authorization.
So an LDAP user could choose to authenticate either using his LDAP credentials, or ASP.NET membership credentials. A non LDAP user can only authenticate using LDAP credentials.
I now want to create a Web API project that uses a similar approach for authentication and authorization.
Using VS 2013, I created a new Web API project that uses the Individual Accounts option for authentication.
I've modified the GrantResourceOwnerCredentials method in the Providers\ApplicationOAuthProvider.cs file.
Before
...
IdentityUser user = await userManager.FindAsync(context.UserName, context.Password);
if (user == null)
{
context.SetError("invalid_grant", "The user name or password is incorrect.");
return;
}
...
After
...
IdentityUser user;
if (AuthenticateActiveDirectory(context.UserName, context.Password, "MyADDomain"))
{
user = await userManager.FindByNameAsync(context.UserName);
}
else
{
user = await userManager.FindAsync(context.UserName, context.Password);
}
if (user == null)
{
context.SetError("invalid_grant", "The user name or password is incorrect.");
return;
}
...
And the AuthenticateActiveDirectory method is:
private bool AuthenticateActiveDirectory(string userName, string password, string domain)
{
bool validation;
try
{
var lcon = new LdapConnection(new LdapDirectoryIdentifier((string)null, false, false));
var nc = new NetworkCredential(userName, password, domain);
lcon.Credential = nc;
lcon.AuthType = AuthType.Negotiate;
lcon.Bind(nc);
validation = true;
}
catch (LdapException)
{
validation = false;
}
return validation;
}
This works, but is it the best way of doing it or is there a better way?
It's fine. Couple things come to mind:
If you have multiple domains in your forest (or ever will support that), username isn't unique across the forest - just the domain. Looks like you're keying on username today.
For your LdapConnection, I assume the null server name is just for show here? Rather than hardcoding one, you can use the S.DS.AD namespace to find a domain controller for you.
You'd probably want AuthType.Basic rather than Negotiate here. You'll want to make sure your connection is LDAP/S since the creds will be cleartext.
I have inherited an existing application. This application uses ASP.NET MVC 3. It has some APIs. Those APIs look like the following:
[AcceptVerbs(HttpVerbs.Post)]
[Endpoint]
public ActionResult AuthenticatePlayer(string username, string password)
{
// Ensure that the user entered valid credentials
if (Membership.ValidateUser(username, password) == false)
return Json(new { statusCode = StatusCodes.INVALID_CREDENTIALS, message = "You entered an invalid username or password. Please try again." });
// Get the profile of the person that just logged in.
ProfileCommon userProfile = (ProfileCommon)(ProfileCommon.Create(username));
if (userProfile != null)
{
string name = username;
if (String.IsNullOrEmpty(userProfile.FirstName) == false)
name = userProfile.FirstName;
return Json(new {
statusCode = StatusCodes.SUCCESS,
payload = name,
username = username.ToLower(),
});
}
}
[AcceptVerbs(HttpVerbs.Get)]
[Endpoint]
public ActionResult SomeUserAction(string q)
{
// TODO: Ensure the user is authorized to perform this action via a token
// Do something
return Json(new { original = q, response = DateTime.UtcNow.Millisecond }, JsonRequestBehavior.AllowGet);
}
I'm trying to figure out how to integrate a token-based authorization schema into this process. From my understanding, a token-based system would return a short-lived token and a refresh token to a user if they successfully login. Then, each method can check to see if a user is authorized to perform the action by looking at the token. I'm trying to learn if this is built-in to ASP.NET MVC or if there is a library I can use. I need to figure out the shortest way to get this done.
Thank you so much!
I've built a WebAPI Token Authentication library a year ago, providing Token based authentication:
WebAPI Token Auth Bootstrap is out of the box Token based User Auth for WebAPI applications, Provides ready to use 'TokenAuthorize'
Attribute and 'TokenAuthApiController' Controller.
Among its features - Token Based User Authentication User Property inside the
TokenAuthApiController (Id, Username, Role, LastAccess).
Token Based User Authorization TokenAuthorizeAttribute with Access
Level - Public, User, Admin or Anonymous.
Built-in Functionality Login(), Logoff(), Error(), Unauthorized()
Responses with various overloads.
You can read more about here and in its own wiki in GitHub.
Nowadays I am working on a Node.js application and I am using Json Web Tokens (JWT) using Node.js library and it is very easy and straightforward.. its Node.js after all ;)
I saw there is a .NET implementation of JWT explained on this article which I recommend you to look at.
You can use Owin ... i.e. Microsoft.owin.security
I haven't tried this implementation but this is just to give you an idea:
var identity = new ClaimsIdentity(Startup.OAuthBearerOptions.AuthenticationType);
var currentUtc = new SystemClock().UtcNow;
ticket.Properties.IssuedUtc = currentUtc;
ticket.Properties.ExpiresUtc = currentUtc.Add(TimeSpan.FromMinutes(30));
DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
return Json(new {
statusCode = StatusCodes.SUCCESS,
payload = name,
username = username.ToLower(),
accessToken = Startup.OAuthBearerOptions.AccessTokenFormat.Protect(ticket)
});
How do I get the roles for an authenticated logged in extranet user in sitecore 6.4? I'm trying to check the roles to restrict access.
The Sitecore.Context.User.Roles is coming back with default\Anonynous not extranet\WebsiteUser.
UPDATE: When checking the roles directly after login all appears fine. However it's when I check the roles from within a httphandler that the Sitecore.Context.User.Roles is lost and defaults to default\Anonynous.
Create extranet user code:
using (new SecurityStateSwitcher(SecurityState.Disabled))
{
var domainUsername = Context.Domain.GetFullName(user.Email);
Sitecore.Security.Accounts.User sitecoreUser = Sitecore.Security.Accounts.User.Create(domainUsername, user.Password);
Database dbCore = Factory.GetDatabase("core");
Item profileItem = dbCore.GetItem(CustomUserProfilePath);
List<Role> roles = Sitecore.Context.Domain.GetRoles().Where(role => role.Name == "extranet\WebsiteUser").ToList();
if (roles.Any())
{
sitecoreUser.Roles.Add(roles.First());
}
sitecoreUser.Profile.ProfileItemId = profileItem.ID.ToString();
sitecoreUser.Profile.FullName = string.Format("{0} {1}", user.FirstName, user.LastName);
sitecoreUser.Profile.Email = user.Email;
sitecoreUser.Profile.Comment = "Created by the register system";
sitecoreUser.Profile.Save();
}
I have now found a solution through using IIS7 url rewrites instead of routing the handler through the web.config. This keeps the Sitecore.Context so I can check the logged in users roles.