繁体   English   中英

IdentityServer,ASP.NET Core和Web API

[英]IdentityServer, ASP.NET Core and Web API

我已经设置了IdentityServer4和另一个客户端ASP.NET Core应用程序。 客户端需要通过IdentityServer进行身份验证,并请求访问第三个应用程序,该应用程序是标准MVC Web API项目。

我已按照以下示例步骤执行操作,以从此示例https://identityserver.github.io/Documentation/docsv2/overview/simplestOAuth.html获得客户端凭据流

现在,我完全不知道如何获取WEB API,以便首先识别Bearer令牌,然后再授予我一些访问Web api端点的授权。

这是我的IdentityServer Statrup.cs

public class Startup
{
    public Startup(IHostingEnvironment env)
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
            .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);

        builder.AddEnvironmentVariables();
        Configuration = builder.Build();
    }

    public IConfigurationRoot Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddIdentityServer()
                .AddInMemoryStores()
                .AddInMemoryClients(Config.GetClients())
                .AddInMemoryScopes(Config.GetScopes());           
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        loggerFactory.AddConsole(LogLevel.Debug);
        app.UseDeveloperExceptionPage();

        app.UseIdentityServer();
    }
}

和Config.cs

 public class Config
{
    // scopes define the resources in your system
    public static IEnumerable<Scope> GetScopes()
    {
        return new List<Scope>
        {
            new Scope
            {
                Name = "api1"
            }
        };
    }

    // clients want to access resources (aka scopes)
    public static IEnumerable<Client> GetClients()
    {
        // client credentials client
        return new List<Client>
        {
            // no human involved
        new Client
        {
            ClientName = "Silicon-only Client",
            ClientId = "silicon",
            Enabled = true,
            AccessTokenType = AccessTokenType.Reference,

            AllowedGrantTypes = GrantTypes.ClientCredentials,

            ClientSecrets = new List<Secret>
            {
                new Secret("F621F470-9731-4A25-80EF-67A6F7C5F4B8".Sha256())
            },

            AllowedScopes = new List<string>
            {
                "api1"
            }
        }
        };
    }}

ASP.NET Core对IdentityServer和Web API的调用

[Route("api/testing")]
    public class TestingController : Controller
    {
        // GET: api/values

        [HttpGet]
        public IActionResult Get()
        {
            var responce = GetClientToken();

            return Json(new
            {
                message = CallApi(responce)
            });
        }

        static TokenResponse GetClientToken()
        {
            var client = new TokenClient(
                Constants.TokenEndpoint,
                "silicon",
                "F621F470-9731-4A25-80EF-67A6F7C5F4B8");

            return client.RequestClientCredentialsAsync("api1").Result;
        }

        static string CallApi(TokenResponse response)
        {
            var client = new HttpClient
            {
                BaseAddress = new Uri(Constants.AspNetWebApiSampleApi),
                Timeout = TimeSpan.FromSeconds(10)
            };
            client.SetBearerToken(response.AccessToken); 
            try
            {                  
                var auth = client.GetStringAsync().Result;
                return auth;
            }
            catch (Exception ex)
            {
                return ex.Message;

            }
        }  
    }

因此,任何人都可以解释或共享一些链接,以说明如何使WEB APi(带有owin中间件)处理来自ASP.NET Core客户端的调用? 我应该在Owin Configuration(IAppBuilder app)方法中输入什么设置。

首先,您必须向api-scope添加一个ScopeType,因为您的API正在处理资源,因此您需要添加ScopeType.Resource,如果您想在MVC-Client上显示同意屏幕,还应该添加一个显示名称和如果您需要在api上进一步声明,请在声明中添加声明列表:

new Scope
{
    Name = "api",
    DisplayName = "Your scopes display name",
    Type = ScopeType.Resource,
    Claims = new List<ScopeClaim>
    {
        new ScopeClaim("role")
    }
}

在您的api项目中,您还必须添加OwinStartup类,因为那是您告诉api使用承载令牌授权的地方:在“启动配置”中:

app.UseIdentityServerBearerTokenAuthentication(
    new IdentityServerBearerTokenAuthenticationOptions
    {
        Authority = "YourIdentityServersAddress.com/identity",
        RequiredScopes = new[] { "api" },
     });
 app.UseWebApi(WebApiConfig.Register());

最后一行只是注册您的webapi-config。 在那指定您的权限,即(即)您的身份服务器和在IdentityServers启动文件中指定的范围。 如果您还想添加自定义AuthorizationManager(例如,用于授权特定角色,则需要在API的启动中的“ UseIdentityServerBearer ...”之前添加以下行:

app.UseResourceAuthorization(new AuthorizationManager());

其中AuthorizationManager是您可以通过从类ResourceAuthorizationManager继承来自己实现的类。 但我不想对此进行深入了解(如果您对此有进一步的疑问,我将很乐意进行深入介绍)

如果需要要求对整个控制器进行授权,则只需在API的控制器上将[Authorize]属性添加到您不想在类级别或在类级别进行授权访问的方法上方即可。 (如果要使用例如角色身份验证,则需要[ResourceAuthorize]

如果您还有其他问题或想知道,请随时提问

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM