Home In MVC how to get Username without Windows Authentication
Reply: 0

In MVC how to get Username without Windows Authentication

Gregory Hall
1#
Gregory Hall Published in 2017-12-07 16:50:36Z

In MVC, I found code to get the Windows Username without using windows authentication, but cannot reference it.

using MvcWinUser.Extensions;

ViewBag.GetWindowsUserName = WindowsIdentityHelper.GetLoginUserName();

Error: An object reference is required for the non-static field, method, or property 'MvcWinUser.Extensions.WindowsIdentityHelper.GetLoginUserName()'


Have the following:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

using System.Threading;
using System.Security.Permissions;
using System.Security.Principal;

namespace MvcWinUser.Extensions
{
    public class WindowsIdentityHelper
    {
        public WindowsPrincipal GetWindowsPrincipal()
        {
            //Get Current AppDomain
            AppDomain myDomain = Thread.GetDomain();
            myDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);
            return (WindowsPrincipal)Thread.CurrentPrincipal;
        }

        public bool IsUserBelongsToWindowsAdministratorGroup()
        {
            WindowsPrincipal myPrincipal = GetWindowsPrincipal();

        if (myPrincipal.IsInRole("Administrators"))
            return true;

            if (myPrincipal.IsInRole(WindowsBuiltInRole.Administrator))
                return true;
            else
                return false;
        }

        public string GetFullDomainLoginUserName()
        {
            WindowsPrincipal myPrincipal = GetWindowsPrincipal();
            return myPrincipal.Identity.Name.ToString();
        }

        public string GetLoginUserName()
        {
            string authenticatedUser = string.Empty;
            string userName = GetFullDomainLoginUserName();
            if (userName.Contains("\\"))
                authenticatedUser = userName.Split('\\')[1];
            else
                authenticatedUser = userName;
            return authenticatedUser;
        }
    }
}
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.329901 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO