0

0

使用 AAD 和 AWS Cognito 为不同端点保护 Spring Boot REST API

王林

王林

发布时间:2024-02-22 13:22:06

|

1070人浏览过

|

来源于stackoverflow

转载

php小编百草为您精心撰写了一篇关于使用aad和aws cognito保护spring boot rest api的java问答文章。在这篇文章中,我们将探讨如何利用这两种身份验证服务来保护不同端点,确保您的api安全可靠。跟随我们的指引,学习如何在您的spring boot项目中实现身份验证和授权,让您的rest api更加强大和可靠。

问题内容

希望有人可以在这里帮助我,因为我在任何地方都找不到有关此主题的任何资源。

我有一个 spring boot restapi,当前配置有两种路由:1. 未经授权 2. 通过 aad/entra 的 bearer 授权

我的配置方法当前设置如下:

@override
protected void configure(httpsecurity http) throws exception {
        super.configure(http);
        http.csrf().disable();
        http.authorizerequests(requests -> requests
                .antmatchers(httpmethod.options, "/**/**").permitall()
                .antmatchers("/api/protected/**").fullyauthenticated()
                .anyrequest().permitall()
        );
}

它包装在一个扩展 aadresourceserverwebsecurityconfigureradapter 的类中。

通过以这种方式配置我们的 api,我们能够按如下方式保护我们的路由:

@preauthorize("hasauthority('approle_appname.rolename')")
@getmapping(value = "/some-method", produces = mediatype.application_json_value)
public responseentity> getstrings() {
    return responseentity.ok(...);
}

我们的 api 现在应该进行扩展,以允许新型用户使用授权端点。这些用户由 aws cognito 管理。如何设置我的 websecurityconfigureradapter 以允许某些路径未经授权,某些路径通过 aad 进行保护,某些路径通过 aws cognito 进行保护?

我似乎遇到的主要问题是 aadresourceserverwebsecurityconfigureradapter 以这样的方式配置 jwt 验证,它仅适用于 microsoft 提供的 bearers。

理想情况下我想要这样的东西:

@configuration
@enablewebsecurity
@enableglobalmethodsecurity(prepostenabled = true)
public class securityconfig extends websecurityconfigureradapter { 

    @configuration
    @order(1)
    public static class azureadsecurityconfig extends aadresourceserverwebsecurityconfigureradapter {

        @override
        protected void configure(httpsecurity http) throws exception {
            http.authorizerequests(requests -> requests
                    .antmatchers("/api/aad/**").fullyauthenticated()
            );
            http.oauth2resourceserver().jwt([utilize aad jwt validation]);
        }

    }

    @configuration
    @order(2)
    public static class awscognitosecurityconfig extends websecurityconfigureradapter {

        @override
        protected void configure(httpsecurity http) throws exception {
            http.authorizerequests(requests -> requests
                    .antmatchers("/api/cognito/**").fullyauthenticated()
            );
            http.oauth2resourceserver().jwt([utilize aws cognito jwt validation]);
        }
    }

    @configuration
    @order(3)
    public static class defaultsecurityconfig extends websecurityconfigureradapter {

            @override
            protected void configure(httpsecurity http) throws exception {
                http.csrf().disable();
                http.authorizerequests(requests -> requests
                        .antmatchers(httpmethod.options, "/**/**").permitall()
                        .anyrequest().permitall()
                );
            }
    }

}

我发现的另一个问题是 aadresourceserverwebsecurityconfigureradapter 自动将 jwtclaimnames“roles”和“scp”的所有可能的前缀设置为“scope_”和“approle_”。理想情况下,我希望 aad 和 aws cognito 的它们有所不同,以便我将“aad_scope_”、“aad_approle_”和“cognito_group_”作为前缀。

我找到了一些资料解释如何为 spring boot 实现多租户 jwt 验证,但它们都仅使用 sql 数据库实现基于密码/用户的身份验证。

有没有办法基本上必须重新实现所有 aad 逻辑,以便我可以混合对 aws cognito 给出的 jwt 的验证,或者有没有办法根据路由进行决定?

我已经知道您可以在 httpsecurity 上使用 oauth2resourceserver() 函数来配置 jwt 使用情况,但我只找到有关如何为单个租户实现该功能的信息。

