首页 > 解决方案 > Spring Boot 错误 401 未经授权的模板

问题描述

我有一个使用 Spring Boot 和旧版 @EnableAuthorizationServer 创建的 OAuth 2.0 授权服务器。可以在下面找到安全配置的摘录:

http
    .requestMatchers()
        .mvcMatchers("/login", "/profile", "/oauth/authorize", "/.well-known/jwks.json")
        .and()
    .authorizeRequests()
        .mvcMatchers("/login", "/.well-known/jwks.json").permitAll()
        .anyRequest().authenticated()
        .and()
    .formLogin()
        .loginPage("/login")
        .permitAll()

一切正常,现在我正在为错误消息创建 Thymeleaf 模板。我的自定义页面使用资源/模板/错误下的文件 404.html 显示 404 之类的错误。对于任何未处理的异常,都有一个通用的 resources/templates/error.html。

由于某种原因,模板 401.html 没有被呈现。相反,Spring 不断返回带有代码 401 和以下内容的默认响应:

<oauth>
  <error_description>Full authentication is required to access this resource</error_description>
  <error>unauthorized</error>
</oauth>

你知道这是否可以改变以及如何改变?为了清楚起见,我不想删除错误,而是返回自定义内容。

感谢您的时间!

标签: springspring-bootspring-securitythymeleafspring-security-oauth2

解决方案


你应该告诉 Spring Security 你不想在错误页面上进行身份验证,如下所示:

http.authorizeRequests().mvcMatchers("/your/error/page/url").permitAll();

推荐阅读