【发布时间】:2021-12-21 11:18:17
【问题描述】:
我很难理解如何从外部 JWT 中检查角色,或者是否有可能。
我的登录页面在另一个外部页面上,我从该页面收到一个 jwt 令牌。 在我的项目中,我需要检查该 jwt 令牌的有效性并根据声明中的角色限制一些端点。
我可以在 jwtFilter 中以某种方式做到这一点,但我没有设法检查在 .antMatchers() 上应用的“.hasAnyRole()”或“.hasAnyAuthority()”。 我尝试在 spring security 中手动登录用户,但没有成功。
这是spring security的配置:
http.cors()
.addFilterBefore(jwtFilter, BearerTokenAuthenticationFilter.class)
.cors()
.and()
.csrf()
.disable()
.authorizeRequests()
.antMatchers(
"/index.html"
)
.authenticated()
.and()
.authorizeRequests()
.antMatchers("/machines/**").hasAuthority("ROLE_USER")
.and()
.headers()
.frameOptions()
.disable()
我尝试像这样手动登录:
Authentication authentication = new UsernamePasswordAuthenticationToken(jwt.getUsername, null,
AuthorityUtils.createAuthorityList(jwt.getRoles()));
SecurityContextHolder.getContext().setAuthentication(authentication);
您知道如何使用 .hasAnyRole() 并仅拥有 jwtToken 吗?
【问题讨论】:
标签: java spring-security jwt