如果有人已经成功实施了这个特定或类似的案例,或者可以将我推向正确的方向,我将非常感激。 或者也许我的想法是完全错误的,那么请告诉我。

使用工作解决方案更新(2024 年 1 月 25 日)

感谢 @ch4mp 的回答,我已经成功了。 >工作答案

现在我的实现已经高度简化,如下所示:

Magician
Magician

Figma插件,AI生成图标、图片和UX文案

下载

应用程序.yml

com:
  c4-soft:
    springaddons:
      oidc:
        ops:
          - iss: https://cognito-idp..amazonaws.com/
            authorities:
              - path: $.cognito:groups
                prefix: cognito_group_
          - iss: https://sts.windows.net//
            authorities:
              - path: $.roles.*
                prefix: aad_approle_
              - path: $.scp
                prefix: aad_scope_
            aud: 
        resource-server:
          permit-all:
            - /api/route/noauth

安全配置

package some.package;

import org.springframework.context.annotation.configuration;
import org.springframework.security.config.annotation.method.configuration.enablemethodsecurity;
import org.springframework.security.config.annotation.web.configuration.enablewebsecurity;

@enablewebsecurity
@enablemethodsecurity
@configuration
public class securityconfig { }

我的控制器现在看起来像这样:

package some.package;


import org.springframework.http.responseentity;
import org.springframework.security.access.prepost.preauthorize;
import org.springframework.security.core.context.securitycontextholder;
import org.springframework.security.oauth2.jwt.jwt;
import org.springframework.web.bind.annotation.getmapping;
import org.springframework.web.bind.annotation.requestmapping;
import org.springframework.web.bind.annotation.restcontroller;

@restcontroller
@requestmapping("/api/route")
public class jwttestcontroller {

    @getmapping("/aadauth")
    @preauthorize("hasauthority('aad_approle_grantedapprole.xxx')")
    public responseentity aadauthrole() {
        jwt jwt = (jwt) securitycontextholder.getcontext().getauthentication().getprincipal();
        return responseentity.ok(jwt.getclaims().tostring());
    }

    @getmapping("/aadauth")
    @preauthorize("hasauthority('aad_scope_grantedscope.xxx')")
    public responseentity aadauthscope() {
        jwt jwt = (jwt) securitycontextholder.getcontext().getauthentication().getprincipal();
        return responseentity.ok(jwt.getclaims().tostring());
    }

    @preauthorize("hasauthority('cognito_group_somegroup')")
    @getmapping("/cognitoauth")
    public responseentity cognitoauth() {
        jwt jwt = (jwt) securitycontextholder.getcontext().getauthentication().getprincipal();
        return responseentity.ok(jwt.getclaims().tostring());
    }

    @getmapping("/noauth")
    public responseentity noauth() {
        return responseentity.ok("hello world!");
    }

}

构建.gradle

implementation 'org.springframework.boot:spring-boot-starter-oauth2-resource-server'
    implementation 'com.c4-soft.springaddons:spring-addons-starter-oidc:7.3.5'

不是 spring 的官方启动器,而是 oss 实现:https://www.php.cn/link/49844ba129a1cbc3d964703fcdb756ba

如果我遇到任何其他问题,我会再次更新,但目前它正在工作。

解决方法

我将在这里公开一个使用 my starter 的解决方案,因为它更容易。

如果您更喜欢仅使用“官方”spring boot 启动器构建安全配置,则必须使用 iss 声明提供自己的 authenticationmanagerresolver,每个身份验证管理器都有自己的身份验证转换器和自己的权限转换器来处理源声明和您想要的前缀。浏览 my tutorialsofficial documentation 以获取示例和实施提示。 This other answer 也可以提供帮助(权限映射要求完全不同,但身份验证管理器解析器类似)。

使用 boot 3.2.2 和 spring-addons



    4.0.0
    
        org.springframework.boot
        spring-boot-starter-parent
        3.2.2
         
    
    com.c4-soft.demo
    multi-tenant-resource-server
    0.0.1-snapshot

    
        21
        7.3.5
    

    
        
            org.springframework.boot
            spring-boot-starter-oauth2-resource-server
        
        
            org.springframework.boot
            spring-boot-starter-web
        
        
            com.c4-soft.springaddons
            spring-addons-starter-oidc
            ${spring-addons.version}
        

        
            com.c4-soft.springaddons
            spring-addons-starter-oidc-test
            ${spring-addons.version}
            test
        
    

    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
        
    


