将Web API Cookie用作MVC Cookie [英] Use web api cookie for mvc cookie

查看:92
本文介绍了将Web API Cookie用作MVC Cookie的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Web API 2和MVC 5制作Web应用程序.

I'm making a web application by using Web API 2 and MVC 5.

我的应用程序具有api: api/account/login,用于检查发布的信息并在授予帐户访问应用程序权限时抛出状态200.

My app has api : api/account/login, which is used for checking posted information and throw status 200 when an account is granted to access application.

此外,我有一个视图:/Home/Index,仅对经过身份验证的客户端可用.

Also, I have one view : /Home/Index which is only available to authenticated client.

现在,我的方法是:

  • 调用api/account/login,接收从该api抛出的cookie.
  • 将返回的Cookie附加到浏览器.
  • 当用户访问/Home/Index时,可以使用他/她的视图.

我的问题是:

-我的方法可行吗?

-如何像MVC 5一样将Web API 2中的cookie加密为它的cookie?

谢谢

推荐答案

实现此目标的最佳方法是在MVC项目中拥有授权服务器(生成令牌的webAPI)和令牌消耗中间件.IdentityServer https://github.com/IdentityServer/IdentityServer3 应该会有所帮助.但是我已经按照以下步骤完成了

The best way to achieve this to have a authorization server (a webAPI generating a token) and token consumption middle ware in your MVC project.IdentityServer https://github.com/IdentityServer/IdentityServer3 should help. However I have done this as below

使用JWT和WEB API和ASP.Net Identity构建授权服务器,如下所述

Built an authorization server using JWT with WEB API and ASP.Net Identity as explained here http://bitoftech.net/2015/02/16/implement-oauth-json-web-tokens-authentication-in-asp-net-web-api-and-identity-2/

一旦您这样做,您的webAPIs startup.cs将如下所示

once you do that your webAPIs startup.cs will look like below

/// Configures cookie auth for web apps and JWT for SPA,Mobile apps
private void ConfigureOAuthTokenGeneration(IAppBuilder app)
{
    // Configure the db context, user manager and role manager to use a single instance per request
    app.CreatePerOwinContext(ApplicationDbContext.Create);
    app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
    app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create);

    //Cookie for old school MVC application
    var cookieOptions = new CookieAuthenticationOptions
    {
        AuthenticationMode = AuthenticationMode.Active,
        CookieHttpOnly = true, // JavaScript should use the Bearer
        AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,                
        LoginPath = new PathString("/api/Account/Login"),
        CookieName = "AuthCookie"
    };
    // Plugin the OAuth bearer JSON Web Token tokens generation and Consumption will be here
    app.UseCookieAuthentication(new CookieAuthenticationOptions());

    OAuthServerOptions = new OAuthAuthorizationServerOptions()
    {
        //For Dev enviroment only (on production should be AllowInsecureHttp = false)
        AllowInsecureHttp = true,
        TokenEndpointPath = new PathString("/oauth/token"),
        AccessTokenExpireTimeSpan = TimeSpan.FromDays(30),
        Provider = new CustomOAuthProvider(),                
        AccessTokenFormat = new CustomJwtFormat(ConfigurationManager.AppSettings["JWTPath"])
    };

    // OAuth 2.0 Bearer Access Token Generation
    app.UseOAuthAuthorizationServer(OAuthServerOptions);

}

您可以在此处 https://找到CustomOAuthProvider,CustomJwtFormat类github.com/tjoudeh/AspNetIdentity.WebApi/tree/master/AspNetIdentity.WebApi/Providers

在我要使用相同令牌进行保护的所有其他API(资源服务器)中写一个消费逻辑(即中间件).由于您要在MVC项目中使用由webAPI生成的令牌,因此在实施授权服务器后,您需要执行以下操作

Write a consumption logic (i.e. middleware) in all my other APIs (Resource servers) that you want to secure using same token. Since you want to consume the token generated by webAPI in your MVC project, after implementing Authorization server you need to do below

在您的MVC应用中,将以下内容添加到startup.cs

In your MVC app add below in startup.cs

public void Configuration(IAppBuilder app)
{
        ConfigureOAuthTokenConsumption(app);
}

private void ConfigureOAuthTokenConsumption(IAppBuilder app)
{
    var issuer = ConfigurationManager.AppSettings["AuthIssuer"];
    string audienceid = ConfigurationManager.AppSettings["AudienceId"];
    byte[] audiencesecret = TextEncodings.Base64Url.Decode(ConfigurationManager.AppSettings["AudienceSecret"]);

    app.UseCookieAuthentication(new CookieAuthenticationOptions { CookieName = "AuthCookie" , AuthenticationType=DefaultAuthenticationTypes.ApplicationCookie });

    //// Api controllers with an [Authorize] attribute will be validated with JWT
    app.UseJwtBearerAuthentication(
        new JwtBearerAuthenticationOptions
        {
            AuthenticationMode = AuthenticationMode.Passive,
            AuthenticationType = "JWT",
            AllowedAudiences = new[] { audienceid },
            IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[]
            {
                new SymmetricKeyIssuerSecurityTokenProvider(issuer, audiencesecret)                           
            }

        });
}

在MVC控制器中,当您收到令牌时,将其反序列化并从访问令牌中生成Cookie

In your MVC controller when you receive the token de-serialize it and generate a cookie from the access token

        AccessClaims claimsToken = new AccessClaims();
        claimsToken = JsonConvert.DeserializeObject<AccessClaims>(response.Content);
        claimsToken.Cookie = response.Cookies[0].Value;               
        Request.Headers.Add("Authorization", "bearer " + claimsToken.access_token);
        var ctx = Request.GetOwinContext();
        var authenticateResult = await ctx.Authentication.AuthenticateAsync("JWT");
        ctx.Authentication.SignOut("JWT");
        var applicationCookieIdentity = new ClaimsIdentity(authenticateResult.Identity.Claims, DefaultAuthenticationTypes.ApplicationCookie);
        ctx.Authentication.SignIn(applicationCookieIdentity);

生成机器密钥,并将其添加到webAPI和ASP.Net MVC站点的web.config中.

Generate a machine key and add it in web.config of your webAPI and ASP.Net MVC site.

使用此方法将创建一个cookie,并且MVC站点和WebAPI中的[Authorize]属性将支持该cookie.

With this a cookie will be created and [Authorize] attribute in MVC Site and WebAPI will honor this cookie.

P.S. -我通过发布JWT(授权服务器或Auth&资源服务器)的Web API做到了这一点,并且能够在ASP.Net MVC网站,Angular内置的SPA站点,python内置的安全API(资源服务器)中成功使用, spring(资源服务器),Android应用程序.

P.S. - I have done this with a web API issuing JWT (Authorization server or Auth & resource server) and successfully able to consume in a ASP.Net MVC website, SPA Site built in Angular , secure APIs built in python (resource server) , spring (resource server), Android App.

这篇关于将Web API Cookie用作MVC Cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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