当前位置: 首页 > 知识库问答 >
问题:

Spring Security和Azure AD预授权hasRole不工作

万俟华辉
2023-03-14

我正在学习一个关于微软文档的教程,介绍如何使用Spring Boot Starter for Azure Active Directory保护我的Spring MVC应用程序。我正在努力保护我网站的管理区域。我在控制器方法上有一个@PreAuthorize注释,我只希望admin组中的用户可以访问它。我可以得到一个登录提示,但成功登录后,我得到了该控制器方法的403。当我删除@PreAuthorize注释时,我可以登录并访问该方法。

以下是控制器方法:

@Controller
public class PostController {

    ...

    @PreAuthorize("hasRole('admin')")
    @RequestMapping(path = "/admin/post", method = RequestMethod.GET)
    public String getPost(@ModelAttribute("post") Post post, Model model) {
        List<Tag> tags = tagService.getAll();
        model.addAttribute("tags", tags);
        return "post";
    }

    ...

以下是WebSecurityConfig.java:

@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private OAuth2UserService<OidcUserRequest, OidcUser> oidcUserService;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
            .antMatchers("/admin/**").authenticated()
            .and()
            .oauth2Login()
            .userInfoEndpoint()
            .oidcUserService(oidcUserService);
    }
}

这是申请表。属性:

# Azure AD
# Specifies your Active Directory ID:
azure.activedirectory.tenant-id=<my-ad-tenant-id>

# Specifies your App Registration's Application ID:
spring.security.oauth2.client.registration.azure.client-id=<my-app-registration-app-id>

# Specifies your App Registration's secret key:
spring.security.oauth2.client.registration.azure.client-secret=<my-client-secret>

# Specifies the list of Active Directory groups to use for authorization:
azure.activedirectory.activeDirectoryGroups=admin

以下是应用程序注册清单:

{
    "id": "<id>",
    "acceptMappedClaims": null,
    "accessTokenAcceptedVersion": null,
    "addIns": [],
    "allowPublicClient": null,
    "appId": "<app-id>",
    "appRoles": [],
    "oauth2AllowUrlPathMatching": false,
    "createdDateTime": "2020-04-10T23:37:26Z",
    "groupMembershipClaims": null,
    "identifierUris": [],
    "informationalUrls": {
        "termsOfService": null,
        "support": null,
        "privacy": null,
        "marketing": null
    },
    "keyCredentials": [],
    "knownClientApplications": [],
    "logoUrl": null,
    "logoutUrl": null,
    "name": "test",
    "oauth2AllowIdTokenImplicitFlow": true,
    "oauth2AllowImplicitFlow": true,
    "oauth2Permissions": [],
    "oauth2RequirePostResponse": false,
    "html" target="_blank">optionalClaims": null,
    "orgRestrictions": [],
    "parentalControlSettings": {
        "countriesBlockedForMinors": [],
        "legalAgeGroupRule": "Allow"
    },
    "passwordCredentials": [
        {
            "customKeyIdentifier": null,
            "endDate": "2299-12-31T05:00:00Z",
            "keyId": "<key-id>",
            "startDate": "2020-04-10T23:39:47.917Z",
            "value": null,
            "createdOn": "2020-04-10T23:39:48.4572747Z",
            "hint": "SVb",
            "displayName": "test key"
        }
    ],
    "preAuthorizedApplications": [],
    "publisherDomain": "test.onmicrosoft.com",
    "replyUrlsWithType": [
        {
            "url": "http://localhost:8080/login/oauth2/code/azure",
            "type": "Web"
        }
    ],
    "requiredResourceAccess": [
        {
            "resourceAppId": "<resource-app-id>",
            "resourceAccess": [
                {
                    "id": "<resource-access-id>",
                    "type": "Scope"
                }
            ]
        }
    ],
    "samlMetadataUrl": null,
    "signInUrl": null,
    "signInAudience": "AzureADMyOrg",
    "tags": [],
    "tokenEncryptionKeyId": null
}

下面是Azure中的团队:

我要登录的用户是此组的成员。根据文件规定,只有未经授权的用户才能获得403。我已尝试将hasRole()参数更改为“ROLE_admin”,但这不起作用。我还尝试在WebSecurity配置中配置hasRole(“管理员”)。java是这样的:

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
        .authorizeRequests()
        .antMatchers("/admin/**").authenticated()
        .antMatchers("/admin/**").hasRole("admin")
        .and()
        .oauth2Login()
        .userInfoEndpoint()
        .oidcUserService(oidcUserService);
}

但这也行不通。我已经做了好几天了,但我不明白为什么当我登录的用户在admin组时我会得到403。

编辑

pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.5.RELEASE</version>
    </parent>
    <groupId>me.test</groupId>
    <artifactId>test-me</artifactId>
    <version>1.0</version>
    <packaging>war</packaging>
    <name>test.me</name>

    <properties>
        <java.version>1.8</java.version>
        <azure.version>2.2.0</azure.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>com.microsoft.azure</groupId>
            <artifactId>azure-active-directory-spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-oauth2-client</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-oauth2-jose</artifactId>
        </dependency>
        <dependency>
            <groupId>org.thymeleaf.extras</groupId>
            <artifactId>thymeleaf-extras-springsecurity5</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>com.microsoft.sqlserver</groupId>
            <artifactId>mssql-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>6.1.0.Final</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.9</version>
        </dependency>
        <dependency>
            <groupId>com.azure</groupId>
            <artifactId>azure-storage-blob</artifactId>
            <version>12.5.0</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>com.microsoft.azure</groupId>
                <artifactId>azure-spring-boot-bom</artifactId>
                <version>${azure.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
    <finalName>ROOT</finalName>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <artifactId>maven-failsafe-plugin</artifactId>
                <executions>
                    <execution>
                        <goals>
                            <goal>integration-test</goal>
                            <goal>verify</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>

您可以在GitHub中查看Microsoft Spring Boot/Azure广告示例。

共有1个答案

东方方伟
2023-03-14

根据我的研究,如果我们想使用graph API检索用户的组成员身份,它要求注册的应用程序具有Direcory。AccessAsUser。所有权限。有关更多详细信息,请参阅本文件和本文件。

举个例子

应用属性

# Azure AD
# Specifies your Active Directory ID:
azure.activedirectory.tenant-id=<my-ad-tenant-id>

# Specifies your App Registration's Application ID:
spring.security.oauth2.client.registration.azure.client-id=<my-app-registration-app-id>

# Specifies your App Registration's secret key:
spring.security.oauth2.client.registration.azure.client-secret=<my-client-secret>

# Specifies the list of Active Directory groups to use for authorization:
azure.activedirectory.activeDirectoryGroups=SQLAdmin

# Configure log level
logging.level.root=Debug
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private OAuth2UserService<OidcUserRequest, OidcUser> oidcUserService;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .antMatchers("/admin/**").authenticated()
                .and()
                .oauth2Login()
                .userInfoEndpoint()
                .oidcUserService(oidcUserService);
    }
}
 @Autowired
    @PreAuthorize("hasRole('SQLAdmin')")
    @GetMapping("/admin")
    @ResponseBody
    public String helloWorld() {
        return "Hello World!";
    }
 类似资料:
  • 我发现了许多类似的问题,但没有一个解决了我的问题。我的问题是可以访问的函数 下面是我的spring-security.xml代码。

  • EDIT做了一些更多的测试:当我只配置secure-annotations=“enabled”时,基于角色的安全性工作。此外,配置pre-postannotations=“enabled”时,既不安全也不预授权。当我只配置前-后注释时,它仍然不起作用。 编辑2 更多的测试:只有secured_annotations=“enabled”,对channelservice的调用通过Cglib2AopPr

  • 我是Spring Security的新手。我们在我的一个示例示例中使用Spring Security 5.4.5和Spring Boot。 我在下面的配置类中尝试在RESTAPI的/user和/adminendpoint中应用Spring Security身份验证/授权。 根据上述Spring配置 /userUSER和ADMIN角色都可以访问, /adminADMIN角色也可以访问。 当我试图在浏

  • 我正在尝试测试使用标准Spring Security注释和方法保护的web api。我查看了网站上的所有选项,没有任何帮助,下面是代码。没有角色,一切都很好。我为这个问题痛苦了好几天。我会感谢你的帮助,谢谢。 控制器类 如果,然后它返回用户,因为它应该 UserDetailsServiceImp 和添加角色的用户数据 这是数据库返回的内容

  • 我在使用Spring Security&Thymeleaf时遇到了一个问题,特别是在尝试使用hasRole表达式时。admin“用户有一个角色”admin“,但在尝试时解析为false 我得HTML: 结果如下: 我已经在security.xml文件中启用了use-expressions 并且在我的配置中包含了SpringSecurityDiscuale 而具有一组 为什么不起作用? 我很感激你的

  • 请求参数说明 参数 描述 必填 示例值 类型 最大长度 action 接口参数组 是 object └action 需要调用的接口名称 是 pre_thaw string get GET参数组,本组参数需要参与签名 是 object └biz_id 业务单号(biz_id与payid只传其一) 是 20191125001 number └amt 解冻金额(退款给客人金额,0或者空表示商家收取全部费