授权自定义Cookie [英] Authorize custom cookie

查看:87
本文介绍了授权自定义Cookie的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嘿,

最近,我从内置会员系统i.asp.net中移出,使用自定义cookie来跟踪已登录的用户.cookie非常简单:

Hey,

Recently i moved from the inbuilt Membership system i asp.net to use a customized cookie to keep track of what user is logged in. The cookie is very simple:

 //Creting a Cookie Object
HttpCookie _userInfoCookies = new HttpCookie("UserInfo");

//Setting values inside it
_userInfoCookies["UserName"] = model.UserName;
_userInfoCookies.Expires = DateTime.Now.AddDays(1);

//Adding cookies to current web response
Response.Cookies.Add(_userInfoCookies);



我的问题是,是否可以授权控制器,如果未经授权,可以将用户重定向到登录页面?像在成员资格中一样,使用[Authorize]属性.

谢谢
sunker



My question is, is it possible to authorize controllers, and redirect the user to login page if unauthorized? Like in the membership, using [Authorize] attribute.

Thanks
sunker

推荐答案

您可以执行以下操作.

You can do something like this.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel.DataAnnotations;
using System.Web;
using System.Web.Mvc;
using System.Configuration;

namespace authorization
{
    /// <summary>
    /// Provides an authorization attribute for code that is a MVC action.
    /// </summary>
    public class MVCAuthorization : AuthorizeAttribute
    {
        /// <summary>
        /// Checks to see if a user is authorized to run this action.
        /// </summary>
        /// <param name="httpContext">The context for the http protocol.</param>
        /// <returns>True if authorized.</returns>
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            string userName = HttpContext.Current.User.Identity.Name;
            // Code to check to see if the user is authenticated here 
        }

        /// <summary>
        /// Handles a request that was not authorized.
        /// </summary>
        /// <param name="filterContext">Information about the request that was made.</param>
        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
                // Redirect the user to the Log in view for this application.
                filterContext.RequestContext.RouteData.Values["controller"] = ConfigurationManager.AppSettings.Get("LoginController");
                filterContext.Result = new ViewResult { ViewName = ConfigurationManager.AppSettings.Get("LoginPage")};
        }
    }
}


appsetting LoginController包含您要重定向到的控制器. LoginPage包含您要重定向到的视图.


The appsetting LoginController contains the controller you want to redirect to. LoginPage contains the view that you want to redirect to.


这篇关于授权自定义Cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