@configuration
@enablemethodsecurity
public class securityconf {
}

编辑以下 application.yaml 以放置您自己的发行者:

com:
  c4-soft:
    springaddons:
      oidc:
        ops:
        - iss: https://cognito-idp.us-west-2.amazonaws.com/us-west-2_rzhmglwjl
          authorities:
          - path: $.cognito:groups
            prefix: cognito_group_
        - iss: https://sts.windows.net/0a962d63-6b23-4416-81a6-29f88c553998/
          authorities:
          - path: $.approles.*.displayname
            prefix: aad_approle_
          - path: $.scope
            prefix: aad_scope_
        resourceserver:
          # spring-addons whitelist is for permitall() (rather than isauthenticated())
          # which is probably much safer
          permit-all:
          - /actuator/health/readiness
          - /actuator/health/liveness
          - /v3/api-docs/**
          - /api/public/**

上面 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 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"
}

本站声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

相关专题

更多
java
java

Java是一个通用术语,用于表示Java软件及其组件,包括“Java运行时环境 (JRE)”、“Java虚拟机 (JVM)”以及“插件”。php中文网还为大家带了Java相关下载资源、相关课程以及相关文章等内容,供大家免费下载使用。

832

2023.06.15

java正则表达式语法
java正则表达式语法

java正则表达式语法是一种模式匹配工具,它非常有用,可以在处理文本和字符串时快速地查找、替换、验证和提取特定的模式和数据。本专题提供java正则表达式语法的相关文章、下载和专题,供大家免费下载体验。

737

2023.07.05

java自学难吗
java自学难吗

Java自学并不难。Java语言相对于其他一些编程语言而言,有着较为简洁和易读的语法,本专题为大家提供java自学难吗相关的文章,大家可以免费体验。

734

2023.07.31

java配置jdk环境变量
java配置jdk环境变量

Java是一种广泛使用的高级编程语言,用于开发各种类型的应用程序。为了能够在计算机上正确运行和编译Java代码,需要正确配置Java Development Kit(JDK)环境变量。php中文网给大家带来了相关的教程以及文章,欢迎大家前来阅读学习。

397

2023.08.01

java保留两位小数
java保留两位小数

Java是一种广泛应用于编程领域的高级编程语言。在Java中,保留两位小数是指在进行数值计算或输出时,限制小数部分只有两位有效数字,并将多余的位数进行四舍五入或截取。php中文网给大家带来了相关的教程以及文章,欢迎大家前来阅读学习。

398

2023.08.02

java基本数据类型
java基本数据类型

java基本数据类型有:1、byte;2、short;3、int;4、long;5、float;6、double;7、char;8、boolean。本专题为大家提供java基本数据类型的相关的文章、下载、课程内容,供大家免费下载体验。

446

2023.08.02

java有什么用
java有什么用

java可以开发应用程序、移动应用、Web应用、企业级应用、嵌入式系统等方面。本专题为大家提供java有什么用的相关的文章、下载、课程内容,供大家免费下载体验。

430

2023.08.02

java在线网站
java在线网站

Java在线网站是指提供Java编程学习、实践和交流平台的网络服务。近年来,随着Java语言在软件开发领域的广泛应用,越来越多的人对Java编程感兴趣,并希望能够通过在线网站来学习和提高自己的Java编程技能。php中文网给大家带来了相关的视频、教程以及文章,欢迎大家前来学习阅读和下载。

16925

2023.08.03

Java 桌面应用开发(JavaFX 实战)
Java 桌面应用开发(JavaFX 实战)

本专题系统讲解 Java 在桌面应用开发领域的实战应用,重点围绕 JavaFX 框架,涵盖界面布局、控件使用、事件处理、FXML、样式美化(CSS)、多线程与UI响应优化,以及桌面应用的打包与发布。通过完整示例项目,帮助学习者掌握 使用 Java 构建现代化、跨平台桌面应用程序的核心能力。

36

2026.01.14

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号