首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将区域/控制器限制为通过身份验证的用户

将区域/控制器限制为通过身份验证的用户
EN

Stack Overflow用户
提问于 2014-01-07 17:27:47
回答 2查看 273关注 0票数 3

我正在用C#构建一个web,这是我第一次使用C#来构建web。没有什么特别的事情发生;我们调用一个存储过程,并以JSON的形式返回结果。

我需要限制对通过身份验证的用户的访问。我将[Authorize]添加到控制器中,即使用户已经通过身份验证,控制器的工作范围也可以重定向到登录页面。[Authorize]没有像预期的那样工作。有一个现有的应用程序,所以我不能更改任何全局设置。我该怎么办?

代码示例如下:

代码语言:javascript
复制
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

using XXXX.XXXX.Web.Areas.api.Models;

namespace XXXX.XXXX.Web.Areas.api.Controllers
{
    [Authorize]
    public class ReportController : Controller
    {
        //
       // GET: /api/Report/

        public ActionResult Index()
        {

             return View();
        }

        //
        // GET: /api/Report/RiskRatingSnapshot
        public JsonResult  RiskRollForward(string type)
        {

            var GET = Request.QueryString;

            if (type != "Details") type = "";

            var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["PaynetDatabase"].ConnectionString);
            var command = new SqlCommand("procPrptAPDPortMgrRollForwardDetails", connection)
            {
                CommandType = CommandType.StoredProcedure
            };

            command.Parameters.AddWithValue("@subid", 0);
            command.Parameters.AddWithValue("@portfolio", GET["portfolio"]);
            command.Parameters.AddWithValue("@currentDateKey", GET["currentDateKey"]);
            command.Parameters.AddWithValue("@priorDateKey", GET["priorDateKey"]);
            command.Parameters.AddWithValue("@exposureFrom", GET["exposureFrom"]);
            command.Parameters.AddWithValue("@exposureTo", GET["exposureTo"]);
            command.Parameters.AddWithValue("@APDSensitivity", GET["APDSensitivity"]);



             if (type == "Details")
            {

                command.Parameters.AddWithValue("@groupId", GET["groupId"]);
                connection.Open();
                SqlDataReader reader = command.ExecuteReader();

                var table = pack(reader);
                connection.Close();

                return Json(table, JsonRequestBehavior.AllowGet);
            /*************************************************************
            --Example:
            DECLARE @return_value int

            EXEC    @return_value = [dbo].[procPrptAPDPortMgrRollForwardDetails]
                    @subid = 0,
                    @portfolio = N'52,53',
                    @currentDateKey = 20111001,
                    @priorDateKey = 20110701,
                    @APDSensitivity = 0.25,
                    @exposureFrom = 0,
                    @exposureTo = 1000000000,
                    @groupId = 2


            GO
            **************************************************************/
            }
            return null;
        }

        private List<DetailsReport> pack(SqlDataReader reader)
        {
            List<DetailsReport> table = new List<DetailsReport>();
            while (reader.Read())
            {
                DetailsReport row = new DetailsReport();

                row.customer_number = reader["customer_number"].ToString();
                row.customer_name = reader["customer_name"].ToString();
                row.portfolio = Convert.ToInt32( reader["portfolio"].ToString() );
                row.portname = reader["portname"].ToString();
                row.state = reader["state"].ToString();
                row.exposure_cur = reader["exposure_cur"].ToString();
                row.exposure_chg = reader["exposure_chg"].ToString();
                row.number_of_lenders = Convert.ToInt32( reader["number_of_lenders"].ToString() );
                row.member_lender_business_unit = reader["member_lender_business_unit"].ToString();
                row.LastKnownDel = reader["LastKnownDel"].ToString();
                row.CurDelStatus = reader["CurDelStatus"].ToString();
                row.PayNet_absolutePD_4q = reader["PayNet_absolutePD_4q"].ToString();
                row.APD_4QChg = reader["4QAPD_Chg"].ToString();
                row.PD_chg_wtd_cur_exp = reader["PD_chg_wtd_cur_exp"].ToString();
                row.expWtdPD_cur = reader["ExpWtdPD_cur"].ToString();
                row.expWtdPD_chg = reader["expWtdPD_chg"].ToString();


                table.Add(row);

            }

            return table;
        }
    }

 }
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-01-08 01:44:39

扩展[Authorize]以满足您的需要。以下是一个例子:

控制器

在控制器中,确保包含新的助手类,并使用[Helper.Authorize]代替[Authorize]

代码语言:javascript
复制
using XXXX.Online.Web.Areas.api.Helpers;

扩展授权

代码语言:javascript
复制
using System;
using System.Web;
using System.Web.Mvc;
using XXXX.Online.Session;
using XXXX.Online.Enums;

 namespace XXXX.Online.Web.Areas.api.Helpers
{
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
    public class AuthorizeAttribute : System.Web.Mvc.AuthorizeAttribute
    {
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
           try
           {
               PayNet.Online.Web.Security.CheckSession(System.Web.HttpContext.Current);
           }
           catch
           {
               // Get the redirection URL for the request from the system.web/authentication section in the the web.config.
               var authenticationSection = (System.Web.Configuration.AuthenticationSection)System.Configuration.ConfigurationManager.GetSection("system.web/authentication");
               System.Web.Configuration.FormsAuthenticationConfiguration formsAuthentication = authenticationSection.Forms;
               string currentLoginUrl = formsAuthentication.LoginUrl;

               HttpContext.Current.Response.Redirect(currentLoginUrl, true);
           }
      }
   }
}
票数 0
EN

Stack Overflow用户

发布于 2014-01-07 17:45:27

通过实现从ActionFilterAttribute继承的自己的类并在那里执行验证(在本例中,检查当前用户在AD组中),我做了类似的事情。通过重写OnActionExecuting方法,您可以访问HttpActionContext,我认为这在您试图实现的过程中已经足够早了。然后,您可以抛出一个HttpResponseException并包括如下所示的自定义消息:

代码语言:javascript
复制
         var msg = string.Format("User {0} attempted to use {1} but is not a member of the AD group.", id, actionContext.Request.Method);
        _logger.Info(msg);
        throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Unauthorized)
        {
            Content = new StringContent(msg),
            ReasonPhrase = msg
        });

希望这能有所帮助!有关于MSDN 这里的演练。

编辑:不久前,我在这个线程这里中给出了一个更好的例子。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/20978026

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档