【问题标题】:Authorize endpoint with Spring "Secured" annotation使用 Spring “Secured”注解授权端点
【发布时间】:2020-01-26 09:44:14
【问题描述】:

在我的 Spring Boot 应用程序中,我使用以下配置创建了一个 WebSecurityConfigurerAdapter

@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
    auth
        .inMemoryAuthentication()
        .withUser("student").password(passwordEncoder().encode("password")).roles("STUDENT")
        .and()
        .withUser("teacher").password(passwordEncoder().encode("admin")).roles("TEACHER");
}

我使用浏览器登录,并获得一个 Cookie 令牌,存储为 JSESSIONID。 然后我继续获取该cookie,并在邮递员中将其用作:

从 Postman 调用以下端点时:

@PostMapping(consumes = "application/json", produces = "application/json", path="/rest/class/{classId}/student")
@org.springframework.security.access.annotation.Secured({"ROLE_TEACHER"})

我得到 403 Forbidden(没有 cookie,我得到 401,可以理解)。

我也在使用以下依赖项:

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

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

    <dependency>
        <groupId>org.thymeleaf.extras</groupId>
        <artifactId>thymeleaf-extras-springsecurity5</artifactId>
    </dependency>

使用这些依赖,自动生成我的thymeleaf登录页面。

如何解决此身份验证/授权问题?

我需要禁用 csrf 吗?如果没有,我怎么能在我的邮递员请求中使用 csrf 令牌? 我尝试使用 X-CSRF-TOKEN 将其添加到 Postman 标头请求中,并在登录过程中使用发送到后端的 _csrf 令牌。 如果我禁用 csrf,那么登录页面甚至不会出现,并且我得到以下异常:

NotReadablePropertyException:无效的属性“principal.authorities” 豆类的

【问题讨论】:

  • 希望我也知道如何使用邮递员或类似工具来做到这一点,喜欢。

标签: spring spring-boot spring-security thymeleaf postman


【解决方案1】:

您的方法是有效的,但请注意 CSRF 令牌与会话相关联,并且会话 ID 会在登录后更新。
如果您发送登录前 CSRF 令牌和登录后会话 ID,则 CSRF 令牌将与预期令牌不匹配。
要获取更新后的 CSRF 令牌,在您登录后,您可以在浏览器中导航到发出所需 POST 请求的页面。
然后您可以在该页面上找到更新后的 CSRF 令牌。
例如,它可能是隐藏的输入字段 &lt;input type="hidden" name="_csrf" value="123"&gt; 或元标记 &lt;meta name="_csrf" content="123"/&gt;,具体取决于您在页面上的设置方式。

【讨论】:

  • 谢谢。我将在今天晚些时候尝试一下。尝试使用 csrf 令牌的原因是因为我注意到我的浏览器所做的其他请求不包含一个。之后,我注意到 GET 请求不需要 CSRF 令牌。但是,出于某种原因,使用 ROLE_TEACHER 保护的端点可以通过 STUDENT 会话 ID 访问。这是为什么呢?
  • @WilhelmSorban 你设置@EnableGlobalMethodSecurity(securedEnabled = true)了吗?这将启用@Secured 注释
猜你喜欢
  • 2013-02-03
  • 1970-01-01
  • 2016-08-11
  • 2021-07-08
  • 2018-11-13
  • 2014-03-09
  • 2020-09-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多