使用Spring“安全”注释授权端点

问题描述 投票:1回答:1

在我的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,并在邮递员中将其用作:enter image description here

从邮递员呼叫以下端点时:

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

我得到了403禁止访问(没有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>

使用这些依赖关系,我的百里香登录页面会自动生成。

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

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

NotReadablePropertyException:无效的属性'principal.authorities'类的]]

在我的Spring Boot应用程序中,我创建了一个具有以下配置的WebSecurityConfigurerAdapter:@Autowired public void configureGlobal(AuthenticationManagerBuilder auth)throws ...

spring spring-boot spring-security thymeleaf postman
1个回答
0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.