amc*_*dnl 26 .net c# asp.net-web-api asp.net-web-api2
我的应用程序设置为必须使用Web API中的授权属性"授权"除登录之外的所有请求.例如
[Authorize]
[HttpGet, Route("api/account/profile")]
public ApplicationUser Profile()
{
return userModel;
}
Run Code Online (Sandbox Code Playgroud)
并且只有登录需要不授权,因为那里你得到令牌;)
[AllowAnonymous]
[HttpPost, Route("api/account/login")]
public async Task<IHttpActionResult> Login(LoginViewModel model)
{
....
}
Run Code Online (Sandbox Code Playgroud)
而不是必须将[Authorize]
属性添加到我的所有路由,有没有办法全局设置它?
ssi*_*777 50
你有两个选择
通过使用authorize属性修饰控制器来控制器级别.
[Authorize]
[RoutePrefix("api/account")]
public class AccountController : ApiController
{
Run Code Online (Sandbox Code Playgroud)您还可以在Register
WebApiConfig.cs文件的方法中将其全局级别设置为所有路由
config.Filters.Add(new AuthorizeAttribute());
Run Code Online (Sandbox Code Playgroud)Lin*_*Lin 21
您可以设置AuthorizeAttribute
到WebApiConfig
类似下面的文件:
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.Filters.Add(new AuthorizeAttribute());
}
Run Code Online (Sandbox Code Playgroud)
现在,您的Web Api控制器中的所有方法都需要授权.如果要删除方法的此授权要求,则需要[AllowAnonymous]
像Login操作方法一样添加属性.
vol*_*kit 14
自 ASP.NET Core 3.0 起,有一种新方法可以通过使用端点路由中间件来无需过滤器来执行此操作,请参阅: https: //learn.microsoft.com/en-gb/aspnet/core/migration/22-to-30 ?view=aspnetcore-5.0&tabs=visual-studio#authorization
如果尚不存在,则需要添加以下内容:
services.UseAuthentication(); // with authentication scheme
app.UseAuthentication();
app.UseAuthorization(); // this is enough, because DefaultPolicy is to require authentication
Run Code Online (Sandbox Code Playgroud)
以及端点中间件:
endpoints.MapControllers().RequireAuthorization();
Run Code Online (Sandbox Code Playgroud)
JWT 身份验证方案的示例:
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options =>
{
options.RequireHttpsMetadata = false;
options.SaveToken = true;
options.TokenValidationParameters = new TokenValidationParameters()
{
ValidateIssuer = true,
ValidIssuer = Configuration["Jwt:Issuer"],
ValidateAudience = false,
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"]))
};
});
}
public void Configure(IApplicationBuilder app)
{
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers().RequireAuthorization();
});
}
Run Code Online (Sandbox Code Playgroud)
您仍然可以允许[AllowAnonymous]
在控制器或操作上进行匿名访问(例如,用于用户登录)。
在 ASP.NET Core Web API 中,它是这样的:
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers(o =>
{
var policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
o.Filters.Add(new AuthorizeFilter(policy));
});
}
Run Code Online (Sandbox Code Playgroud)
来源:https://joonasw.net/view/apply-authz-by-default
归档时间: |
|
查看次数: |
22296 次 |
最近记录: |