我一直在研究这篇文章(以及其他一些类似的文章:https://medium.com/omarelgabrys-blog/microservices-with-spring-boot-authentication-with-jwt-part-3-fafc9d7187e8
客户端是Angular 8应用程序,它从独立的微服务获取Jwt。尝试将过滤器添加到其他微服务,以要求通过jwt角色进行特定授权。
始终接收403错误。
安全配置:
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled=true,
securedEnabled = true,
jsr250Enabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
private BCryptPasswordEncoder bCryptPasswordEncoder;
public WebSecurityConfig() {}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.cors().and().csrf().disable()
// make sure we use stateless session; session won't be used to store user's state.
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
// Add a filter to validate the tokens with every request
.addFilterAfter(new JwtAuthorizationFilter2(), UsernamePasswordAuthenticationFilter.class)
// authorization requests config
.authorizeRequests()
// Any other request must be authenticated
.anyRequest().authenticated();
}
}
过滤器:
public class JwtAuthorizationFilter2 extends OncePerRequestFilter {
private final String HEADER = "Authorization";
private final String PREFIX = "Bearer ";
private final String SECRET = "foo";
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
String token = request.getHeader(SecurityConstants.HEADER_STRING);
if (token != null) {
// parse the token.
DecodedJWT decoded = JWT.require(Algorithm.HMAC512(SecurityConstants.SECRET.getBytes()))
.build()
.verify(token.replace(SecurityConstants.TOKEN_PREFIX, ""));
String user = decoded.getSubject();
List<SimpleGrantedAuthority> sgas = Arrays.stream(
decoded.getClaim("roles").asArray(String.class))
.map( s -> new SimpleGrantedAuthority(s))
.collect( Collectors.toList());
if (sgas != null) {
sgas.add(new SimpleGrantedAuthority("FOO_Admin"));
UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(
user,
null,
sgas);
SecurityContextHolder.getContext().setAuthentication(auth);
}
else {
SecurityContextHolder.clearContext();
}
chain.doFilter(request, response);
}
}
}
此代码无需定义任何授权要求即可正常工作,但是,如果在WebSecurityConfig中定义了授权,或者通过装饰控制器方法,将为作用域中的所有请求接收http 403。
示例:
.authorizeRequests().antMatchers("/**").hasRole("FOO_Admin")
// or any of these
@PreAuthorize("hasRole('FOO_Admin')")
@RolesAllowed({"FOO_Admin"})
@Secured({"FOO_Admin"})
Device get(@PathVariable String id) {
// some code
}
[当代码在SecurityContextHolder.getContext().setAuthentication(auth)
处暂停时,auth.authenticated = true
和auth.authorities
包括“ FOO_Admin”的SimpleGrantedAuthority]
所以我想知道是否:FilterChain是否需要身份验证过滤器(或者身份验证是否发生在JwtAuthorizationFilter2中?)?角色名称没有拼写或格式或大小写差异。
我很震惊。任何帮助将不胜感激。
@PreAuthorize("hasRole('FOO_Admin'))
应期望用户具有权限@PreAuthorize("hasRole('FOO_Admin'))
,该权限将以ROLE_FOO_Admin
为前缀。但是,用户仅具有权限ROLE_
,因此无法访问该方法。
您有几种选择:
((1)通过声明FOO_Admin
bean来更改前缀:
GrantedAuthorityDefaults
并使用@Bean
GrantedAuthorityDefaults grantedAuthorityDefaults() {
return new GrantedAuthorityDefaults("FOO");
}
保护该方法。
((2)或更简单的方法是使用@PreAuthorize(hasRole('Admin'))
,它将直接检查用户是否具有权限@PreAuthorize("hasAuthority('FOO_Admin')")
,而无需添加任何前缀。
P.S FOO_Admin
仅验证用户是否有效,并获取稍后为授权用户准备的相关用户信息。这是一种身份验证,我将其重命名为JwtAuthorizationFilter2
以更准确地描述其实际功能。