0

I am using windows authentication for my ASP.NET application. Fetching the current user name is fairly straightforward in razor views i.e @User.Identity.Name

The feature I am implementing is that I pass the current user name in my sql select query and get the associated role from the table. Next, I would like to pass the role back to the controller so that I can access it in all of my application views.

So that I could perform operations in my views like

@if (CurrentUserRole = "Admin") {
  // Do something
} else {
  // So something else
}

HomeController.cs

using System;
using System.Web;
using System.Collections.Generic;
using System.Diagnostics;
using Microsoft.AspNetCore.Mvc;
using nmvs_db.dal;
using nmvs_module;
using nmvs_module.util;
using SecureMedi.Models;
using SecureMedi.DAL;

namespace SecureMedi.Controllers {
    public class HomeController: Controller {
        static HomeController() {
            foreach(string s in new string[] {
                "com.ibm.oauth.OAuthUtils",
                "nmvs_server",
                "nmvs_module"
            }) {
                var l = org.apache.log4j.Logger.getLogger(s);
                l.addAppender(new DotNetAppender());
                l.debug(s + " test");
            }
        }

        public IActionResult Error() {
            return View();
        }

        public IActionResult Index() {
            ViewData["TextAreaResult"] = "No result yet";
            return View();
        }

        public IActionResult AnotherPage() {
            ViewData["TextAreaResult"] = "No result yet";
            return View();
        }
    }
}

UsersDAL.cs (DAL)

using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using SecureMedi.Models;

namespace SecureMedi.DAL {
    public class UsersDAL {
        public void CurrentUser(string currentUserName) {
            string connectionstring = "MY_CONNECTION_STRING";
            string sql = String.Format("select users.name 'Username', roles.name 'Role' from sys.database_principals users inner join sys.database_role_members memberof on users.principal_id = memberof.member_principal_id inner join sys.database_principals roles ON memberof.role_principal_id = roles.principal_id and roles.type = 'R' where users.name = '[{0}]'", currentUserName);
            SqlConnection conn = new SqlConnection(connectionstring);
            SqlCommand cmd = new SqlCommand(sql, conn);

            conn.Open();
            SqlDataReader rdr = cmd.ExecuteReader();
            if (rdr.Read()) {
                string CurrentUserRole = rdr["Role"].ToString();
                rdr.Close();
            }
            conn.Close();
        }
    }
}

Running a query against DB table directly returns something like

Query

select users.name 'Username', roles.name 'Role' from sys.database_principals users inner join sys.database_role_members memberof on users.principal_id = memberof.member_principal_id inner join sys.database_principals roles ON memberof.role_principal_id = roles.principal_id and roles.type = 'R' where users.name = 'Domain\username'

Result

Username             Role 
Domain\username      Admin

Also, I am not 100% sure if I am passing the currentUserName arg correctly in my CurrentUser function.

I have looked up on How to get the current user in ASP.NET MVC and How to pass a value from ASP.NET MVC controller to ASP.NET webforms control inside MVC View? but I am not sure how to pass the value of current user name to and fro from my controller and DAL.

0xburned
  • 2,625
  • 8
  • 39
  • 69
  • make your CurrentUser method return a string, and writing `return CurrentUserRole;` would seem to be an obvious starting point? Then you can call that method, passing in User.Identity.Name as the current username, and fetch the current role back. As for passing the currentUserName arg into the database, it's not ideal because it's vulnerable to SQL injections. Take an ADO.NET tutorial and find out how to use parameters. See http://bobby-tables.com/ if you like, it has an explanation and some examples. – ADyson Jan 24 '18 at 16:30
  • Your CurrentUser function returns nothing, and you declare local variable "CurrentUserRole" in if statement, how it should work? Also this method isn't static so you would have to create instance of UsersDAL class first to call it. – Jac Mos Jan 24 '18 at 16:31

1 Answers1

0
public CurrentUser GetCurrentUser(string currentUserName) {
        string connectionstring = "MY_CONNECTION_STRING";
        string sql = String.Format("select users.name 'Username', roles.name 'Role' from sys.database_principals users inner join sys.database_role_members memberof on users.principal_id = memberof.member_principal_id inner join sys.database_principals roles ON memberof.role_principal_id = roles.principal_id and roles.type = 'R' where users.name = '[{0}]'", currentUserName);
        SqlConnection conn = new SqlConnection(connectionstring);
        SqlCommand cmd = new SqlCommand(sql, conn);

        conn.Open();
        CurrentUser currentUser = new CurrentUser();
        SqlDataReader rdr = cmd.ExecuteReader();
        if (rdr.Read()) {
            currentUser.Role = rdr["Role"].ToString();
            currentUser.Username = currentUserName;
            rdr.Close();
        }
        conn.Close();

       return currentUser;

    }


public class CurrentUser
{
    public string Username {get;set;}
    public string Role {get;set;}
 }

in controller :

public IActionResult Index() {
        UsersDal dal = new UsersDal();
        ViewData["CurrentUser"] = dal.GetCurrentUser("username");

        return View();
    }

in cshtml:

@{
   var user = ViewData["CurrentUser"];
 }

 <b>@user.Username</b>
hakantopuz
  • 481
  • 5
  • 11