IdentityServer, ASP.NET Core and Web API
本文关键字:and Web API Core NET ASP IdentityServer | 更新日期: 2023-09-27 18:11:53
我已经设置了IdentityServer4和另一个客户端ASP。. NET Core应用程序。客户端需要使用IdentityServer进行身份验证,并请求访问第三个应用程序,该应用程序是标准MVC Web API项目。
我遵循了这个示例中实现Client Credentials Flow的步骤https://identityserver.github.io/Documentation/docsv2/overview/simplestOAuth.html
现在我完全失去了如何让WEB API首先识别承载令牌,然后给我一些授权来访问WEB API端点。
这是我的IdentityServer statrupp .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核心对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(与自己的中间件)来处理来自ASP的调用。. NET Core客户端?我应该把什么设置在Owin配置(IAppBuilder应用程序)方法。
首先,你必须添加一个ScopeType到你的api-scope,当你的API处理资源时,你需要添加ScopeType。资源,如果你想在mvc客户端显示同意屏幕,你还应该添加一个显示名称,如果你需要在api中进一步声明,将它们与声明列表一起添加:
new Scope
{
Name = "api",
DisplayName = "Your scopes display name",
Type = ScopeType.Resource,
Claims = new List<ScopeClaim>
{
new ScopeClaim("role")
}
}
在你的api项目中,你还必须添加一个OwinStartup类,因为这是你告诉你的api使用承载令牌授权的地方:在Startup配置中:
app.UseIdentityServerBearerTokenAuthentication(
new IdentityServerBearerTokenAuthenticationOptions
{
Authority = "YourIdentityServersAddress.com/identity",
RequiredScopes = new[] { "api" },
});
app.UseWebApi(WebApiConfig.Register());
最后一行只是注册你的webapi-config。这就是你指定权限的地方,即(这意味着)你的身份服务器和你在身份服务器启动文件中指定的范围。如果你还想添加一个自定义AuthorizationManager(例如,为特定角色授权),你需要在API启动时的"UseIdentityServerBearer…"之前添加以下行:
app.UseResourceAuthorization(new AuthorizationManager());
其中AuthorizationManager是一个类,您可以通过继承类ResourceAuthorizationManager自己实现。但是我不想深入讨论这个(如果你有更多的问题,我很乐意深入讨论)
在你的API的控制器,你只需要添加[授权]属性上面的方法,你不想有授权访问或在类级别,如果你的整个控制器应该被要求被授权。如果你想使用角色认证,你需要[ResourceAuthorize]。
如果您有其他问题或想知道,请随时问