【发布时间】:2022-01-06 09:03:29
【问题描述】:
我正在使用 spring cloud oauth-2 和 spring cloud security 构建用户身份验证系统。我希望有许多可以分配给用户组的权限。权限存储为枚举常量,如下所示:
public enum Authority {
READ_USER(1, "View users and their details", "READ_USER"),
WRITE_USER(2, "Create, Edit and Delete users and their details", "WRITE_USER"),
// More authorities will be added
;
Authority(int id, String description, String name) {
this.id = id;
this.description = description;
this.name = name;
}
private final int id;
private final String description;
private final String name;
public int getId() {
return id;
}
public String getDescription() {
return description;
}
public String getName() {
return name;
}
}
我已将身份验证服务器设置为向内存中的客户端颁发 JWT 令牌。一切正常(我认为)。
下面是我的 UserDetails 实现
public class AuthPrincipal implements UserDetails {
private String email;
private String password;
private Collection<? extends GrantedAuthority> authoritySet;
public AuthPrincipal(User user) {
this.email = user.getEmail();
this.password = user.getPassword();
this.authoritySet = user.getGroup().getAuthorities().stream().map(authority -> new SimpleGrantedAuthority(authority.getName())).collect(Collectors.toList());
}
// Necessary getters
}
就像我说的,身份验证服务器正在发布令牌。我面临的问题是授权。下面是我的资源服务器http配置:
@Configuration
@EnableWebSecurity()
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
@Override
public void configure(HttpSecurity http) throws Exception{
http
.authorizeRequests()
.antMatchers("/").permitAll()
// Users paths
.antMatchers(HttpMethod.GET, "/users/**").hasAuthority(Authority.READ_USER.getName())
.antMatchers(HttpMethod.POST, "/users/**").hasAuthority(Authority.WRITE_USER.getName())
.antMatchers(HttpMethod.PUT, "/users/**").hasAuthority(Authority.WRITE_USER.getName())
.antMatchers(HttpMethod.DELETE, "/users/**").hasAuthority(Authority.WRITE_USER.getName())
.anyRequest().authenticated();
}
}
身份验证成功后,对于具有所需权限的用户,我收到 403 access denied 错误,如下面的安全调试日志所示:
2021-11-29 14:34:42.567 DEBUG 9832 --- [nio-8080-exec-3] o.s.security.web.FilterChainProxy : Securing GET /users
2021-11-29 14:34:42.567 DEBUG 9832 --- [nio-8080-exec-3] s.s.w.c.SecurityContextPersistenceFilter : Set SecurityContextHolder to empty SecurityContext
2021-11-29 14:34:42.591 DEBUG 9832 --- [nio-8080-exec-3] p.a.OAuth2AuthenticationProcessingFilter : Authentication success: OAuth2Authentication [Principal=superuser@email.com, Credentials=[PROTECTED], Authenticated=true, Details=remoteAddress=0:0:0:0:0:0:0:1, tokenType=BearertokenValue=<TOKEN>, Granted Authorities=[{authority=READ_USER}, {authority=WRITE_USER}]]
2021-11-29 14:34:42.595 DEBUG 9832 --- [nio-8080-exec-3] o.s.s.w.a.i.FilterSecurityInterceptor : Failed to authorize filter invocation [GET /users] with attributes [#oauth2.throwOnError(hasAuthority('READ_USER'))]
2021-11-29 14:34:42.604 DEBUG 9832 --- [nio-8080-exec-3] s.s.o.p.e.DefaultOAuth2ExceptionRenderer : Written [error="access_denied", error_description="Access is denied"] as "application/json" using [org.springframework.http.converter.json.MappingJackson2HttpMessageConverter@4cd51cd5]
2021-11-29 14:34:42.604 DEBUG 9832 --- [nio-8080-exec-3] s.s.w.c.SecurityContextPersistenceFilter : Cleared SecurityContextHolder to complete request
从日志中可以看出,用户拥有“READ_USERS”的权限,但GET请求仍然被拒绝。我错过了什么?
@Entity
public class User extends BaseEntity{
@Id
private UUID id = UUID.randomUUID();
@NotNull(message = "First Name cannot be blank")
private String firstName;
@NotNull(message = "Last Name cannot be blank")
private String lastName;
private String middleName;
@NotNull(message = "Email cannot be blank")
@Column(unique = true)
private String email;
private String phoneNumber;
@JsonIgnore
private String password;
private String imageUrl;
@ManyToOne
private UserGroup group;
// Constructors, Getters and Setters
}
和用户组
@Entity
public class UserGroup extends BaseEntity{
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
@ElementCollection(fetch = FetchType.EAGER)
@Enumerated(EnumType.STRING)
private Set<Authority> authorities = new HashSet<>();
// Getters and setters
}
【问题讨论】:
-
您好,请调试:
user.getGroup().getAuthorities()... 目前尚不清楚权威来自哪里。 -
@xerx593 权限是分配给用户组的枚举常量。用户类有一个 Group 属性。 Group 类是一个拥有 Authorities 集合的实体。
标签: java spring spring-boot oauth-2.0