mirror of
https://github.com/nsnail/IGeekFan.AspNetCore.Knife4jUI.git
synced 2025-09-19 07:42:42 +08:00
@@ -0,0 +1,58 @@
|
||||
using System.Collections.Generic;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
|
||||
namespace OAuth2Integration.ResourceServer.Controllers
|
||||
{
|
||||
[Route("products")]
|
||||
[Authorize(AuthenticationSchemes = "Bearer")]
|
||||
public class ProductsController : Controller
|
||||
{
|
||||
[HttpGet]
|
||||
[Authorize("readAccess")]
|
||||
public IEnumerable<Product> GetProducts()
|
||||
{
|
||||
yield return new Product
|
||||
{
|
||||
Id = 1,
|
||||
SerialNo = "ABC123",
|
||||
};
|
||||
}
|
||||
|
||||
[HttpGet("{id}")]
|
||||
[Authorize("readAccess")]
|
||||
public Product GetProduct(int id)
|
||||
{
|
||||
return new Product
|
||||
{
|
||||
Id = 1,
|
||||
SerialNo = "ABC123",
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
[HttpPost]
|
||||
[Authorize("writeAccess")]
|
||||
public void CreateProduct([FromBody]Product product)
|
||||
{
|
||||
}
|
||||
|
||||
[HttpDelete("{id}")]
|
||||
[Authorize("writeAccess")]
|
||||
public void DeleteProduct(int id)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
public class Product
|
||||
{
|
||||
public int Id { get; internal set; }
|
||||
public string SerialNo { get; set; }
|
||||
public ProductStatus Status { get; set; }
|
||||
}
|
||||
|
||||
public enum ProductStatus
|
||||
{
|
||||
InStock, ComingSoon
|
||||
}
|
||||
}
|
@@ -0,0 +1,40 @@
|
||||
using System.Linq;
|
||||
using System.Collections.Generic;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.OpenApi.Models;
|
||||
using Swashbuckle.AspNetCore.SwaggerGen;
|
||||
|
||||
namespace OAuth2Integration.ResourceServer.Swagger
|
||||
{
|
||||
public class SecurityRequirementsOperationFilter : IOperationFilter
|
||||
{
|
||||
public void Apply(OpenApiOperation operation, OperationFilterContext context)
|
||||
{
|
||||
// Policy names map to scopes
|
||||
var requiredScopes = context.MethodInfo
|
||||
.GetCustomAttributes(true)
|
||||
.OfType<AuthorizeAttribute>()
|
||||
.Select(attr => attr.Policy)
|
||||
.Distinct();
|
||||
|
||||
if (requiredScopes.Any())
|
||||
{
|
||||
operation.Responses.Add("401", new OpenApiResponse { Description = "Unauthorized" });
|
||||
operation.Responses.Add("403", new OpenApiResponse { Description = "Forbidden" });
|
||||
|
||||
var oAuthScheme = new OpenApiSecurityScheme
|
||||
{
|
||||
Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "oauth2" }
|
||||
};
|
||||
|
||||
operation.Security = new List<OpenApiSecurityRequirement>
|
||||
{
|
||||
new OpenApiSecurityRequirement
|
||||
{
|
||||
[ oAuthScheme ] = requiredScopes.ToList()
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user