add security
This commit is contained in:
@@ -0,0 +1,40 @@
|
|||||||
|
package hackathon.FrisbYEE.config;
|
||||||
|
|
||||||
|
import java.util.Collection;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import org.springframework.context.annotation.Bean;
|
||||||
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||||
|
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
|
||||||
|
import org.springframework.security.core.authority.SimpleGrantedAuthority;
|
||||||
|
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken;
|
||||||
|
import org.springframework.security.web.SecurityFilterChain;
|
||||||
|
|
||||||
|
@Configuration
|
||||||
|
@EnableWebSecurity
|
||||||
|
public class WebSecurityConfig {
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
|
||||||
|
http
|
||||||
|
.csrf(csrf -> csrf.disable())
|
||||||
|
.authorizeHttpRequests(auth -> auth
|
||||||
|
.requestMatchers("/", "/public", "/coach/**").permitAll() // allow coach endpoints
|
||||||
|
.requestMatchers("/admin/**").hasRole("admin")
|
||||||
|
.requestMatchers("/user/**").hasRole("user")
|
||||||
|
.anyRequest().authenticated())
|
||||||
|
.oauth2ResourceServer(oauth2 -> oauth2
|
||||||
|
.jwt(jwt -> jwt.jwtAuthenticationConverter(jwtToken -> {
|
||||||
|
Map<String, Collection<String>> realmAccess = jwtToken.getClaim("realm_access");
|
||||||
|
Collection<String> roles = realmAccess.get("roles");
|
||||||
|
List<SimpleGrantedAuthority> authorities = roles.stream()
|
||||||
|
.map(role -> new SimpleGrantedAuthority("ROLE_" + role))
|
||||||
|
.toList();
|
||||||
|
return new JwtAuthenticationToken(jwtToken, authorities);
|
||||||
|
})));
|
||||||
|
|
||||||
|
return http.build();
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user