Переглянути джерело

Endpoints secured with keycloak

wpfat23-5 3 роки тому
батько
коміт
29fbe1f6e1

+ 76 - 54
pom.xml

@@ -1,64 +1,86 @@
 <?xml version="1.0" encoding="UTF-8"?>
 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
-	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
-	<modelVersion>4.0.0</modelVersion>
-	<parent>
-		<groupId>org.springframework.boot</groupId>
-		<artifactId>spring-boot-starter-parent</artifactId>
-		<version>3.0.5</version>
-		<relativePath/> <!-- lookup parent from repository -->
-	</parent>
-	<groupId>com.DeliveryProject</groupId>
-	<artifactId>EasyDelivery</artifactId>
-	<version>0.0.1-SNAPSHOT</version>
-	<packaging>war</packaging>
-	<name>EasyDelivery</name>
-	<description>EasyDelivery</description>
-	<properties>
-		<java.version>17</java.version>
-	</properties>
-	<dependencies>
-		<dependency>
-			<groupId>org.springframework.boot</groupId>
-			<artifactId>spring-boot-starter-web</artifactId>
-		</dependency>
+         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
+    <modelVersion>4.0.0</modelVersion>
+    <parent>
+        <groupId>org.springframework.boot</groupId>
+        <artifactId>spring-boot-starter-parent</artifactId>
+        <version>2.7.10</version>
+        <relativePath/> <!-- lookup parent from repository -->
+    </parent>
+    <groupId>com.DeliveryProject</groupId>
+    <artifactId>EasyDelivery</artifactId>
+    <version>0.0.1-SNAPSHOT</version>
+    <packaging>war</packaging>
+    <name>EasyDelivery</name>
+    <description>EasyDelivery</description>
+    <properties>
+        <java.version>11</java.version>
+    </properties>
+    <dependencies>
+        <dependency>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-starter-web</artifactId>
+            <version>2.7.10</version>
+        </dependency>
+        <dependency>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-starter-tomcat</artifactId>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-starter-test</artifactId>
+            <scope>test</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-starter-actuator</artifactId>
+        </dependency>
 
-		<dependency>
-			<groupId>org.springframework.boot</groupId>
-			<artifactId>spring-boot-starter-tomcat</artifactId>
-			<scope>provided</scope>
-		</dependency>
+        <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
+        <dependency>
+            <groupId>javax.servlet</groupId>
+            <artifactId>javax.servlet-api</artifactId>
+            <version>4.0.1</version>
+            <scope>provided</scope>
+        </dependency>
 
 
+        <dependency>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-starter-security</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.keycloak</groupId>
+            <artifactId>keycloak-spring-boot-starter</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.keycloak</groupId>
+            <artifactId>keycloak-spring-security-adapter</artifactId>
+        </dependency>
 
 
-		<dependency>
-			<groupId>org.springframework.boot</groupId>
-			<artifactId>spring-boot-starter-test</artifactId>
-			<scope>test</scope>
-		</dependency>
-		<dependency>
-			<groupId>org.springframework.boot</groupId>
-			<artifactId>spring-boot-starter-actuator</artifactId>
-		</dependency>
+    </dependencies>
+    <dependencyManagement>
+        <dependencies>
+            <dependency>
+                <groupId>org.keycloak.bom</groupId>
+                <artifactId>keycloak-adapter-bom</artifactId>
+                <version>10.0.0</version>
+                <type>pom</type>
+                <scope>import</scope>
+            </dependency>
+        </dependencies>
+    </dependencyManagement>
+    <build>
+        <plugins>
+            <plugin>
+                <groupId>org.springframework.boot</groupId>
+                <artifactId>spring-boot-maven-plugin</artifactId>
 
-		<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
-		<dependency>
-			<groupId>javax.servlet</groupId>
-			<artifactId>javax.servlet-api</artifactId>
-			<version>4.0.1</version>
-			<scope>provided</scope>
-		</dependency>
-
-	</dependencies>
-
-	<build>
-		<plugins>
-			<plugin>
-				<groupId>org.springframework.boot</groupId>
-				<artifactId>spring-boot-maven-plugin</artifactId>
-			</plugin>
-		</plugins>
-	</build>
+            </plugin>
+        </plugins>
+    </build>
 
 </project>

+ 5 - 0
src/main/java/com/deliveryproject/easydelivery/Configuration/Constants.java

@@ -0,0 +1,5 @@
+package com.deliveryproject.easydelivery.Configuration;
+
+public class Constants {
+    public static String CLIENT_ID = "login-app";
+}

+ 44 - 0
src/main/java/com/deliveryproject/easydelivery/Configuration/KeycloakAdapterConfig.java

