我有一个有效的令牌,但每次使用它时都会收到 403 错误。我正在使用 Spring Boot 的版本 3 以及“oauth2 资源服务器”依赖项。 有人可以看看我的代码吗?
我的安全配置
@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
public class SecurityConfig {
private String secretKey = "pNmNaLNFiyISfzEmrQN3WiKad7Q1p9JXSuKYIAsaNfuNLNEMkJaPLtDXcttRB8nn";
private final UserDetailsServiceImpl userDetailsService;
@Bean
public AuthenticationManager authenticationManager(){
DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider();
daoAuthenticationProvider.setPasswordEncoder(passwordEncoder());
daoAuthenticationProvider.setUserDetailsService(userDetailsService);
return new ProviderManager(daoAuthenticationProvider);
}
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception{
return httpSecurity
.csrf(csrf -> csrf.disable())
.sessionManagement(sm->sm.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.authorizeHttpRequests(au->au.requestMatchers("/api/login/**","/").permitAll())
.authorizeHttpRequests(au->au.requestMatchers(toH2Console()).permitAll())
.authorizeHttpRequests(au->au.anyRequest().authenticated())
.userDetailsService(userDetailsService)
.build();
}
@Bean
BCryptPasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
@Bean
JwtEncoder jwtEncoder(){
return new NimbusJwtEncoder(new ImmutableSecret<>(secretKey.getBytes()));
}
@Bean
JwtDecoder jwtDecoder(){
SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getBytes(),"RSA");
return NimbusJwtDecoder.withSecretKey(secretKeySpec).macAlgorithm(MacAlgorithm.HS512).build();
}
}
用户详情服务
@Service
@RequiredArgsConstructor
public class UserDetailsServiceImpl implements UserDetailsService {
private final AppUserRepository appUserRepository;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
AppUser user = appUserRepository.findByUsername(username);
if (user==null) throw new UsernameNotFoundException("Utilisateur introuvable!");
UserDetails userDetails = User.withUsername(user.getUsername())
.password(user.getPassword())
.authorities(Set.of(new SimpleGrantedAuthority(user.getRole().name())))
.build();
return userDetails;
}
}
端点
@RequiredArgsConstructor
@RestController
@RequestMapping("/api")
public class APIController {
private final ProductService productService;
private final AuthenticationManager authenticationManager;
private final JwtEncoder jwtEncoder;
@GetMapping("/products")
public List<Product> getProducts(){
return productService.getAllProducts();
}
@PostMapping("/login")
public Map<String,String> login(String username,String password){
Authentication authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, password));
Instant instant = Instant.now();
String scope = authentication.getAuthorities().stream()
.map(GrantedAuthority::getAuthority).collect(Collectors.joining(" "));
System.out.println("les roles : "+scope);
JwtClaimsSet jwtClaimsSet = JwtClaimsSet.builder()
.issuedAt(instant)
.expiresAt(instant.plus(10, ChronoUnit.MINUTES))
.subject(username)
.claim("scope",scope)
.build();
JwtEncoderParameters jwtEncoderParameters =
JwtEncoderParameters.from(
JwsHeader.with(MacAlgorithm.HS512).build(),
jwtClaimsSet
);
String jwt = jwtEncoder.encode(jwtEncoderParameters).getTokenValue();
return Map.of("access_token",jwt);
}
@GetMapping("/profil")
public Authentication authentication(Authentication authentication){
return authentication;
}
}
我收到 403 错误。我正在使用 Spring Boot 的版本 3 以及“oauth2 资源服务器”依赖项。
我想检索产品列表,但即使将令牌放入请求的标头中,我仍然收到我不明白的 403 错误
UserDetailsService 在资源服务器上没有用处。
使用我维护的启动器,配置资源服务器(具有自定义权限映射)可以像这样简单:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
</dependency>
<dependency>
<groupId>com.c4-soft.springaddons</groupId>
<artifactId>spring-addons-starter-oidc</artifactId>
<version>7.1.9</version>
</dependency>
com:
c4-soft:
springaddons:
oidc:
ops:
- iss: https://localhost/realms/master
username-claim: preferred_username
authorities:
- path: $.realm_access.roles
- path: $.resource_access.*.roles
resourceserver:
permit-all:
- "/public/**"
cors:
- path: /**
allowed-origin-patterns: http://localhost:4200
@Configuration
@EnableMethodSecurity
public class SecurityConfig {
}
要在没有“我的”启动器的情况下执行相同操作,请参阅