在MVC和Web Api中进行Owin认证

Kry*_*ard 3 c# asp.net-web-api owin

我正在尝试在MVC控制器和Web Api控制器之间使用相同的身份验证.Web api位于/ Controllers/API /文件夹中的同一项目中.

我似乎无法弄清楚如何使用OWIN进行身份验证,当我通过MVC登录并创建声明和cookie时,如下例所示.

 var identity = new ClaimsIdentity(new[]
 {
  new Claim(ClaimTypes.Name,"Admin"),
  new Claim(ClaimTypes.Role,"Administrator")
  , "ApplicationCookie");

   var ctx = Request.GetOwinContext();
   var authManager = ctx.Authentication;
   authManager.SignIn(identity);
   return RedirectToAction("Index", "Home", null);
  }
Run Code Online (Sandbox Code Playgroud)

在MVC控制器中一切正常,但我不能在我的Web API控制器上使用[Authorize(Roles ="Administrator")属性并使其正常工作.它始终让我通过.

谢谢

编辑:只有我能够解决这个问题的方法是使用静态类和属性存储IPrincipal,然后在覆盖授权属性时,查找该属性并检查角色是否存在.我不确定这是不是一个好主意?

Rav*_* A. 6

您的身份验证代码在哪里写?MVC控制器或Web API控制器?我建议你在你的web API控制器中使用它,以后可以将它用于任何其他应用程序(SPA或任何其他Web应用程序).你需要构建一个授权服务器/资源服务器模型(抱歉我的英语不是确定如何构建这句话).在您的情况下,Web API是两者,MVC站点是资源服务器.

下面是JWT + Cookie中间件的示例

使用带有WEB API和ASP.Net Identity的JWT构建授权服务器,如此处所述http://bitoftech.net/2015/02/16/implement-oauth-json-web-tokens-authentication-in-asp-net-web -API和-身份-2 /

一旦你这样做,你的webAPIs 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);
   }
Run Code Online (Sandbox Code Playgroud)

你可以在这里找到CustomOAuthProvider,CustomJwtFormat类https://github.com/tjoudeh/AspNetIdentity.WebApi/tree/master/AspNetIdentity.WebApi/Providers

在你的MVC应用程序中,在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)                           
                }

            });
    }
Run Code Online (Sandbox Code Playgroud)

在接收令牌时,在MVC控制器中对其进行反序列化并从acceSs令牌生成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);
Run Code Online (Sandbox Code Playgroud)

这样就可以创建一个cookie,并且MVC站点和WebAPI中的[Authorize]属性将尊重这个cookie.