【问题标题】:How to secure Asp.Net WebApi built in .Net Framework 4.x using IdentityServer4如何使用 IdentityServer4 保护 .Net Framework 4.x 中内置的 Asp.Net WebApi
【发布时间】:2020-05-28 18:39:10
【问题描述】:

我使用 Identity Server 4 设置了我的身份验证服务器,但我无法在 .Net 框架 4.5.2 中构建的 WebApi 中使用 Identity Server 4 发出的令牌。虽然我能够保护 Core 中内置的 Web Api。

谁能指导我如何做到这一点,因为我们的 .Net Api 是一个遗留应用程序,我们无法将其转换为核心 API。

提前致谢。

最好, 塔伦·奥里

【问题讨论】:

    标签: asp.net-web-api jwt identityserver4 openid-connect jwt-auth


    【解决方案1】:

    我相信您正在寻找可以在 WebApi 中验证您的令牌的中间件。几天前我遇到了这个问题,我无法安装 IdentityServer4.AccessTokenValidation NuGet 包,因为它是在 .NET 核心中开发的。

    所以我找到了解决方法。您可以安装IdentityServer3.AccessTokenValidation NuGet 包以在 WebApi 中验证您的 ID4 令牌。详情请看下面的示例代码:

    Startup.cs
    
    public void Configuration(IAppBuilder app)
            {
    
                    IdentityServerBearerTokenAuthenticationOptions options = new IdentityServerBearerTokenAuthenticationOptions
                    {
                        Authority = "Identity Server 4 base URL",
                        AuthenticationType = "Bearer",
                        RequiredScopes = "Scopes (space separated)"
                    };
              app.UseIdentityServerBearerTokenAuthentication(options);
            }
    

    注意:UseIdentityServerBearerTokenAuthentication 中间件将验证您的请求。希望这能帮助您解决问题。

    【讨论】:

    • 感谢您的回复。我已尝试按照您的建议进行操作,但无法通过。请查看我共享的代码并指导我哪里出错了。感谢您!塔伦·奥里
    【解决方案2】:

    @Mahesh More 请看看下面的代码并指导我哪里出错了:

    startup.cs

    [assembly: OwinStartup(typeof(AspNet_4_5_2_API.Startup))]
    namespace AspNet_4_5_2_API
    {
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
    
            IdentityServerBearerTokenAuthenticationOptions options = new IdentityServerBearerTokenAuthenticationOptions
            {
                Authority = "http://localhost:5000",
                AuthenticationType = "Bearer",
                RequiredScopes = new[] { "api1" }
            };
            app.UseIdentityServerBearerTokenAuthentication(options);
        }
    }
    }
    

    API 控制器类

    namespace AspNet_4_5_2_API.Controllers
    {
    [Route("identity")]
    public class IdentityController : ApiController
    {
        [HttpGet]
        public IHttpActionResult Get()
        {
            var identity = (ClaimsIdentity)User.Identity;
            IEnumerable<Claim> claims = identity.Claims;
    
            return Ok(claims);
        }
    }
    }
    

    Identity Server 项目中的客户端配置

    public static IEnumerable<ApiResource> GetApis()
        {
            return new List<ApiResource>
            {
                new ApiResource("api1", "My API")
            };
        }
    
        public static IEnumerable<Client> GetClients()
        {
            return new List<Client>
        {            
            // JavaScript Implicit Client
            new Client
            {
                ClientId = "client_id_js",
                AllowedGrantTypes = GrantTypes.Implicit,
    
                RedirectUris = { "http://localhost:5004/home/signin" },
                PostLogoutRedirectUris = { "http://localhost:5004/home/index" },
                AllowedCorsOrigins =     { "http://localhost:5004" },
    
                AllowedScopes =
                {
                    IdentityServerConstants.StandardScopes.OpenId,
                    IdentityServerConstants.StandardScopes.Profile,
                    "api1", "tenant", "dateofbirth"
                },
    
                //AccessTokenLifetime = 1, //! second for testing
                AlwaysIncludeUserClaimsInIdToken = true,
    
                AllowAccessTokensViaBrowser = true,
                RequireConsent = false
            }
        };
        }
    

    Javascript 客户端代码。在这个 callApi 函数中调用的是 Web API 项目。

    var config = {
    userStore: new Oidc.WebStorageStateStore({ store: window.localStorage }),
    authority: "http://localhost:5000",
    client_id: "client_id_js",
    redirect_uri: "http://localhost:5004/Home/SignIn",
    response_type: "id_token token",
    scope: "openid api1 dateofbirth tenant",
    post_logout_redirect_uri: "http://localhost:5004/Home/Index"
    };
    var userManager = new Oidc.UserManager(config);
    
    var signIn = function () {
    userManager.signinRedirect();
    };
    
    var signOut = function () {
    userManager.signoutRedirect();
    };
    
    userManager.getUser().then(user => {
    console.log("user : ", user);
    if (user) {
        axios.defaults.headers.common["Authorization"] = "Bearer " + user.access_token;
    }
    });
    
    
    var callApi = function () {
    axios.get("http://localhost:59502/api/identity").then(result => {
        console.log(result);
    });
    };
    
    var refreshing = false;
    
    axios.interceptors.response.use(
    function (response) { return response; },
    function (error) {
        console.log("axios error: ", error.response);
    
        var axiosConfig = error.response.config;
    
        // if error response is 401 try to refresh token
        if (error.response.status === 401) {
            console.log("axios error 401");
            // if already refreshing dont make another request
            if (!refreshing) {
                console.log("starting token refresh");
                refreshing = true;
    
                // do the refresh
                return userManager.signinSilent().then(user => {
                    console.log("new user:", user);
    
                    //update the http request and client
                    axios.defaults.headers.common["Authorization"] = "Bearer " + user.access_token;
                    axiosConfig.headers["Authorization"] = "Bearer " + user.access_token;
    
                    //retry the http request
                    return axios(axiosConfig);
                });
            }
        }
    
        return Promise.reject(error);
    }
    );
    

    【讨论】:

    • 嘿,我检查了您的客户端配置,一切看起来都不错,但除非您分享您的确切错误消息,否则我无法弄清楚您的问题。您能否解释一下您在使用此配置时遇到的确切问题?
    • @Mahesh 更多,感谢您的及时回复。我已经解决了这个问题。实际上,我的 Web API 项目中缺少一个库。 :) 如果有人遇到同样的问题,请确保在您的 web api 项目中安装了这些库:Install-Package Microsoft.Owin.Host.SystemWeb -ProjectName Api Install-Package Microsoft.Owin.Cors -ProjectName Api Install-Package Microsoft.AspNet.WebApi.Owin -ProjectName Api Install-Package IdentityServer3.AccessTokenValidation -ProjectName Api
    • @MaheshMore 你对此有什么意见吗[链接]stackoverflow.com/questions/60445614/…
    猜你喜欢
    • 2021-03-01
    • 2020-11-04
    • 1970-01-01
    • 2020-07-28
    • 1970-01-01
    • 1970-01-01
    • 2018-09-13
    • 2013-09-21
    • 1970-01-01
    相关资源
    最近更新 更多