AAD 및 AWS Cognito를 사용하여 다양한 엔드포인트에 대한 Spring Boot REST API 보안
php 편집자 Baicao는 AAD 및 AWS Cognito를 사용하여 Spring Boot REST API를 보호하는 방법에 대한 Java Q&A 기사를 신중하게 작성했습니다. 이 기사에서는 이 두 가지 인증 서비스를 활용하여 다양한 엔드포인트를 보호하고 API가 안전한지 확인하는 방법을 살펴보겠습니다. 가이드를 따라 Spring Boot 프로젝트에서 인증 및 권한 부여를 구현하여 REST API를 더욱 강력하고 안정적으로 만드는 방법을 알아보세요.
질문 내용
이 주제에 대한 리소스를 어디에서도 찾을 수 없으므로 누군가가 나를 도와줄 수 있기를 바랍니다.
스프링 부트 Restapi가 있고 현재 구성에는 두 가지 경로가 있습니다: 1. 승인되지 않음 2. aad/entra 전달자를 통해 승인됨
내 구성 방법은 현재 다음과 같이 설정되어 있습니다.
으아악확장된 클래스aadresourceserverwebsecurityconfigureradapter
로 포장되어 있습니다.
이러한 방식으로 API를 구성하면 다음과 같이 경로를 보호할 수 있습니다.
으아악이제 새로운 유형의 사용자가 인증 엔드포인트를 사용할 수 있도록 API가 확장되어야 합니다. 이러한 사용자는 aws cognito에 의해 관리됩니다. 일부 경로를 무단으로 허용하고, 일부 경로를 aad를 통해 보호하고, 일부 경로를 aws cognito를 통해 보호하도록 websecurityconfigureradapter
를 설정하려면 어떻게 해야 합니까?
내가 겪고 있는 주요 문제는 aadresourceserverwebsecurityconfigureradapter
Microsoft에서 제공하는 전달자에서만 작동하도록 jwt 유효성 검사를 구성하는 것입니다.
이상적으로는 다음과 같은 것을 원합니다:
으아악내가 발견한 또 다른 문제는 aadresourceserverwebsecurityconfigureradapter
jwtclaimnames "roles" 및 "scp"에 대해 가능한 모든 접두사를 "scope_" 및 "approle_"로 자동 설정하는 것입니다. 이상적으로는 "aad_scope_", "aad_approle_" 및 "cognito_group_"이라는 접두사를 붙이도록 aad와 aws cognito에 대해 서로 다르기를 바랍니다.
스프링 부트에 대해 다중 테넌트 jwt 인증을 구현하는 방법을 설명하는 정보를 찾았지만 모두 SQL 데이터베이스만 사용하여 비밀번호/사용자 기반 인증을 구현합니다.
aws cognito에서 제공하는 jwt 검증을 혼합할 수 있도록 기본적으로 모든 aad 로직을 다시 구현해야 하는 방법이 있습니까, 아니면 라우팅을 기반으로 결정을 내리는 방법이 있습니까?
httpsecurity
上使用 oauth2resourceserver()
함수에서 jwt 사용을 구성할 수 있다는 것을 이미 알고 있지만 단일 테넌트에 대해 해당 기능을 구현하는 방법에 대한 정보만 찾았습니다.
이 특정 사례나 유사한 사례를 성공적으로 구현한 사람이 있거나 나를 올바른 방향으로 이끌 수 있는 사람이 있다면 매우 감사하겠습니다. 아니면 내 생각이 완전히 틀렸을 수도 있으니 알려주세요.
작업 솔루션 업데이트 사용(2024년 1월 25일)
@ch4mp님의 답변 덕분에 성공했습니다. >작업 답변<
내 구현은 이제 매우 단순화되었으며 다음과 같습니다.
application.yml
으아악보안 구성
으아악내 컨트롤러는 이제 다음과 같습니다:
으아악build.gradle
으아악This는 봄의 공식 런처가 아니지만 OSS 구현: https://www.php.cn/link/49844ba129a1cbc3d964703fcdb756ba
다른 문제가 발생하면 다시 업데이트하겠지만 현재로서는 작동합니다.
Solution
여기서 my starter를 사용하여 솔루션을 공개하겠습니다. 왜냐하면 더 쉽기 때문입니다.
보안 구성을 구축하기 위해 "공식" 스프링 부트 스타터만 사용하려는 경우 iss
声明提供自己的 authenticationmanagerresolver<httpservletrequest>를 사용해야 합니다. 각 인증 관리자에는 소스 클레임을 처리하기 위한 자체 인증 변환기와 권한 변환기가 있으며 필수 접두사가 필요합니다. 예제와 구현 팁을 보려면 <a href="https://www.php.cn/link/49844ba129a1cbc3d964703fcdb756ba/tree/master/samples/tutorials" rel="nofollow noreferrer">내 튜토리얼</a> 또는 <a href="https://www.php.cn/link/37841383bc8c327de7912cf44790f3fd" rel="nofollow noreferrer">공식 문서</a>를 찾아보세요. <a href="https://www.php.cn/link/945a1b4276b1524763d2acc19dc8c475">이 다른 답변</a>도 도움이 될 수 있습니다(권한 매핑 요구 사항은 완전히 다르지만 인증 관리자 확인자는 비슷합니다). </p>
<h3 id="부팅-code-code-및-스프링-애드온">부팅<code>3.2.2
및 스프링 애드온을 사용하세요.
으아악
으아악
다음을 편집하여 application.yaml
나만의 출판사를 배치하세요.
위의 path
값은 json 경로입니다. jsonpath.com과 같은 도구를 사용하여 자체 토큰 페이로드(jwt.io와 같은 도구를 사용하여 추출)에 대해 경로 표현식을 테스트할 수 있습니다.
네, 정말 간단해요. 아니요, yaml 속성이나 Java 구성을 생략하지 않았습니다. 제 말을 믿지 못하시면 새 프로젝트에서 테스트해 보세요.
示例控制器
@restcontroller public class greetcontroller { @getmapping("/greet") @preauthorize("isauthenticated()") public string getgreet(authentication auth) { return "hello %s! you are granted with %s.".formatted(auth.getname(), auth.getauthorities()); } @getmapping(value = "/strings") @preauthorize("hasanyauthority('aad_approle_admin', 'cognito_group_admin')") public list<string> getstrings() { return list.of("protected", "strings"); } }
示例测试
@webmvctest(controllers = greetcontroller.class) @autoconfigureaddonswebmvcresourceserversecurity @import(securityconf.class) class greetcontrollertest { @autowired mockmvcsupport api; @test @withanonymoususer void givenuserisanonymous_whengetgreet_thenunauthorized() throws unsupportedencodingexception, exception { api.get("/greet").andexpect(status().isunauthorized()); } @test @withjwt("aad_admin.json") void givenuserisaadadmin_whengetgreet_thenok() throws unsupportedencodingexception, exception { final var actual = api.get("/greet").andexpect(status().isok()).andreturn().getresponse().getcontentasstring(); assertequals( "hello aad-admin! you are granted with [aad_approle_msiam_access, aad_approle_admin, aad_scope_openid, aad_scope_profile, aad_scope_machin:truc].", actual); } @test @withjwt("cognito_admin.json") void givenuseriscognitoadmin_whengetgreet_thenok() throws unsupportedencodingexception, exception { final var actual = api.get("/greet").andexpect(status().isok()).andreturn().getresponse().getcontentasstring(); assertequals("hello amazon-cognito-admin! you are granted with [cognito_group_admin, cognito_group_machin:truc].", actual); } @test @withjwt("aad_machin-truc.json") void givenuserisaadmachintruc_whengetgreet_thenok() throws unsupportedencodingexception, exception { final var actual = api.get("/greet").andexpect(status().isok()).andreturn().getresponse().getcontentasstring(); assertequals("hello aad-user! you are granted with [aad_approle_msiam_access, aad_scope_openid, aad_scope_profile, aad_scope_machin:truc].", actual); } @test @withjwt("cognito_machin-truc.json") void givenuseriscognitomachintruc_whengetgreet_thenok() throws unsupportedencodingexception, exception { final var actual = api.get("/greet").andexpect(status().isok()).andreturn().getresponse().getcontentasstring(); assertequals("hello amazon-cognito-user! you are granted with [cognito_group_machin:truc].", actual); } @test @withanonymoususer void givenuserisanonymous_whengetstrings_thenunauthorized() throws unsupportedencodingexception, exception { api.get("/strings").andexpect(status().isunauthorized()); } @test @withjwt("aad_admin.json") void givenuserisaadadmin_whengetstrings_thenok() throws unsupportedencodingexception, exception { final var actual = api.get("/strings").andexpect(status().isok()).andreturn().getresponse().getcontentasstring(); assertequals("[\"protected\",\"strings\"]", actual); } @test @withjwt("cognito_admin.json") void givenuseriscognitoadmin_whengetstrings_thenok() throws unsupportedencodingexception, exception { final var actual = api.get("/strings").andexpect(status().isok()).andreturn().getresponse().getcontentasstring(); assertequals("[\"protected\",\"strings\"]", actual); } @test @withjwt("aad_machin-truc.json") void givenuserisaadmachintruc_whengetstrings_thenforbidden() throws unsupportedencodingexception, exception { api.get("/strings").andexpect(status().isforbidden()); } @test @withjwt("cognito_machin-truc.json") void givenuseriscognitomachintruc_whengetstrings_thenforbidden() throws unsupportedencodingexception, exception { api.get("/strings").andexpect(status().isforbidden()); } }
使用此测试资源:
aad_admin.json
{ "sub": "aad-admin", "iss": "https://sts.windows.net/0a962d63-6b23-4416-81a6-29f88c553998/", "approles": [ { "allowedmembertypes": [ "user" ], "description": "msiam_access", "displayname": "msiam_access", "id": "ef7437e6-4f94-4a0a-a110-a439eb2aa8f7", "isenabled": true, "origin": "application", "value": null }, { "allowedmembertypes": [ "user" ], "description": "administrators only", "displayname": "admin", "id": "4f8f8640-f081-492d-97a0-caf24e9bc134", "isenabled": true, "origin": "serviceprincipal", "value": "administrator" } ], "scope": "openid profile machin:truc" }
aad_machin-truc.json
{ "sub": "aad-user", "iss": "https://sts.windows.net/0a962d63-6b23-4416-81a6-29f88c553998/", "approles": [ { "allowedmembertypes": [ "user" ], "description": "msiam_access", "displayname": "msiam_access", "id": "ef7437e6-4f94-4a0a-a110-a439eb2aa8f7", "isenabled": true, "origin": "application", "value": null } ], "scope": "openid profile machin:truc" }
cognito_admin.json
{ "sub": "amazon-cognito-admin", "iss": "https://cognito-idp.us-west-2.amazonaws.com/us-west-2_rzhmglwjl", "cognito:groups": ["admin", "machin:truc"], "scope": "openid profile cog:scope" }
cognito_machin-truc.json
{ "sub": "amazon-cognito-user", "iss": "https://cognito-idp.us-west-2.amazonaws.com/us-west-2_RzhmgLwjl", "cognito:groups": ["machin:truc"], "scope": "openid profile cog:scope" }
위 내용은 AAD 및 AWS Cognito를 사용하여 다양한 엔드포인트에 대한 Spring Boot REST API 보안의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

