簡體   English   中英

在MVC和Web Api中進行Owin認證

[英]Owin Authentication In MVC and Web Api

我正在嘗試在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);
  }

在MVC控制器中一切正常,但我不能在我的Web API控制器上使用[Authorize(Roles =“Administrator”)屬性並使其正常工作。它始終讓我通過。

謝謝

編輯:只有我能夠解決這個問題的方法是使用靜態類和屬性存儲IPrincipal,然后在覆蓋授權屬性時,查找該屬性並檢查角色是否存在。 我不確定這是不是一個好主意?

您的身份驗證代碼在哪里寫? 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);
   }

你可以在這里找到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控制器中對其進行反序列化並從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);

這樣就可以創建一個cookie,並且MVC站點和WebAPI中的[Authorize]屬性將尊重這個cookie。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM