Kartic Kalyan
Kartic Kalyan

Reputation: 41

Custom Authorization & Role in MVC 4 not working

I need to implement a Single Sign on where a Com+ component should be called to authenticate the user & provide the roles. In short, I need to bypass the default mechanism in MVC 4 where it tries to access the aspnetdb database. So I started with a new MVC4 internet project and added the following code.

In Global.asax

public void FormsAuthentication_OnAuthenticate(object sender, FormsAuthenticationEventArgs args)
    {
        bool retval = CreateUserObject("John", "pwd");
    }

private bool CreateUserObject(string userName, string password)
    {
        string[] currentUserRoles = { "Admin", "User" };
        GenericPrincipal userPrincipal = new GenericPrincipal(new GenericIdentity(userName), currentUserRoles);
        HttpContext.Current.User = userPrincipal;
        //Thread.CurrentPrincipal = userPrincipal;
        return true;
     }

Within the HomeController.cs, I added the [Authorize] attribute for the "About" action as below and it works as expected

[Authorize]
public ActionResult About()

However if I modify the [Authorize] attribute to permit only "Admin" role as below I get a runtime error (at the bottom). Is there a way around this to use my own collection of roles for the logged in user, instead of querying the database? I also need to do something similar to the user Profile as well (i.e, instead of database, I should populate the values from the Com+ application.

[Authorize(Roles = "Admin")]
public ActionResult About()

Server Error in '/' Application.

A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)

Upvotes: 3

Views: 867

Answers (1)

miguelerm
miguelerm

Reputation: 124

Maybe you need to create a Custom RoleProvider, like this:

namespace DemoApp.Providers
{
    public class MyCustomRoleProvider : System.Web.Security.SqlRoleProvider
    {
        public override string[] GetRolesForUser(string username)
        {
            string[] currentUserRoles = { "Admin", "User" };
            return currentUserRoles;
        }
    }
}

And in the web.config of the application, change the default role provider:

<system.web>
    <roleManager enabled="true" defaultProvider="DefaultRoleProvider">
        <providers>
            <add name="DefaultRoleProvider" type="DemoApp.Providers.MyCustomRoleProvider, DemoApp"/>
        </providers>
    </roleManager>
<system.web>

Upvotes: 2

Related Questions