.net core6 实现oauth2.0服务端,含JWT
时间: 2023-07-11 12:39:41 浏览: 97
在.NET Core 6中实现OAuth2.0服务端,包括JWT,与.NET Core 5的实现方式基本相同。以下是一个简单的示例:
1. 创建一个ASP.NET Core Web API项目。
2. 安装IdentityServer4和Microsoft.AspNetCore.Authentication.JwtBearer NuGet包。
3. 在Startup.cs中配置IdentityServer,并添加JwtBearer认证。示例代码如下:
```csharp
public void ConfigureServices(IServiceCollection services)
{
// 添加IdentityServer服务
services.AddIdentityServer()
.AddInMemoryClients(Config.Clients)
.AddInMemoryApiResources(Config.Apis)
.AddDeveloperSigningCredential();
// 添加JwtBearer认证
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.Authority = "http://localhost:5000"; // IdentityServer地址
options.RequireHttpsMetadata = false; // HTTPS设置为false,方便测试
options.Audience = "api1"; // API资源名称
});
services.AddControllers();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseRouting();
app.UseIdentityServer();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
```
4. 创建客户端和API资源,并将它们添加到IdentityServer中。示例代码如下:
```csharp
public static class Config
{
public static IEnumerable<Client> Clients => new List<Client>
{
new Client
{
ClientId = "client1",
ClientSecrets = { new Secret("secret1".Sha256()) },
AllowedGrantTypes = GrantTypes.ClientCredentials,
AllowedScopes = { "api1" }
}
};
public static IEnumerable<ApiResource> Apis => new List<ApiResource>
{
new ApiResource("api1", "My API")
};
}
```
5. 实现授权终结点。示例代码如下:
```csharp
[HttpPost]
[Route("/connect/token")]
public async Task<IActionResult> Token([FromBody] TokenRequest request)
{
if (request.GrantType == "password")
{
var user = _userService.ValidateCredentials(request.UserName, request.Password);
if (user != null)
{
var accessToken = await _tokenService.CreateAccessTokenAsync(user);
return Ok(new
{
access_token = accessToken,
token_type = "Bearer",
expires_in = (int)_tokenService.Options.Expiration.TotalSeconds
});
}
}
return BadRequest(new
{
error = "unsupported_grant_type"
});
}
```
6. 实现API资源的保护。示例代码如下:
```csharp
[Authorize]
[HttpGet]
[Route("test")]
public IActionResult Test()
{
return Ok(new
{
message = "Hello, World!"
});
}
```
以上是一个基本的OAuth2.0服务端实现,包括JWT。你可以根据自己的需求进行调整和扩展。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)
![](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)
![7z](https://img-home.csdnimg.cn/images/20210720083312.png)