Asp.net WebApi(non core) + IdentityServer4搭建過程


 

 

 

最近項目要引用identityserver 4來進行多客戶端身份驗證,按照官網的教程,搭建了基於asp.net core的WebApi+MVC的客戶端,但是項目中有非core的asp.net webapi,官網上沒有例子,自己調查了一下,將搭建步驟記錄一下,以備之后參考。

 

  • 在webapi項目中添加Owin Startup啟動類Startup.cs,之后通過NuGet安裝Microsoft.Owin.Host.SystemWeb,不安裝的話將不會執行Startup的代碼
  • 在webapi項目中通過NuGetIdentityServer3.AccessTokenValidation,官網教程中core的webapi中安裝的是IdentityServer4.AccessTokenValidation ,但是該插件基於core的開發的,non core的webapi不能使用。這里兼容性不用擔心,無論IdentityServer3還是IdentityServer4只是符合相同協議的實現, 這同樣適用於那些TokenValidation中間件。也就是說,可以在一個AspNetCore API項目中使用IdentityServer4.AccessTokenValidation來驗證來自IdentityServer3項目的Token。 相反,也可以在一個AspNet API項目中使用dentityServer3.AccessTokenValidation來驗證來自IdentityServer4 AspNetCore項目的Token。
  • 在IdentityServer4的config中添加ApiResource代碼

 

return new[]
            {
                new ApiResource("ICPWebApi", "ICPWebApi")
                {
                    ApiSecrets = new List<Secret>()
                    {
                        new Secret("secret".Sha256())//.net core api中不需要此配置
                    }
 
                }
            }

 

  • 在identityServer4的config中添加一個Client用來生成Token訪問API

 

  public static IEnumerable<Client> GetClients()
        {
            return new[]
            {
                new Client
                {
                    ClientId = "Api",
                    ClientSecrets = new [] { new Secret("secret".Sha256()) },
                    AllowedGrantTypes = GrantTypes.ResourceOwnerPasswordAndClientCredentials,
                    AllowedScopes = new [] { "ICPWebApi" }
                },
            };
        }

 

在webApi的Startup的Configration中添加以下代碼

// 有關如何配置應用程序的詳細信息,請訪問 https://go.microsoft.com/fwlink/?LinkID=316888
            JwtSecurityTokenHandler.InboundClaimTypeMap.Clear();
            app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
            {
                Authority = "http://localhost:5000",//IdentityServer
                AuthenticationType = "Bearer",
                ClientId = "ICPWebApi",
                ValidationMode = ValidationMode.ValidationEndpoint,
                ClientSecret = "secret"
            });

在valuesController的Get方法添加Authorize屬性,然后運行項目,訪問api/values/ 會提示Message:已拒絕次請求授權,錯誤代碼401

通過Client獲取Token

 

 

 用獲取的token訪問api/Values,狀態200,訪問成功。

 

 最后需要注意在CoreWebApi中,可以不聲明Secret,但是在non core WebApi中需要在identityServer中設置Secret並且在WebApi中設定ClientSecret。

 

 

 

原文地址:https://blog.csdn.net/heyongsi/article/details/79984476


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM