c# - asp.net core restful风格的认证过滤怎么定制?

查看:176
本文介绍了c# - asp.net core restful风格的认证过滤怎么定制?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

我希望某些restful操作需要认证,可asp.net 的认证注解不好用:

app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationScheme = "foo",          
                LoginPath = new PathString("/user/forbidden"),
                AccessDeniedPath = new PathString("/user/forbidden"),
                AutomaticAuthenticate = true,
                AutomaticChallenge = true
            });
            
            

我的控制器需要返回json数据,加了[Authorize]的部分如果没登陆的话AccessDeniedPath 好像从来不会跳到,然后我把LoginPath也改成一样,倒是返回json数据了,可url也跳转了,还携带了return url信息.我的需求是加[Authorize]的控制器代码只返回{"error":"need anthorize"}就好,这应该怎么改动?

解决方案

自己重写,下面是api的
/// <summary>

/// 是否具有权限   (已登陆)
/// </summary>
public class LoginValidationAttribute : AuthorizationFilterAttribute
{
    /// <summary>
    /// 是否验证
    /// </summary>
    public bool IsValidataion { get; set; }

    /// <summary>
    /// 构造函数
    /// </summary>
    /// <param name="isValidataion"></param>
    public LoginValidationAttribute(bool isValidataion = true)
    {
        IsValidataion = isValidataion;
    }

    /// <summary>
    /// 验证规则
    /// </summary>
    /// <param name="actionContext"></param>
    public override void OnAuthorization(HttpActionContext actionContext)
    {
        if (IsValidataion)
        {
            var token = HttpContext.Current.Request[RequestConfig.ApiToken];
            var user = new TokenStoreBusiness().GetUserByToken(token);
            var isThrough = user != null;
            if (isThrough)
            {
                RequestStore.User = user;
            }
            else
            {
                HttpResponseMessage messageResp;
                messageResp = actionContext.Request.CreateResponse(System.Net.HttpStatusCode.OK, new ResponseStrApi()
                {
                    ResultCode = ResponseResult.NoAuthorize,
                    Message = "未授权的访问",
                    Data = "未授权的访问"
                });
                actionContext.Response = messageResp;
                RequestStore.Record.StoreAsync(actionContext);
            }
        }
    }

}

这篇关于c# - asp.net core restful风格的认证过滤怎么定制?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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