@@ -0,0 +1,44 @@
+package com.deliveryproject.easydelivery.Configuration;
+
+import org.keycloak.adapters.springboot.KeycloakSpringBootConfigResolver;
+import org.keycloak.adapters.springsecurity.KeycloakConfiguration;
+import org.keycloak.adapters.springsecurity.authentication.KeycloakAuthenticationProvider;
+import org.keycloak.adapters.springsecurity.config.KeycloakWebSecurityConfigurerAdapter;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Import;
+import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
+import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
+import org.springframework.security.config.annotation.web.builders.HttpSecurity;
+import org.springframework.security.config.http.SessionCreationPolicy;
+import org.springframework.security.core.authority.mapping.SimpleAuthorityMapper;
+import org.springframework.security.web.authentication.session.NullAuthenticatedSessionStrategy;
+
+@KeycloakConfiguration
+@EnableGlobalMethodSecurity(prePostEnabled = true)
+@Import({KeycloakSpringBootConfigResolver.class})
+public class KeycloakAdapterConfig extends KeycloakWebSecurityConfigurerAdapter {
+
+    /* Registers the KeycloakAuthenticationProvider with the authentication manager.*/
+
+    @Autowired
+    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
+        KeycloakAuthenticationProvider keycloakAuthenticationProvider = keycloakAuthenticationProvider();
+        keycloakAuthenticationProvider.setGrantedAuthoritiesMapper(new SimpleAuthorityMapper());
+        auth.authenticationProvider(keycloakAuthenticationProvider);
+    }
+
+    /* Defines the session authentication strategy.*/
+
+    @Bean
+    @Override
+    protected NullAuthenticatedSessionStrategy sessionAuthenticationStrategy() {
+        return new NullAuthenticatedSessionStrategy();
+    }
+
+    @Override
+    protected void configure(HttpSecurity http) throws Exception {
+        super.configure(http);
+        http.csrf().disable().authorizeRequests().anyRequest().authenticated().and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
+    }
+}

+ 33 - 0
src/main/java/com/deliveryproject/easydelivery/KeycloakController.java

@@ -0,0 +1,33 @@
+package com.deliveryproject.easydelivery;
+
+import com.deliveryproject.easydelivery.Configuration.Constants;
+import com.deliveryproject.easydelivery.RequestBody.Token;
+import org.springframework.http.*;
+import org.springframework.util.LinkedMultiValueMap;
+import org.springframework.util.MultiValueMap;
+import org.springframework.web.bind.annotation.*;
+import org.springframework.web.client.RestTemplate;
+
+@RestController
+public class KeycloakController {
+    @RequestMapping(value = "/keycloak/login")
+    @ResponseBody
+    @CrossOrigin(origins = "http://localhost:3000", maxAge = 3600)
+    public ResponseEntity<Token> getToken(@RequestParam String username, @RequestParam String password) {
+        RestTemplate restTemplate = new RestTemplate();
+
+        HttpHeaders headers = new HttpHeaders();
+        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
+
+        MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
+        map.add("client_id", Constants.CLIENT_ID);
+        map.add("grant_type", "password");
+        map.add("username", username);
+        map.add("password", password);
+
+        HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<>(map, headers);
+
+        ResponseEntity<Token> exchange = restTemplate.exchange("http://localhost:8180/auth/realms/SpringBootKeycloak/protocol/openid-connect/token", HttpMethod.POST, entity, Token.class);
+        return exchange;
+    }
+}

+ 2 - 3
src/main/java/com/deliveryproject/easydelivery/MainController.java

@@ -4,6 +4,7 @@ import com.deliveryproject.easydelivery.OSMRClass.Intersection;
 import com.deliveryproject.easydelivery.OSMRClass.Root;
 import com.deliveryproject.easydelivery.OSMRClass.Step;
 import com.fasterxml.jackson.databind.ObjectMapper;
+import org.springframework.security.access.prepost.PreAuthorize;
 import org.springframework.web.bind.annotation.*;
 
 import java.io.BufferedReader;
@@ -16,9 +17,7 @@ import java.util.ArrayList;
 
 @RestController
 public class MainController {
-
-
-
+    @PreAuthorize("hasRole('User')")
     @GetMapping("/route/nodes")
     @ResponseBody
     @CrossOrigin(origins = "http://localhost:3000", maxAge = 3600)

+ 13 - 0
src/main/java/com/deliveryproject/easydelivery/RequestBody/Token.java

@@ -0,0 +1,13 @@
+package com.deliveryproject.easydelivery.RequestBody;
+
+public class Token {
+    public String access_token;
+    public int expires_in;
+    public int refresh_expires_in;
+    public String refresh_token;
+    public String token_type;
+    public int not_before_policy;
+    public String session_state;
+    public String scope;
+
+}

+ 6 - 0
src/main/resources/application.properties

@@ -0,0 +1,6 @@
+keycloak.realm=SpringBootKeycloak
+keycloak.auth-server-url=http://localhost:8181/auth
+keycloak.resource=login-app
+keycloak.public-client=true
+keycloak.bearer-only=true
+keycloak.use-resource-role-mappings=true