im trying to create mvc application with role based authorization. Currently i want 2 roles only, admin and user. I already make simple authorization work, but still without role. I already search so many reference in internet but still cant find one that works with me. Please help, thank you.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Login(LoginViewModel model)
{
if (ModelState.IsValid)
{
string loginquery = "select UserId,Password,Roles from UserAcc where "
+ "userId = #p0 and Password = #p1";
var a= db.User.SqlQuery(loginquery,model.userid, model.password).Count() ;
if (a>0)
{
FormsAuthentication.SetAuthCookie(model.userid, false);
Session["userid"] = model.userid.ToString();
return RedirectToAction("Index", "Employee");
}
else { return RedirectToAction("Login"); }
}
else
{
ModelState.AddModelError("", "EmailId or Password Incorrect.");
}
return View(model);
}
I want the program to set role authorization based on role field in database
SELECT TOP 1000 [UserId]
,[Password]
,[Roles] FROM [ESS].[dbo].[UserAcc]
And i want to filter my controller like this
namespace TEST2.Controllers{[Authorize(Roles = "user")]
public class EmployeeController : Controller
{
Thankyou,
Related
I have Xamarin forms app ,the user will register and login for first time and save username in SQLite database ,then I want the app check if the database found and the username is have been inserted any time he open the app.
i used this code in registration page :
SqliteUser squser = new SqliteUser()
{
appUser = user
};
using (SQLiteConnection conn = new SQLiteConnection(App.DatabaseLocation))
{
conn.CreateTable<SqliteUser>();
int rows = conn.Insert(squser);
};
I checked the user is inserted successfully.
Now I made CheckUserpage to check if there is a user registered, if yes the alert me the name of first user inserted :-
public partial class CheckUserPage : ContentPage
{
public CheckUserPage()
{
InitializeComponent();
CheckSqlUser();
}
private void CheckSqlUser() {
using (SQLiteConnection conn = new SQLiteConnection(App.DatabaseLocation))
{
var userQuery = conn.Table<SqliteUser>().Where(a=>a.appUser!="");
if (userQuery != null) {
DisplayAlert("user found", "user found", "OK");
}
};
}
}
How can I get the first user name inserted ?
Best Regard
to get the first value in a list, use LINQ
using System.Linq;
var userQuery = conn.Table<SqliteUser>().Where(a=>a.appUser!="");
var results = userQuery.ToList();
var first = results.FirstOrDefault();
I understand that the title of the question may be vague but then that's the best way I could come up with to explain my issue at hand.
I'm overriding the OnActionExecuting function to manage my session related activities and allow/ deny requests to authorized/ unauthorized users, respectively. Along with tracking of the session, I'm also using the OnActionExecuting to load user available features for the current page into a temporary class and accessing from the view using ajax call.
namespace MyApp.Controllers
{
public class TESTController : Controller
{
[SessionTimeout]
public ActionResult Index()
{
return this.View();
}
}
}
public class SessionTimeoutAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
HttpContext ctx = HttpContext.Current;
if (ctx.Session["AppUser"] == null)
{
// Redirect to the login page
// Or deny request
}
else
{
var controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;
var actionName = filterContext.ActionDescriptor.ActionName;
var methodType = ((ReflectedActionDescriptor)filterContext.ActionDescriptor).MethodInfo.ReturnType;
if (methodType == typeof(ActionResult))
{
// Load all user access rights for the current page into a temporary memory
// by using the Action and Controller name
}
}
base.OnActionExecuting(filterContext);
}
}
The above works like a charm.. But the issue is when the user clicks on the back button of the browser or hits the backspace key. In that case, the OnActionExecuting function is never called for the ActionResult and further I am unable to load the current page access rights for the user.
Thanks & Regards,
Kshitij
Adding the following to my ActionResult made the above code to work.
[SessionTimeout]
[OutputCache(Duration = 0, NoStore = true)]
public ActionResult SomeView()
{
return this.View();
}
I'm trying to add a controller for the ApplicationUser.cs so that when a admin is logged in, they have the ability to view, edit, delete any records from the dbo.AspNetUsers table however I think I'm doing it wrong.
<form asp-controller="Admin" asp-action="ActiveUser" method="post">
<input type="hidden" asp-for="#user.Email" />
<button type="submit" class="btn btn-primary">Active</button>
</form>
Admin Controller :
[HttpGet]
public IActionResult ActiveUser() { return View(); }
[HttpPost]
public async Task<ActionResult> ActiveUser(ApplicationUser Model)
{
var active =_userManager.Users.FirstOrDefault(p => p.Email == Model.Email);
if (active != null)
{
active.IsActive = true;
using (var transaction = _application.Database.BeginTransaction())
{
try
{
await _application.SaveChangesAsync();
transaction.Commit();
}
catch (Exception ex)
{
_ = (ex.Message);
transaction.Rollback();
return View("Er");
}
}
}
return View();
}
but I think Submit button linked to wrong form post because when I debug active is null! and no changes in my SQL Server. How to manage it?
To add, delete and modify the users and roles in AspNetUsers you must use the UserManager and RoleManager services. Do not try to modify the entities directly using the DbContext.
So to create a user calll the UserManager.CreateAsync() method.
To save changes to a user call UserManager.UpdateAsync()
Example - To find a User by email address, change a property then save the change:
var currentUser = await _userManager.FindByEmailAsync(email);
currentUser.IsActive = true;
await _userManager.UpdateAsync(currentUser);
The same applies for roles that users are in. Use the RoleManager service to add and delete roles.
if (!await roleManager.RoleExistsAsync(roleName))
{
await roleManager.CreateAsync(new IdentityRole(roleName));
}
await userManager.AddToRoleAsync(currentUser, roleName);
Microsoft docs with some examples of updating users and roles
Right now I'm working with silverlight project and I'm stuck on how to list all of users and user profile together.
Now I'm using this method to get all user via WCF
public IEnumerable<MembershipServiceUser> GetAllUsers()
{
return Membership.GetAllUsers().Cast<MembershipUser>().Select(u => new MembershipServiceUser(u));
}
public void FromMembershipUser(MembershipUser user)
{
this.Comment = user.Comment;
this.CreationDate = user.CreationDate;
this.Email = user.Email;
this.IsApproved = user.IsApproved;
this.UserName = user.UserName;
}
I can get all user from those code above but I don't know how extactly to get user profile
eg. Firstname , Lastname , etc..
You can create a new instance of ProfileBase and access the profile fields with the method GetPropertyValue("propertyName"), where propertyName is the name of your custom registration data.
var profile = ProfileBase.Create(user.UserName);
this.CustomProperty = profile.GetPropertyValue("customPropertyName");
I'm not 100% sure about the syntax, I come from a vb environment and haven't written any c# in a while.
ProfileInfoCollection profiles = ProfileManager.GetAllProfiles(ProfileAuthenticationOption.All);
foreach (ProfileInfo pi in profiles)
{
ProfileCommon p = Profile.GetProfile(pi.UserName);
countries.Add(p.Country);
}
How i can get Current User. And how i can validate user via Active Directory by user and pass.
You should use ASP.NET authentification to achieve this. In order to implement this, I would strongly recommend you to use something as RIA Services, which contains all the plumbing required to enable ASP.NET authentification in a Silverlight App.
With ASP.NET auth enabled, you will be able to edit your config file to use a AD identity provider, as in any other ASP.NET web app.
More informations about the ActiveDirectoryMembershipProvider on MSDN
[OperationContract]
public string GetCurrentUserWindowsLogin()
{
return Environment.UserName;
}
[OperationContract()]
public User DoLogIn(string login, string password)
{
string userName = String.Format(#"ELEGION\{0}", login);
string SERVER = "LDAP://Caesar.elegion.local";
User user = null;
try
{
DirectoryEntry entry = new DirectoryEntry(SERVER, userName, password, AuthenticationTypes.ReadonlyServer);
object nativeObject = entry.NativeObject;
if (nativeObject != null)
{
HeRMeSSunRiseDBEntities ent = EntitySingleton.Entities;
user = ent.Users.Where(l => l.Login == login && l.IsDisabled == false).FirstOrDefault();
if (user != null)
{
user.ADObject = entry.Guid.ToString();
ent.SaveChanges();
return user;
}
}
}
catch (DirectoryServicesCOMException cex)
{
Debug.Write(cex.Message);
}
catch (Exception ex)
{
Debug.Write(ex.Message);
}
return user;}