Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@

@RestController
public class DemoController {

// to manage access, add route rules in security/SecurityConfig.java like in the
// examples
@GetMapping("/demo")
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
// based on this tutorial: https://www.javacodegeeks.com/2025/07/spring-boot-keycloak-role-based-authorization.html


package com.ase.userservice.security;

import org.springframework.core.convert.converter.Converter;
Expand Down
28 changes: 15 additions & 13 deletions src/main/java/com/ase/userservice/security/SecurityConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -8,24 +8,26 @@
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationConverter;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
@EnableMethodSecurity
public class SecurityConfig {

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
JwtAuthenticationConverter jwtConverter = new JwtAuthenticationConverter();
jwtConverter.setJwtGrantedAuthoritiesConverter(new JwtAuthConverter());

// the role always has to be capatalized
http
.authorizeHttpRequests(authorize -> authorize

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
JwtAuthenticationConverter jwtConverter = new JwtAuthenticationConverter();
jwtConverter.setJwtGrantedAuthoritiesConverter(new JwtAuthConverter());


//the role always has to be capitalized
http
.csrf(csrf -> csrf.disable()) // Disable CSRF for API endpoints isnt needed for our purpose since we are not using cookies for auth
.authorizeHttpRequests(authorize -> authorize
.requestMatchers("/demo").hasRole("DEFAULT-ROLES-SAU")
.requestMatchers("/admin/**").hasRole("admin")
.anyRequest().authenticated())
.oauth2ResourceServer(oauth2 -> oauth2
.oauth2ResourceServer(oauth2 -> oauth2
.jwt(jwt -> jwt.jwtAuthenticationConverter(jwtConverter)));
return http.build();
}
return http.build();
}
}
Loading