首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何使用IdentityServer4保护内置在.Net框架4.x中的Asp.Net WebApi

如何使用IdentityServer4保护内置在.Net框架4.x中的Asp.Net WebApi
EN

Stack Overflow用户
提问于 2020-02-13 13:58:27
回答 2查看 1.4K关注 0票数 1

我使用Identity Server4设置了身份验证服务器,但我无法在.Net framework 4.5.2内置的WebApi中使用Identity Server4发出的令牌。虽然我能够保护核心内置的Web Api。

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

提前谢谢。

最佳,Tarun Ohri

EN

回答 2

Stack Overflow用户

发布于 2020-02-13 15:36:43

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

所以我找到了一个解决方法。您可以安装IdentityServer3.AccessTokenValidation NuGet程序包以在WebApi中验证您的ID4令牌。有关更多详细信息,请参阅以下示例代码:

代码语言:javascript
运行
复制
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中间件将验证您的请求。我希望这能帮助你解决你的问题。

票数 1
EN

Stack Overflow用户

发布于 2020-02-24 14:13:38

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

startup.cs

代码语言:javascript
运行
复制
[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控制器类

代码语言:javascript
运行
复制
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项目中的客户端配置

代码语言:javascript
运行
复制
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项目。

代码语言:javascript
运行
复制
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);
}
);
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60201322

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档