예, H5 페이지 제작은 HTML, CSS 및 JavaScript와 같은 핵심 기술을 포함하는 프론트 엔드 개발을위한 중요한 구현 방법입니다. 개발자는 & lt; canvas & gt; 그래픽을 그리거나 상호 작용 동작을 제어하기 위해 JavaScript를 사용하는 태그.

인라인 블록 요소의 잘못 정렬 된 디스플레이에 대한 이유와 솔루션과 관련하여. 웹 페이지 레이아웃을 작성할 때, 우리는 종종 이상하게 겉보기에 이상한 디스플레이 문제가 발생합니다. 비교하다...

CSS에서 크기 조정 기호를 사용자 정의하는 방법은 배경색으로 통합됩니다. 매일 개발에서, 우리는 종종 조정과 같은 사용자 인터페이스 세부 정보를 사용자 정의 해야하는 상황을 발생시킵니다.

브라우저의 인쇄 설정에서 페이지의 상단과 끝을 제어하기 위해 JavaScript 또는 CSS를 사용하는 방법. 브라우저의 인쇄 설정에는 디스플레이가 ...인지 제어 할 수있는 옵션이 있습니다.

세그먼터의 45도 곡선 효과를 달성하는 방법은 무엇입니까? 세분화 장치를 구현하는 과정에서 왼쪽 버튼을 클릭 할 때 오른쪽 테두리를 45도 곡선으로 바꾸는 방법과 포인트 ...

실시간 비트 코인 USD 가격 비트 코인 가격에 영향을 미치는 요인 향후 비트 코인 가격을 예측하기위한 지표 다음은 2018-2024 년 비트 코인 가격에 대한 몇 가지 주요 정보입니다.

VUE 2.0을 사용하여 모바일 애플리케이션을 개발할 때 다른 장치에서 멀티 로우 오버플로의 호환성 문제가 종종 텍스트를 넘어서야 할 필요성을 만듭니다 ...

사용자 인터페이스 디자인에서 세그먼트 효과를 구현하기위한 팁, 세그먼터는 특히 모바일 애플리케이션 및 반응 형 웹 페이지에서 일반적인 탐색 요소입니다. ...