2017-06-09 100 views
1

我試圖實施OAuth2身份驗證和授權。我有一個授權服務器和一個資源服務器。客戶端登錄授權服務器(將用戶名和密碼發送給授權服務器),授權服務器返回access_token。客戶端使用access_token來請求resource_server中具有[Authorize]標籤的資源。OAuth2 401未經授權從資源服務器

身份驗證部分(向授權服務器發送憑證並取回access_token)工作正常。我得到一個有效的JWT令牌。 問題是資源服務器無法識別access_token。每次客戶端發送請求以獲取具有[Authorize]標籤的資源時,我都會收到:'401未授權的授權已被拒絕'

這是我嘗試過的事情的清單/驗證:

  1. 我查Microsoft.Owin.Security.OAuth既資源和授權服務器上的版本完全相同(2.1.0版本)
  2. 我檢查了client_id和secret在資源和授權服務器上是完全相同的版本
  3. 我確保在資源和授權服務器上有完全相同的機器密鑰(在web.config文件中有相同的值,在iis)
  4. 我檢查了iis啓用匿名身份驗證(並禁用任何其他形式的身份驗證)
  5. 我的CORS處處啓用
  6. 這兩臺服務器位於同一臺計算機上。
  7. 我驗證請求到資源服務器和令牌的Authorization頭髮送這樣的:Authorization:JWT eyJ0eXAiO.......JuRpuf6yWg
  8. 我送與郵差同樣的請求,但我得到了同樣的答覆

我實現基於這兩個教程:

  1. http://bitoftech.net/2014/09/24/decouple-owin-authorization-server-resource-server-oauth-2-0-web-api/
  2. http://bitoftech.net/2014/10/27/json-web-token-asp-net-web-api-2-jwt-owin-authorization-server/

這是我的資源服務器的Startup.cs類:

using Microsoft.Owin.Cors; 
using Microsoft.Owin.Security; 
using Microsoft.Owin.Security.DataHandler.Encoder; 
using Microsoft.Owin.Security.Jwt; 
using Microsoft.Owin.Security.OAuth; 
using Owin; 
using System.Threading.Tasks; 
using System.Web.Http; 
using Web.Api.App_Start; 

namespace Web.Api 
{ 
    public class Startup 
    { 
     public void Configuration(IAppBuilder app) 
     { 
      HttpConfiguration config = new HttpConfiguration(); 
      ConfigureOAuth(app); 
      app.UseAutofacMiddleware((newAutofacContainer()) 
        .ConfigureContainer(config)); 
      app.UseCors(CorsOptions.AllowAll); 
      WebApiConfig.Register(config); 
      app.UseWebApi(config); 
     } 

     public void ConfigureOAuth(IAppBuilder app) 
     { 
      var issuer = "http://localhost:81/Auth.Server"; 
      var audience = "AUDIENCE"; 
      var secret = TextEncodings.Base64Url.Decode("SECRET"); 
      app.UseJwtBearerAuthentication(
       new JwtBearerAuthenticationOptions 
       { 
        AuthenticationMode = AuthenticationMode.Active, 
        AllowedAudiences = new[] { audience }, 
        IssuerSecurityTokenProviders = new 
          IIssuerSecurityTokenProvider[] 
          { 
          new SymmetricKeyIssuerSecurityTokenProvider(issuer, 
           secret) 
          }, 
        Provider = new OAuthBearerAuthenticationProvider 
        { 
         OnValidateIdentity = context => 
         { 
          context.Ticket.Identity.AddClaim(new 
           System.Security 
           .Claims.Claim("newCustomClaim", "newValue")); 
          return Task.FromResult<object>(null); 
         } 
        } 
       }); 

     } 
    } 
} 
+0

[解決]:應該是授權:**持票人** eyJ0eXAiO ....... JuRpuf6yWg(持票人不是JWT!) –

回答

0

[解決]:應該是Authorization:Bearer eyJ0eXAiO.......JuRpuf6yWg承載不智威湯遜!)

相關問題