这种方式没用啊,我用的是.net core的WebApi
时间: 2024-03-13 18:46:36 浏览: 22
对于 Web API,可以使用类似的方式来保护需要登录的 API 接口。在方法上加上 `[Authorize]` 属性标记,表示只有登录后的用户才能访问该接口。同时,在 Startup.cs 文件的 ConfigureServices 方法中配置身份验证和授权服务,例如:
```csharp
public void ConfigureServices(IServiceCollection services)
{
// 添加身份验证服务
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = Configuration["Jwt:Issuer"],
ValidAudience = Configuration["Jwt:Audience"],
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"]))
};
});
// 添加授权服务
services.AddAuthorization(options =>
{
options.AddPolicy("RequireAuthenticatedUser", policy => policy.RequireAuthenticatedUser());
});
// 注册其他服务
services.AddControllers();
}
```
这里使用 JWT Token 进行身份验证,需要在 appsettings.json 文件中配置 Jwt 相关的参数。然后在需要登录的 API 接口上加上 `[Authorize]` 属性标记,例如:
```csharp
[ApiController]
[Route("[controller]")]
public class MyController : ControllerBase
{
[Authorize(Policy = "RequireAuthenticatedUser")]
[HttpGet]
public IActionResult MyMethod()
{
// 需要登录才能访问的代码
}
}
```
这样就可以保证 `MyMethod` 接口必须登录才能访问。如果用户没有登录,访问该接口会返回 401 Unauthorized 错误。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)