2016-07-01 73 views
3

我想在MVC控制器和Web Api控制器之间使用相同的认证。 Web api位于同一个项目中,位于/ Controllers/API /文件夹中。在MVC和Web Api中的Owin认证

我似乎无法弄清楚如何使用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); 
    } 

一切正常,在MVC控制器很好,但我不能用我的Web API控制器上的[授权(角色=“管理员”]属性,并已将其正常工作。它总是让我通过不管。

感谢

编辑:只有这样我已经能够解决这个问题是重写授权属性时,有一个静态类和属性存储的IPrincipal然后,查找财产和检查的作用是存在的我不知道这是不是一个好主意?

+0

你能检查我的答案吗? –

回答

5

您的验证码写在哪里? MVC控制器或Web API控制器?我建议将它用于您的Web API控制器,以便您可以稍后将其用于任何其他应用程序(SPA或任何其他Web应用程序)。您需要构建授权服务器/资源服务器模型(对不起,因为我的英文不是确定如何构造这个句子)。在你的情况下,Web API既是MVC站点,也是资源服务器。

以下是智威汤逊+饼干中间件

生成使用智威汤逊与WEB API和ASP.Net身份一旦你这样做,你的webAPIs startup.cs看起来这里http://bitoftech.net/2015/02/16/implement-oauth-json-web-tokens-authentication-in-asp-net-web-api-and-identity-2/

讲解了授权服务器的样本像下面

/// 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); 
    } 

你可以找到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)       
       } 

      }); 
    } 

在你的MVC控制器时,您会收到令牌解序列,并生成访问令牌

  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); 

有了这样的一个cookie cookie将被创建并且MVC站点中的[Authorize]属性和WebAPI将遵守这个cookie。