我是Open ID,Identity Server和构建API的新手, 我已经设置了一个Identity Server 3和API以及客户端,我的服务器将为客户端提供访问令牌,在调用API时可以使用它 服务器启动是
public void Configuration (IAppBuilder app)
{
var options = new IdentityServerOptions
{
Factory = new IdentityServerServiceFactory()
.UseInMemoryClients(Clients.Get())
.UseInMemoryScopes(Scopes.Get())
.UseInMemoryUsers(Users.Get()),
RequireSsl = false
};
app.UseIdentityServer(options);
}
和我的API启动
public void Configuration(IAppBuilder app)
{
//accept access token from indentityserver and require a scope of api1
app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
{
Authority = "http://localhost:62172/",
ValidationMode = ValidationMode.ValidationEndpoint,
RequiredScopes = new[] { "api1" }
});
//config web api
var config = new HttpConfiguration();
config.MapHttpAttributeRoutes();
// require authentication for all controllers
config.Filters.Add(new AuthorizeAttribute());
app.UseWebApi(config);
}
我的问题是为什么当我使用
[Route("api/Search")]
它的工作方式与使用[授权]
相同[Route("api/Search")]
public async Task<IHttpActionResult> Companies(SearchRequest searchRequest)
{
}
为什么上面的打击代码如下:
[Authorize]
public async Task<IHttpActionResult> Companies(SearchRequest searchRequest)
{}
更多信息
在我的控制器中这是我正在调用的方法,我试图强制用户进行授权
public async Task<IHttpActionResult> Companies(SearchRequest searchRequest)
{
var caller = User as ClaimsPrincipal;
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
HttpResponseMessage response = new HttpResponseMessage();
Framework.BusinessLogicFactory factory = new Framework.BusinessLogicFactory();
BusinessLogic.Search search = factory.CreateSearch();
}
但是如果我在控制器上没有[Authorize]或[Route(“api / Sreach”)]属性,那么对API的任何调用都会得到结果, 这就是我测试API的方式
string APiURL = "http://localhost:59791/api/Search";
var responses = GetClientToken();
var clinet = new HttpClient();
var value = new Dictionary<string, string>()
{
{ "CompanyNumber", " " },
{ "CompanyName", "test" },
{ "Address1", " " },
{ "Address2", " " },
{ "Address3", " " },
{ "PostCode", " " },
{ "CountryCode", " " },
};
var content = new FormUrlEncodedContent(value);
var response = await clinet.PostAsync(APiURL, content);
var t = response.StatusCode;
答案 0 :(得分:1)
因为您在API初创公司中有config.Filters.Add(new AuthorizeAttribute());
行。
这会将[Authorize]
应用于所有控制器。所以它不是[Route]
导致授权被应用但是这个过滤器。