首页 文章

IdentityServer,ASP.NET Core和Web API

提问于
浏览
0

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

我已按照步骤从此示例实现客户端凭据流https://identityserver.github.io/Documentation/docsv2/overview/simplestOAuth.html

现在我完全迷失了如何让WEB API首先识别Bearer令牌,然后给我一些授权来访问web api endpoints .

这是我的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配置(IAppBuilder应用程序)方法中设置什么设置 .

1 回答

  • 1

    首先,您必须向您的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 . 这就是您指定权限的地方,即(这意味着)您的Identity-Server以及您在IdentityServers启动文件中指定的范围 . 如果您还想添加自定义AuthorizationManager(例如,为了授权特定角色,您需要在API的启动中在“UseIdentityServerBearer ...”之前添加以下行:

    app.UseResourceAuthorization(new AuthorizationManager());
    

    AuthorizationManager是由您自己通过继承类 ResourceAuthorizationManager 实现的类 . 但我不愿意更深入地去)

    在您的API控制器中,如果需要授权整个控制器,您只需在上面或类级别授权访问的方法上添加 [Authorize] 属性 . (如果要使用例如角色身份验证,则需要 [ResourceAuthorize] .

    如果您有其他问题或想知道随时可以询问

相关问题