保护 Spring 支持,当前端使用 adal auth 保护时

2024-05-05

所以我们的应用程序有两个部分

  1. 前端 ui - 使用 Angular JS
  2. 后端 - 使用Spring boot的rest api

使用 microsoft-adal-angular6 库通过 Azure Active Directory 进行身份验证来保护前端

我的问题是保护后端安全的正确方法是什么,以便只有经过活动目录身份验证的用户才能访问 API?


我建议使用jwt 令牌 https://jwt.io/,它作为“授权”标头附加到后端的每个请求。该令牌由三部分组成,其中一部分保存有关用户的数据,另一部分保存签名,因此您可以验证您的令牌是否由可信来源创建。数据部分可能看起来像这样:

{
    "iss": "Online JWT Builder",
    "iat": 1580283510,
    "exp": 1611819510,
    "aud": "www.example.com",
    "sub": "[email protected] /cdn-cgi/l/email-protection",
    "GivenName": "Johnny",
    "roles": ["PROJECT_MANAGER", "ADMIN"]
    "scope": "WEBAPP"
}

在 Spring 方面,我建议使用具有最新配置的 Spring Security 5。 您将需要这些依赖项:

         <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-config</artifactId>
            <version>5.x.x.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-oauth2-jose</artifactId>
            <version>5.x.x.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-oauth2-resource-server</artifactId>
            <version>5.x.x.RELEASE</version>

现在您可以启用安全性并使用配置类对其进行配置。在里面,您可以定义请求必须具有的范围、如何签署令牌以及路由应该是公开的还是安全的。


@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Value("${spring.security.oauth2.resourceserver.jwt.jwk-set-uri}")
    String jwkSetUri;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // @formatter:off
        http
            .cors().disable()
            .authorizeRequests()
            .antMatchers(("/webapp/**")).hasAuthority("SCOPE_WEBAPP")
            .antMatchers(("/admin/**")).hasRole("ADMIN")
            ...
            .and()
            .oauth2ResourceServer().jwt(jwtConfigurer -> jwtConfigurer.decoder(jwtDecoder())
            .jwtAuthenticationConverter(new CustomJwtAuthenticationConverter()))
            ...
        // @formatter:on
    }

    @Bean
    JwtDecoder jwtDecoder() {
        return NimbusJwtDecoder.withJwkSetUri(jwkSetUri).build();
    }
}

我必须使用自定义 JwtConverter 从 jwt 获取角色,但这取决于您如何做到这一点,我想。

public class CustomJwtAuthenticationConverter implements Converter<Jwt, AbstractAuthenticationToken> {

    private final JwtGrantedAuthoritiesConverter defaultGrantedAuthoritiesConverter = new JwtGrantedAuthoritiesConverter();

    public CustomJwtAuthenticationConverter() {
    }

    @Override
    public AbstractAuthenticationToken convert(@NotNull final Jwt jwt) {
        Collection<GrantedAuthority> authorities = Stream
                .concat(defaultGrantedAuthoritiesConverter.convert(jwt).stream(), extractResourceRoles(jwt).stream())
                .collect(Collectors.toSet());
        return new JwtAuthenticationToken(jwt, authorities);
    }

    private static Collection<? extends GrantedAuthority> extractResourceRoles(final Jwt jwt) {
        Collection<String> userRoles = jwt.getClaimAsStringList("roles");
        if (userRoles != null)
            return userRoles
                    .stream()
                    .map(role -> new SimpleGrantedAuthority("ROLE_" + role))
                    .collect(Collectors.toSet());
        return Collections.emptySet();
    }
}

这使您能够基于 URL 保护您的应用程序。

jwt、to Jwt Converter 中的角色和@EnableGlobalMethodSecurity注释使您能够安全即使在方法级别 https://www.baeldung.com/spring-security-method-security.

@Transactional
@PreAuthorize("hasRole('ROLE_PROJECT_MANAGER')")
public Page<Project> findAll(Pageable pageable) {
    return projectRepository.findAll(pageable);
}

Azure Active Directory 应该支持智威汤逊 https://azure.microsoft.com/de-de/blog/windows-azure-active-directory-supports-json-web-tokens/,但我没有这个 IDP 的经验。 我无法回答的是,如何在令牌内注入自定义声明(例如角色)以及从哪里获取用于验证令牌签名的 jwks(Json Web 密钥集)。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

保护 Spring 支持,当前端使用 adal auth 保护时 的相关文章

