我正在使用Oauth2资源服务器JWT进行身份验证。我正在尝试为两个路由添加身份验证,路由“/student/”将访问权限给予角色ROLE_USER,路由“/students/”将访问权限授予角色ROLE_ADMIN。
安全配置
public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception{
return httpSecurity
.csrf(AbstractHttpConfigurer::disable)
.authorizeHttpRequests(a ->
{
a.requestMatchers("/student/").hasAnyRole("ROLE_USER");
a.requestMatchers("/student/**").hasAnyRole("ROLE_USER");
a.requestMatchers("/students/").hasAnyRole("ROLE_ADMIN");
a.requestMatchers("/students/**").hasAnyRole("ROLE_ADMIN");
a.requestMatchers("/").permitAll();
a.requestMatchers("/token/").permitAll();
a.requestMatchers("/token/**").permitAll();
a.anyRequest().authenticated();
})
.oauth2ResourceServer(OAuth2ResourceServerConfigurer::jwt)
.userDetailsService(userDetailsService)
.headers(headers -> headers.frameOptions().sameOrigin())
.httpBasic(Customizer.withDefaults())
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.build();
}
我尝试将控制器上的hasRole()
更改为hasAnyRole()
、hasAuthority()
、treid @PreAuthorize()
,并使用没有“ROLE_
“前缀的角色进行检查,但没有任何效果。
用户详细信息服务
public class jpaUserDetailsService implements UserDetailsService {
UserRepository userRepository;
public jpaUserDetailsService(UserRepository userRepository) {
this.userRepository = userRepository;
}
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
return userRepository.findUserByUsername(username)
.map(SecurityUser::new)
.orElseThrow(() -> new UsernameNotFoundException("Username not found " + username));
}
}
用户详细信息
public class SecurityUser implements UserDetails {
public Collection<? extends GrantedAuthority> getAuthorities() {
return user.getRoles().stream()
.map(Role::getRole)
.map(UserRoles::toString)
.map(SimpleGrantedAuthority::new).toList();
}
}
我正在对所有角色使用枚举
public enum UserRoles {
ROLE_ADMIN,
ROLE_USER
}
生成jwt令牌的服务
public class TokenService {
private final JwtEncoder jwtEncoder;
public TokenService(JwtEncoder jwtEncoder) {
this.jwtEncoder = jwtEncoder;
}
public String generateToken(Authentication authentication){
Instant now = Instant.now();
String scope = authentication.getAuthorities().stream()
.map(GrantedAuthority::getAuthority)
.collect(Collectors.joining(" "));
JwtClaimsSet claims = JwtClaimsSet.builder()
.issuer("self")
.issuedAt(now.plus(1 , ChronoUnit.HOURS))
.subject(authentication.getName())
.claim("scope" , scope)
.build();
return this.jwtEncoder.encode(JwtEncoderParameters.from(claims)).getTokenValue();
}
用户实体
public class User {
@Id
@GeneratedValue
private long userId;
@Column(unique = true , nullable = false)
private String username;
@Column(nullable = false)
private String password;
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(
joinColumns = @JoinColumn(name = "userId"),
inverseJoinColumns = @JoinColumn(name = "roleId")
)
@ToString.Exclude
private List<Role> roles;
}
角色实体
public class Role {
@Id
@GeneratedValue
private Long roleId;
@Column(unique = true , nullable = false)
@Enumerated(EnumType.STRING)
private UserRoles role;
}
最后我的控制器
@GetMapping("/student/") // route i want to allow with role user;
public Student getStudent(Principal principal){
}
@GetMapping("/students/") // route i want to allow only role admin
public List<Student> getStudents(Principal principal){
}
}
1条答案
按热度按时间q5lcpyga1#
默认的
JwtGrantedAuthoritiesConverter
实现从scope
声明(您提供的)中读取授权,并在它们前面加上SCOPE_
,这意味着您的授权将变为SCOPE_ROLE_USER
和SCOPE_ROLE_ADMIN
。您可以适应它并将
SecurityFilterChain
更改为:或者您可以创建自定义
JwtGrantedAuthoritiesConverter
:还要注意权限和角色之间的区别在于角色只是遵循特定命名约定的权限(=前缀为
ROLE_
),这意味着您应该使用hasAnyAuthority("ROLE_USER")
或hasAnyRole("USER")
,因此如果禁用范围前缀,则应该将SecurityFilterChain
更改为:在评论中你还问了如何调试这个问题。要调试它是否正确运行,你可以:
scope
声明。JwtGrantedAuthoritiesConverter.getAuthorities()
方法中放置断点,以验证是否正确读取了标记。