Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ionic-framework/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Asp.net mvc 将web api cookie用于mvc cookie_Asp.net Mvc_Asp.net Web Api - Fatal编程技术网

Asp.net mvc 将web api cookie用于mvc cookie

Asp.net mvc 将web api cookie用于mvc cookie,asp.net-mvc,asp.net-web-api,Asp.net Mvc,Asp.net Web Api,我正在使用WebAPI2和MVC5制作一个web应用程序 我的应用程序有api: api/account/login,用于检查发布的信息,并在授予帐户访问应用程序时抛出状态200 另外,我有一个视图:/Home/Index,它只对经过身份验证的客户端可用 现在,我的方法是: 调用api/account/login,接收从该api抛出的cookie 将抛出的cookie附加到浏览器 当用户访问/Home/Index时,视图对他/她可用 我的问题是: -我的方法可行吗? -如何像MVC 5对其c

我正在使用WebAPI2和MVC5制作一个web应用程序

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

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

现在,我的方法是:

  • 调用api/account/login,接收从该api抛出的cookie
  • 将抛出的cookie附加到浏览器
  • 当用户访问/Home/Index时,视图对他/她可用
我的问题是:

-我的方法可行吗?

-如何像MVC 5对其cookie那样在Web API 2中加密cookie?

谢谢,

一旦用户通过帐户控制器的身份验证,您就可以设置

public class AccountController 
{
   public HttpResponseMessage Login() 
   {         
      // Your authentication logic

      var responseMessage = new HttpResponseMessage();

      var cookie = new CookieHeaderValue("session-id", "12345");
      cookie.Expires = DateTimeOffset.Now.AddDays(1);
      cookie.Domain = Request.RequestUri.Host;
      cookie.Path = "/";

      responseMessage.Headers.AddCookies(new CookieHeaderValue[] { cookie });
      return responseMessage;
   }
}
要进行身份验证,您可以将
[authenticate]
属性放在
主控制器上

public class HomeController
{
    [Authenticate]
    public ActionResult Index() 
    {
       return View();
    }
}
如果需要,还可以在控制器级别应用Authenticate属性

[Authenticate]
public class HomeController
{
}
如果需要,您还可以通过覆盖和检查有效cookie来创建自己的授权属性:

public class CustomAuth : AuthenticationAttribute
{
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        HttpCookie authCookie = httpContext.Request.Cookies["CookieName"];

        // Your logic
        return true;
    }
}

实现这一点的最佳方法是在MVC项目中使用授权服务器(生成令牌的webAPI)和令牌消费中间件。IdentityServer应该会有所帮助。然而,我已经这样做了如下

使用JWT和WEB API以及ASP.Net标识构建了一个授权服务器,如下所述

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

/// 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);
在MVC控制器中,当您收到令牌时,将其反序列化并从访问令牌生成cookie

        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);
AccessClaims claimsToken=new AccessClaims();
claimsToken=JsonConvert.DeserializeObject(response.Content);
claimsToken.Cookie=response.Cookies[0]。值;
添加(“授权”、“承载人”+claimsToken.access_令牌);
var ctx=Request.GetOwinContext();
var authenticateResult=等待ctx.Authentication.authenticateSync(“JWT”);
ctx.认证.注销(“JWT”);
var applicationcokieeidentity=new ClaimsIdentity(authenticateResult.Identity.Claims,DefaultAuthenticationTypes.applicationcokie);
ctx.Authentication.SignIn(applicationCookieIdentity);
生成机器密钥并将其添加到webAPI和ASP.Net MVC站点的web.config中

有了这个cookie,MVC站点中的[Authorize]属性将被创建,WebAPI将尊重这个cookie


另外,我已经通过发布JWT(授权服务器或Auth&resource服务器)的web API完成了这项工作,并成功地在ASP.Net MVC网站、内置角度的SPA网站、内置python(资源服务器)的安全API、spring(资源服务器)和安卓应用程序中使用

你能核对一下我的答案吗。我遗漏了什么吗?别忘了web.config(或计算机上)中的
system.web/machineKey
属性在不同的服务器上使用时必须相等。感谢您提供有关我问题的链接。你的答案解释得很好。我有一个简短的问题,您将如何在win form应用程序中使用它?如果它是一个独立的应用程序,不与远程数据库/API交互,那么令牌方法将不会有帮助,如果它与API交互,那么您可以有一个API(比如AuthAPI)生成令牌,另一个API(ResourceAPI)它可以使用AuthAPI生成的令牌并获取数据。ResourceAPI的所有方法都受[Authorize]保护属性。现在1)在winforms中设置登录屏幕2)登录按钮将进行AuthAPI调用并获取需要存储在winform中的令牌3)对ResourceAPI的后续API调用应使用从以前的AuthAPI调用接收的令牌添加授权标头。因此,整个想法是设计类似于移动应用程序的winform。(很抱歉使用标点符号,由于字符限制,必须使用标点符号)
        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);