【问题标题】:Spring Boot, Azure Active Directory, 404 Not Found PageSpring Boot,Azure Active Directory,404 未找到页面
【发布时间】:2022-01-05 03:19:05
【问题描述】:

我正在尝试使用 Web 服务为我的 Spring Boot 运行 azure Active Directory。问题是当我成功登录时,它找不到应该可以访问的页面。

我添加了以下属性(tetant-id、client-id、client-secret、user-group.allowed-group-names)

azure.activedirectory.redirect-uri-template=login/oauth2/code

我的配置是:

@Order(1)
@Configuration
@EnableWebSecurity
public class AADSecurityConfiguration extends AADWebSecurityConfigurerAdapter {

  @Override
  public void configure(WebSecurity web) {
    web.ignoring().antMatchers("/health");
  }

  @Override
  protected void configure(HttpSecurity http) throws Exception {

    http.authorizeRequests()
        .antMatchers("/oauth2/**", "/login/**")
        .permitAll()
        .anyRequest()
        .authenticated()
        .and()
        .oauth2Login()
        .defaultSuccessUrl("/list", true);
  }
}

简单的控制器请求是:

  @GetMapping("/list")
  @PreAuthorize("hasRole('Admin') or hasRole('Users')")
  public String getListPage() {
    return "list";
  }

依赖的版本是:

<spring.security.version>5.6.0</spring.security.version>
<spring.boot.version>2.5.4</spring.boot.version>
<azure.version>3.10.0</azure.version>

我已经添加了重定向 URI,例如

正如我在正确登录时提到的,/list 页面无法访问,它在下面显示 404 错误。 白标错误页面

This application has no explicit mapping for /error, so you are seeing this as a fallback.
Sat Nov 27 12:29:06 UTC 2021
There was an unexpected error (type=Not Found, status=404).

导致该问题的原因可能是什么?

【问题讨论】:

    标签: spring-boot azure-active-directory spring-security-oauth2


    【解决方案1】:

    请检查以下是否可能的解决方法

    在某些情况下,可能是Application启动类的位置有问题。将Application类放在最外面,这样它就包含了所有的子包。

    1. 尽量把应用类(包含main方法)放在控制器包的根目录下。(目的是让应用包含所有的子包)

    (或)

    1. 错误是由于 Bootstrap 类不知道需要查看的控制器的位置。 尝试在您的主类中添加类级别注释:@ComponentScan(basePackages = {(您的控制器包的名称)}

        @ComponentScan(basePackages={"com.sample.controller"})
        @SpringBootApplication

    (或)

    尝试在 pom.xml 中添加 thymeleaf 依赖

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
    

    注意:还要确保,如果 spring boot 重定向 url 必须使用 Azure 本场景中的 AD 启动器,设置重定向 /login/oauth2/code/ 的 URI。例如: http://localhost:8080/login/oauth2/code/。一定要包括 尾随/

    尝试清除缓存并重试。

    参考文献

    1. spring-oauth-2-0-client-returns-401-unauthorized
    2. spring-boot-SO

    【讨论】:

    • 感谢您的回答。我可以确认主类位于控制器类的根目录中。我也使用 thymeleaf 依赖和上面的 spring boot 版本。在重定向网址上,我使用 https://{prod.url}/login/oauth2/code (它不包括尾随)但我只是在本地尝试这些选项,没有在 prod -prod 上尝试同样的错误-。不确定是否值得尝试因为这些 URL 而被推送到产品上?