>  기사  >  AAD 및 AWS Cognito를 사용하여 다양한 엔드포인트에 대한 Spring Boot REST API 보안

AAD 및 AWS Cognito를 사용하여 다양한 엔드포인트에 대한 Spring Boot REST API 보안

王林
王林앞으로
2024-02-22 13:22:06870검색

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님의 답변 덕분에 성공했습니다. >작업 답변05f297c713c84d8206bc0da44d89a1aa를 사용해야 합니다. 각 인증 관리자에는 소스 클레임을 처리하기 위한 자체 인증 변환기와 권한 변환기가 있으며 필수 접두사가 필요합니다. 예제와 구현 팁을 보려면 내 튜토리얼 또는 공식 문서를 찾아보세요. 이 다른 답변도 도움이 될 수 있습니다(권한 매핑 요구 사항은 완전히 다르지만 인증 관리자 확인자는 비슷합니다).

부팅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 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
이 기사는 stackoverflow.com에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제