Code: Select all
@Configuration
@EnableWebSecurity
public class DirectlyConfiguredJwkSetUri {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(authorize -> authorize
.requestMatchers("/contacts/**").access(hasScope("contacts"))
.requestMatchers("/messages/**").access(hasScope("messages"))
.anyRequest().authenticated()
)
.oauth2ResourceServer(oauth2 -> oauth2
.jwt(Customizer.withDefaults())
);
return http.build();
}
}
< /code>
Oder auf der Methodenebene: < /p>
@PreAuthorize("hasAuthority('SCOPE_messages')")
public List getMessages(...) {}
Code: Select all
@PreAuthorize("hasAuthority('TENANT:' + #tenantId) or hasAuthority('ADMIN')")
@GetMapping("{tenantId}/users/{userId}/settings")
public ResponseEntity getTenantResources(@PathVariable long tenantId,
@PathVariable long userId Authentication authentication) {
User user = (User) authentication.getPrincipal();
if (user.getId != userId) {
throw new IdConflicException;
}
// Retrieve and return settings from DB using the userId
}
< /code>
Ich suche jedoch nach einer besseren Lösung, da dies eine Menge Code -Duplikation bedeuten würde und daher fehleranfällig und schwer zu pflegen wäre. Lösung, die keine Annotationen auf Methodenebene beinhaltet. public static void checkAllowedToAccessTenantAndUser(long tenantId, long userId, Jwt jwt) {
long jwtUserId = jwt.getClaim("userId");
long jwtTenantId = jwt.getClaim("tenantId");
if (scope.contains(Authorities.CLIENT.getAuthority())) {
return;
}
if (jwtUserId != userId || jwtTenantId != tenantId) {
throw new IdorException();
}
}