Auth0으로 .NET 6 Minimal API 보안
13342 단어 authenticationsecurityapiwebdev
이 경우 공식 설명서link를 따르거나 최소 API 및 ASP.NET Core에 대한 Microsoft Learn 경로link를 따르도록 제안할 수 있습니다.
최소 API 프로젝트 만들기
명령 프롬프트에서 직접 Minimal API 프로젝트를 생성할 수 있습니다.
즐겨찾는 터미널(저는 Windows 터미널 사용)을 열고 다음 명령을 실행합니다.
dotnet new webapi -minimal -o SampleAuth0
그런 다음 SampleAuth0 디렉터리로 전환하고 VS Code(또는 Visual Studio 2022)를 시작합니다.

새 API 끝점 추가
Minimal API의 템플릿에는 "/weatherforecast"경로가 있는 하나의 GET 엔드포인트만 포함됩니다.

기본 끝점 아래에 아래 코드를 추가하여 다른 끝점을 추가합니다(이 예에서는 WeatherForecast 모델이 있는 POST).
app.MapPost("/weatherforecast", (WeatherForecast forecast) =>
{
return forecast;
})
.WithName("PostWeatherForecast");
애플리케이션을 실행하고 url/swagger로 이동하면 새 API에 대한 Swagger 문서가 표시됩니다.

Auth0 계정에서 API 생성
먼저 Auth0 대시보드에서 Auth0 API를 생성해야 합니다.
계정이 없는 경우 계정을 만들 수 있습니다here.
Auth0 Dashboard 에서 응용 프로그램 -> API로 이동하고 오른쪽 창에서 API 생성 버튼을 클릭합니다.

새 창에서 이름, 식별자(웹 API의 URL이어야 함) 및 서명 알고리즘에 대한 데이터를 삽입합니다.

프로젝트 구성
Microsoft.AspNetCore.Authentication.JwtBearer라는 프로젝트에 NuGet 패키지를 추가합니다.
이제 Program.cs 파일에 다음 코드를 추가할 준비가 되었습니다.
builder.Services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(options =>
{
options.Authority = builder.Configuration["Auth0:Domain"];
options.Audience = builder.Configuration["Auth0:Audience"];
});
builder.Services.AddAuthorization(o =>
{
o.AddPolicy("weatherforecast:read-write", p => p.
RequireAuthenticatedUser().
RequireClaim("permissions", "weatherforecast:read-write"));
});
app.UseAuthentication();
app.UseAuthorization();
Program.cs 파일의 16행에 이 코드 조각을 삽입할 수 있습니다.
appsettings.json 파일에서 아래 JSON 섹션을 추가하고 자리 표시자를 Auth0 애플리케이션의 값으로 바꿉니다.
"Auth0": {
"Domain": "<YOUR_DOMAIN>",
"Audience": "https://www.yourapp.com"
}
각 엔드포인트에서 다음 코드와 함께 정책을 추가합니다.
.RequireAuthorization("weatherforecast:read-write")
애플리케이션을 테스트하기 전에 Auth0 대시보드로 돌아가 API의 권한 탭으로 이동하여 정책을 추가합니다.

설정 탭으로 돌아와 액세스 토큰에 권한을 포함하도록 RBAC 및 설정을 활성화합니다.

이제 Machine to Machine Applications 탭에서 애플리케이션을 선택하고 weatherforecast:read-write 권한을 확인하고 Update 버튼을 클릭합니다.

테스트할 준비가 되었습니다.
우편 배달부로 테스트
보안을 테스트하는 빠르고 쉬운 방법 중 하나는 Postman 을 사용하는 것입니다.
해보자.
"테스트"탭을 클릭하고 access_token 값을 클립보드에 복사합니다.

준비가 되면 Postman을 열고 새 Get 요청을 만들고 API URL을 삽입합니다.
URL 텍스트 상자 아래에서 Authorization을 클릭하고 "Bearer Token"을 선택합니다.
클립보드의 액세스 토큰을 텍스트 상자에 붙여넣습니다.

이제 "보내기"를 클릭하면 아래 스크린샷과 같이 본문 결과에서 데이터를 볼 수 있습니다.

Swagger로 테스트하기
보안 및 Minimal API를 테스트하는 또 다른 방법이 있습니다.
Swagger를 사용할 수 있습니다. 몇 줄의 코드를 추가해야 하지만 그 후에는 프로젝트 내부에 모든 것이 있습니다.
이를 위해 Program.cs 파일의 7번 줄에 이러한 코드 줄을 추가할 수 있습니다.
builder.Services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo
{
Title = "SampleAuth0",
Version = "v1"
});
c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme()
{
Name = "Authorization",
Type = SecuritySchemeType.ApiKey,
Scheme = "Bearer",
BearerFormat = "JWT",
In = ParameterLocation.Header,
Description = "JWT Authorization header using the Bearer scheme. \r\n\r\n Enter 'Bearer' [space] and then your token in the text input below.\r\n\r\nExample: \"Bearer 1safsfsdfdfd\"",
});
c.AddSecurityRequirement(new OpenApiSecurityRequirement {
{
new OpenApiSecurityScheme {
Reference = new OpenApiReference {
Type = ReferenceType.SecurityScheme,
Id = "Bearer"
}
},
new string[] {}
}
});
});
이 코드 부분은 인증 버튼을 Swagger에 추가합니다.
애플리케이션의 디버그 세션을 시작하고 "/swagger"로 이동합니다.
보시다시피 오른쪽 상단에 "Authorize"라는 새 버튼이 있습니다.
그것을 클릭하고 지침을 따르십시오.
앞에 "Bearer"텍스트가 있는 텍스트 상자에 베어러를 붙여넣습니다(지침을 읽으십시오).
액세스 토큰을 검색하는 방법을 모르는 경우 이전 단락을 살펴보십시오.

이제 Swagger에서 직접 API를 테스트할 준비가 되었습니다.

결론
보시다시피 Minimal API 프로젝트에서 Auth0으로 인증 및 권한 부여를 구현하는 것은 매우 쉽습니다.
내 Gist 계정에서 코드를 찾을 수 있습니다: gist
Reference
이 문제에 관하여(Auth0으로 .NET 6 Minimal API 보안), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/kasuken/securing-net-6-minimal-api-with-auth0-4h5f텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념
(Collection and Share based on the CC Protocol.)