随机推荐

  • 如何将日期格式设置为 (dd/mm/yyyy hh:mm:ss)

    如何将下面的日期转换为此模板 dd mm yyyy hh mm ss 05 04 2021 14 52 我尝试这样做 但我只得到时间 而不是日期和时间 var data new Date 05 04 2021 14 52 var time
  • 使用 Stringstream 将字符串转换为 Int

    这里有一个小问题 int IntegerTransformer transformFrom std string string stream gt clear std cout lt
  • 如何使用 MsBuild v15 构建 C++ 项目?

    我在 Visual Studio 2017 中使用 NuGet 包管理器安装了以下程序集 Microsoft Build Microsoft Build Framework Microsoft Build Utilities Core 一切
  • 尝试通过 API 将成员添加到 Google 群组时出现“缺少必填字段:成员”

    尝试使用 Google 管理目录 API 来读取 google 群组 组织 的成员 它工作正常 当我尝试添加成员时 我得到 errors domain global reason required message Missing requi
  • getline() 与 fgets():控制内存分配

    要从文件中读取行 有getline and fgets POSIX 函数 忽略可怕的gets 这是常识getline 优先于fgets 因为它根据需要分配行缓冲区 我的问题是 这不危险吗 如果有人意外或恶意地创建了一个 100GB 的文件
  • 如何按日期正确对从 CoreData 获取的列表进行分组?

    为了简单起见 假设我想创建一个简单的待办事项应用程序 我的 xcdatamodeld 中有一个实体 Todo 其属性id title and date 以及以下 swiftui 视图 如图所示的示例 import SwiftUI struc
  • Android 应用程序 Azure 依赖项 gradle 构建时出错

    我在 Android Studio 2 3 3 的 Gradle 同步中收到以下错误 错误 模块 com microsoft azure azure mobile android 3 3 0 依赖于一个或多个 Android 库 但它是一个
  • 将文件 Google Wear 发送到手机

    我正在尝试将文件从 Google Wear 发送到 Nexus 5 我已阅读一些教程并编写了以下代码 但我的手机未收到文件 Mobile private GoogleApiClient mGoogleApiClient private in
  • 带有路径连接器的 jQuery 可拖动小部件

    参考该图像 Block1 和Block2 都是可拖动的 我的问题是 如何在两个块之间制作红色链状连接器 要求是链条应该延伸到块被拖动的地方 请提供任何教程 学习材料的指示 谢谢 有许多 Jquery 插件可用于创建数据库可视化或流程图的连接
  • 在 Pandas 时间序列图中从 Axes.get_xlim() 获取可用日期

    我试图从用 pandas 创建的时间序列图中获取作为 python 日期时间对象的图的 xlimits 使用ax get xlim 将轴限制返回为numpy float64 我不知道如何将数字转换为可用的日期时间 import pandas
  • 当字段未触及时,角度反应形式返回空值

    在我的用例中 当用户单击编辑按钮时 Angular 会对后端进行 HTTP 调用并检索对象 然后在编辑表单上填充这些值 用户可以更新或保持字段不变 点击时update按钮 Angular 应该获取表单中存在的所有这些值并将它们发送到后端 因
  • 当单元格值和复选框更改时更改工作表

    我有一本包含多个工作表的工作簿 我有一个菜单页面 工作表 其中包含多个用户选择 输入新订单 更新订单等 每个选项旁边都有一个复选框 根据选中的复选框 单元格F4 F21改变自0 to 1并且 细胞B1更改我想要去的工作表的名称 我的主菜单工
  • 如何从 os_log() 查找源文件和行号

    The 记录 Apple 参考 https developer apple com reference os 1891852 logging对于 iOS 10 和 macOS Sierra 中的新日志记录系统 明确表示不要包含行号和源文件信
  • clickedButtonAtIndex 方法未被调用

    当用户点击按钮时UIAlertView the clickedButtonAtIndex应该调用方法 但是 它没有 in the h我已经打电话给UIAlertView协议 interface RechercherViewControlle
  • Laravel 5.4 上传原始文件名和扩展名

    通过表单提交文件时 如何将原始文件名 file jpg 上传到数据库 控制器 public function addCv Request request cv Cv create request gt all file request gt
  • log4net 未记录到数据库

    我有一个奇怪的问题 我的 log4net 设置没有将任何数据记录到数据库中 也没有引发任何异常来通知问题 我已经在一个名为 Log4net Config 的单独文件中定义了配置设置 并且 已经在程序集中引用了它 请注意 我通过 nuget
  • MYSQL中如何获取不带小数的列值

    我的 mysql 表中有两列A and B我正在获取这样的记录 select A B from table 但问题是上面的查询提供了类似这样的值 12 00 3 4 78 9 但我想得到这样的结果 12 3 78 我将使用哪个 MySQL
  • 如何解决 Python 'Pyzbar' 库的导入错误?

    我刚刚开始熟悉 Pyzbar 库 但是当使用decode方法我得到一个错误 这是代码 import cv2 import numpy as np import pyzbar code image cv2 imread C Users Ace
  • 如何在 Python 中使用 Selenium 运行无头 Chrome?

    我正在尝试使用 selenium 进行一些操作 我真的希望我的脚本能够快速运行 我认为使用无头 Chrome 运行我的脚本会使其速度更快 首先 这个假设是否正确 或者我是否使用无头驱动程序运行我的脚本并不重要 我希望无头 Chrome 能够
  • 保护 Spring 支持,当前端使用 adal auth 保护时

    所以我们的应用程序有两个部分 前端 ui 使用 Angular JS 后端 使用Spring boot的rest api 使用 microsoft adal angular6 库通过 Azure Active Directory 进行身份验