且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用Shibboleth的asp.net MVC身份验证

更新时间:2022-12-06 12:32:45

您将要在Global.asax.cs中创建一个具有以下签名的方法

You'll want to create a method in Global.asax.cs that has the following signature

protected void Application_PostAuthenticateRequest()
{
    //Your code here.
}

在几乎完成任何其他操作之前,它将自动被调用(如果存在,MVC会调用此方法,您不必在任何地方打开"该方法),这是设置Principal的地方.例如,假设您有一个名为RolesHeader的标头,该标头具有逗号分隔的角色值,另一个标为UserId的标头具有(duh)用户ID.

This will be called automatically before almost anything else is done (MVC will call this method if it exists, you don't have to "turn it on" anywhere), and this is where you need to set the Principal. For instance, let's assume you have a header called RolesHeader that has a comma separated value of roles and another header called UserId that has (duh) the user ID.

您的代码没有任何错误处理,可能类似于:

Your code, without any error handling, might look something like:

protected void Application_PostAuthenticateRequest()
{
    var rolesheader = Context.Request.Headers["RolesHeader"];
    var userId = Context.Request.Headers["UserId"];
    var roles = rolesheader.Split(',');
    var principal = new GenericPrincipal(new GenericIdentity(userId), roles);
    Context.User = principal;
}

这是[Authorize]属性使用的主体/身份,因此在请求生命周期开始时在此处设置它意味着[Authorize]属性将正常工作.

It's the Principal/Identity that the [Authorize] attribute uses, so setting it here at the beginning of the request lifecycle means the [Authorize] attribute will work correctly.

其余的是可选的,但我建议:

我喜欢创建自己的实现IPrincipal和IIdentity的自定义类,而不是使用GenericPrincipal和GenericIdentity,因此可以在其中填充更多用户信息.这样,我自定义的Principal和Identity对象将获得更多信息,例如分支机构号或电子邮件地址或其他任何信息.

I like to create my own custom classes that implement IPrincipal and IIdentity instead of using the GenericPrincipal and GenericIdentity, so I can stuff more user information in it. My custom Principal and Identity objects then have much more rich information, such as branch numbers or email addresses or whatever.

然后,我创建一个名为BaseController的控制器,该控制器具有以下内容

Then, I create a Controller called BaseController that has the following

protected new CustomPrincipal User
{
    get
    {
        return (base.User as CustomPrincipal) ?? CustomPrincipal.GetUnauthorizedPrincipal();
    }
}

这使我可以访问所有丰富的自定义主体数据,而不仅仅是IPrincipal中定义的数据.然后,我所有的真实控制器都从BaseController继承,而不是直接从Controller继承.

This allows me to access all my rich, custom Principal data instead of just what's defined in IPrincipal. All of my real controllers then inherit from BaseController instead of directly from Controller.

很明显,当使用这样的自定义主体时,可以在Application_PostAuthenticateRequest()方法中将Context.User设置为您的CustomPrincipal而不是GenericPrincipal.

Obviously, when using a custom Principal like this, in the Application_PostAuthenticateRequest() method, you'd set the Context.User to be your CustomPrincipal instead of a GenericPrincipal.