在MVC 5

时间:2017-07-09 07:35:37

标签: asp.net-mvc cookies jwt

我想在我的MVC应用中制作JWT auth。我在Web API中创建授权Web服务,正确返回令牌。之后,我试图将令牌存储在cookie中。

 [HttpPost]
    public async Task<ActionResult> Login(LoginDto loginDto)
    {
        var token = await loginService.GetToken(loginDto);

        if (!string.IsNullOrEmpty(token))
        {
            var cookie = new System.Web.HttpCookie("token", token)
            {
                HttpOnly = true
            };
            Response.Cookies.Add(cookie);
            return RedirectToAction("Index", "Product");
        }
        return View("LoginFailed");
    }

但现在我想将此令牌添加到每个请求的标头中。所以我认为动作过滤器最适合实现这一点。

public class CustomActionFilter : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        var token = filterContext.HttpContext.Request.Cookies.Get("token");

        if (token != null)
            filterContext.HttpContext.Request.Headers.Add("Authorization", $"Bearer {token}");

        base.OnActionExecuting(filterContext);
    }
}

启动

public class Startup
{
    public void Configuration(IAppBuilder app)
    {
        AutofacConfig.Configure();
        AreaRegistration.RegisterAllAreas();
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);

        ConfigureOAuth(app);
    }

    public void ConfigureOAuth(IAppBuilder app)
    {
        var issuer = System.Configuration.ConfigurationManager.AppSettings["issuer"];
        var audience = System.Configuration.ConfigurationManager.AppSettings["appId"];
        var secret = TextEncodings.Base64Url.Decode(System.Configuration.ConfigurationManager.AppSettings["secret"]);

        app.UseJwtBearerAuthentication(
            new JwtBearerAuthenticationOptions
            {
                AuthenticationMode = AuthenticationMode.Active,
                AllowedAudiences = new[] { audience },
                IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[]
                {
                    new SymmetricKeyIssuerSecurityTokenProvider(issuer, secret)
                },

            });

    }
}

然后我只是标记了授权属性的控制器。当我用POSTMAN调用它时它工作正常。

但MVC中的动作过滤器总是在授权过滤器之后触发。所以我有疑问:

  1. 如何将Cookie中的令牌添加到每个请求中?这是好习惯吗?如果不是我应该做什么?
  2. csrf攻击和其他攻击怎么样? AntiForgeryTokenAttr会做这项工作吗?那么ajax会怎么称呼?

2 个答案:

答案 0 :(得分:1)

我找到了解决方案。我只是制作自定义OAuthBearerAuthenticationProvider提供程序,在此类中我从cookie中检索令牌,然后将其分配给context.Token

public class MvcJwtAuthProvider : OAuthBearerAuthenticationProvider
{
    public override Task RequestToken(OAuthRequestTokenContext context)
    {
        var token = context.Request.Cookies.SingleOrDefault(x => x.Key == "token").Value;

        context.Token = token;
        return base.RequestToken(context);
    }
}

然后在startup.cs里面

public class Startup
{
    public void Configuration(IAppBuilder app)
    {
        AutofacConfig.Configure();
        AreaRegistration.RegisterAllAreas();
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);

        ConfigureOAuth(app);
    }

    public void ConfigureOAuth(IAppBuilder app)
    {
        var issuer = System.Configuration.ConfigurationManager.AppSettings["issuer"];
        var audience = System.Configuration.ConfigurationManager.AppSettings["appId"];
        var secret = TextEncodings.Base64Url.Decode(System.Configuration.ConfigurationManager.AppSettings["secret"]);

        app.UseJwtBearerAuthentication(
            new JwtBearerAuthenticationOptions
            {
                AuthenticationMode = AuthenticationMode.Active,
                AllowedAudiences = new[] { audience },
                IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[]
                {
                    new SymmetricKeyIssuerSecurityTokenProvider(issuer, secret)
                },
                Provider = new MvcJwtAuthProvider() // override custom auth

            });

    }
}

答案 1 :(得分:0)

@迈克尔 这就是登录服务的样子。它只是调用auth端点

 public class LoginService : ILoginService
{
    public async Task<string> GetToken(LoginDto loginDto)
    {
        var tokenIssuer = ConfigurationManager.AppSettings["issuer"];
        using (var httpClient = new HttpClient {BaseAddress = new Uri($"{tokenIssuer}/oauth2/token")})
        {
            using (var response = await httpClient.PostAsync(httpClient.BaseAddress, new FormUrlEncodedContent(
                new List<KeyValuePair<string, string>>
                {
                    new KeyValuePair<string, string>("username", loginDto.Username),
                    new KeyValuePair<string, string>("password", loginDto.Password),
                    new KeyValuePair<string, string>("grant_type", "password"),
                    new KeyValuePair<string, string>("client_id", ConfigurationManager.AppSettings["appId"])
                })))
            {
                var contents = await response.Content.ReadAsStringAsync();

                if (response.StatusCode == HttpStatusCode.OK)
                {
                    var deserializedResponse =
                        new JavaScriptSerializer().Deserialize<Dictionary<string, string>>(contents);

                    var token = deserializedResponse["access_token"];

                    return token;
                }
            }
            return null;
        }
    }
}
相关问题