فهرست منبع

Created Cors config and added createUser and getAdminToken endpoints. Refactored the code.

wpfat23-5 2 سال پیش
والد
کامیت
b5a38465a4

+ 10 - 0
pom.xml

@@ -59,6 +59,16 @@
             <groupId>org.keycloak</groupId>
             <groupId>org.keycloak</groupId>
             <artifactId>keycloak-spring-security-adapter</artifactId>
             <artifactId>keycloak-spring-security-adapter</artifactId>
         </dependency>
         </dependency>
+        <dependency>
+            <groupId>org.springframework</groupId>
+            <artifactId>spring-webmvc</artifactId>
+            <version>6.0.7</version>
+        </dependency>
+        <dependency>
+            <groupId>org.springframework</groupId>
+            <artifactId>spring-webmvc</artifactId>
+            <version>5.3.26</version>
+        </dependency>
 
 
 
 
     </dependencies>
     </dependencies>

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

@@ -2,4 +2,7 @@ package com.deliveryproject.easydelivery.Configuration;
 
 
 public class Constants {
 public class Constants {
     public static String CLIENT_ID = "login-app";
     public static String CLIENT_ID = "login-app";
+    public static String ADMIN_USERNAME = "admin";
+    public static String ADMIN_PASSWORD = "admin";
+    public static String KEYCLOAK_ADDRESS = "http://localhost:8181";
 }
 }

+ 9 - 1
src/main/java/com/deliveryproject/easydelivery/Configuration/KeycloakAdapterConfig.java

@@ -7,6 +7,7 @@ import org.keycloak.adapters.springsecurity.config.KeycloakWebSecurityConfigurer
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.context.annotation.Bean;
 import org.springframework.context.annotation.Bean;
 import org.springframework.context.annotation.Import;
 import org.springframework.context.annotation.Import;
+import org.springframework.http.HttpMethod;
 import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
 import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
 import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
 import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
 import org.springframework.security.config.annotation.web.builders.HttpSecurity;
 import org.springframework.security.config.annotation.web.builders.HttpSecurity;
@@ -39,6 +40,13 @@ public class KeycloakAdapterConfig extends KeycloakWebSecurityConfigurerAdapter
     @Override
     @Override
     protected void configure(HttpSecurity http) throws Exception {
     protected void configure(HttpSecurity http) throws Exception {
         super.configure(http);
         super.configure(http);
-        http.csrf().disable().authorizeRequests().anyRequest().authenticated().and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
+        http
+                .csrf()
+                .disable()
+                .authorizeRequests().antMatchers("/keycloak/**").permitAll()
+                .anyRequest().authenticated()
+                .and()
+                .sessionManagement()
+                .sessionCreationPolicy(SessionCreationPolicy.STATELESS);
     }
     }
 }
 }

+ 38 - 0
src/main/java/com/deliveryproject/easydelivery/Configuration/MyCorsConfig.java

@@ -0,0 +1,38 @@
+package com.deliveryproject.easydelivery.Configuration;
+
+import org.springframework.core.Ordered;
+import org.springframework.core.annotation.Order;
+import org.springframework.http.HttpMethod;
+import org.springframework.stereotype.Component;
+
+import javax.servlet.*;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.io.IOException;
+
+@Component
+@Order(Ordered.HIGHEST_PRECEDENCE)
+public class MyCorsConfig implements Filter {
+
+    @Override
+    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
+        final HttpServletResponse response = (HttpServletResponse) res;
+        response.setHeader("Access-Control-Allow-Origin", "*");
+        response.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE");
+        response.setHeader("Access-Control-Allow-Headers", "Authorization, Content-Type, enctype");
+        response.setHeader("Access-Control-Max-Age", "3600");
+        if (HttpMethod.OPTIONS.name().equalsIgnoreCase(((HttpServletRequest) req).getMethod())) {
+            response.setStatus(HttpServletResponse.SC_OK);
+        } else {
+            chain.doFilter(req, res);
+        }
+    }
+
+    @Override
+    public void destroy() {
+    }
+
+    @Override
+    public void init(FilterConfig config) throws ServletException {
+    }
+}

+ 4 - 0
src/main/java/com/deliveryproject/easydelivery/EasyDeliveryApplication.java

@@ -2,6 +2,10 @@ package com.deliveryproject.easydelivery;
 
 
 import org.springframework.boot.SpringApplication;
 import org.springframework.boot.SpringApplication;
 import org.springframework.boot.autoconfigure.SpringBootApplication;
 import org.springframework.boot.autoconfigure.SpringBootApplication;
+import org.springframework.context.annotation.Bean;
+import org.springframework.web.servlet.config.annotation.CorsRegistry;
+import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
+import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
 
 
 @SpringBootApplication
 @SpringBootApplication
 public class EasyDeliveryApplication {
 public class EasyDeliveryApplication {

+ 75 - 2
src/main/java/com/deliveryproject/easydelivery/KeycloakController.java

@@ -8,6 +8,15 @@ import org.springframework.util.MultiValueMap;
 import org.springframework.web.bind.annotation.*;
 import org.springframework.web.bind.annotation.*;
 import org.springframework.web.client.RestTemplate;
 import org.springframework.web.client.RestTemplate;
 
 
+import java.io.*;
+import java.net.HttpURLConnection;
+import java.net.MalformedURLException;
+import java.net.ProtocolException;
+import java.net.URL;
+import java.util.Objects;
+
+import static com.deliveryproject.easydelivery.Configuration.Constants.*;
+
 @RestController
 @RestController
 public class KeycloakController {
 public class KeycloakController {
     @RequestMapping(value = "/keycloak/login")
     @RequestMapping(value = "/keycloak/login")
@@ -27,7 +36,71 @@ public class KeycloakController {
 
 
         HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<>(map, headers);
         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);
+        ResponseEntity<Token> exchange = restTemplate.exchange(KEYCLOAK_ADDRESS + "/auth/realms/SpringBootKeycloak/protocol/openid-connect/token", HttpMethod.POST, entity, Token.class);
         return exchange;
         return exchange;
     }
     }
-}
+
+    @RequestMapping(value = "/keycloak/adminLogin")
+    @ResponseBody
+    public ResponseEntity<Token> getAdminToken() {
+        RestTemplate restTemplate = new RestTemplate();
+
+        HttpHeaders headers = new HttpHeaders();
+        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
+
+        MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
+        map.add("client_id", "admin-cli");
+        map.add("grant_type", "password");
+        map.add("username", ADMIN_USERNAME);
+        map.add("password", ADMIN_PASSWORD);
+
+        HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<>(map, headers);
+
+        ResponseEntity<Token> exchange = restTemplate.exchange(KEYCLOAK_ADDRESS + "/auth/realms/master/protocol/openid-connect/token", HttpMethod.POST, entity, Token.class);
+        return exchange;
+    }
+
+
+    @RequestMapping(value = "/keycloak/createUser")
+    @ResponseBody
+    public void createUser(@RequestParam String username, @RequestParam String password) {
+        try {
+            URL url = new URL(KEYCLOAK_ADDRESS + "/auth/admin/realms/SpringBootKeycloak/users");
+            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
+            conn.setRequestMethod("POST");
+            conn.setRequestProperty("Content-Type", "application/json");
+            conn.setRequestProperty("Authorization", "Bearer " + Objects.requireNonNull(getAdminToken().getBody()).access_token);
+
+            conn.setDoOutput(true);
+
+            String json = "{\n" +
+                    "    \"username\": \"" + username + "\",\n" +
+                    "    \"enabled\": true,\n" +
+                    "    \"credentials\": [\n" +
+                    "        {\n" +
+                    "            \"type\": \"password\",\n" +
+                    "            \"value\": \"" + password + "\",\n" +
+                    "            \"temporary\": false\n" +
+                    "        }\n" +
+                    "    ]\n" +
+                    "}";
+            try (OutputStream os = conn.getOutputStream()) {
+                byte[] input = json.getBytes("utf-8");
+                os.write(input, 0, input.length);
+            }
+
+            BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
+            StringBuilder response = new StringBuilder();
+            String responseLine = null;
+            while ((responseLine = br.readLine()) != null) {
+                response.append(responseLine.trim());
+            }
+            System.out.println(response.toString());
+
+            conn.disconnect();
+        } catch (Exception e) {
+            System.err.println(e);
+        }
+    }
+}
+

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

@@ -14,13 +14,12 @@ import java.net.HttpURLConnection;
 import java.net.URL;
 import java.net.URL;
 import java.util.ArrayList;
 import java.util.ArrayList;
 
 
-
+@CrossOrigin
 @RestController
 @RestController
 public class MainController {
 public class MainController {
     @PreAuthorize("hasRole('User')")
     @PreAuthorize("hasRole('User')")
     @GetMapping("/route/nodes")
     @GetMapping("/route/nodes")
     @ResponseBody
     @ResponseBody
-    @CrossOrigin(origins = "http://localhost:3000", maxAge = 3600)
     public ArrayList<ArrayList<Double>> getNodesBetweenTwoCoordinates(@RequestParam double lon1, @RequestParam double lat1, @RequestParam double lon2, @RequestParam double lat2) throws IOException {
     public ArrayList<ArrayList<Double>> getNodesBetweenTwoCoordinates(@RequestParam double lon1, @RequestParam double lat1, @RequestParam double lon2, @RequestParam double lat2) throws IOException {
         System.out.println(lon1);
         System.out.println(lon1);
         String url = "http://router.project-osrm.org/route/v1/driving/" + lon1 + "," + lat1 + ";" + lon2 + "," + lat2 + "?steps=true&geometries=geojson";
         String url = "http://router.project-osrm.org/route/v1/driving/" + lon1 + "," + lat1 + ";" + lon2 + "," + lat2 + "?steps=true&geometries=geojson";
@@ -61,3 +60,4 @@ public class MainController {
 
 
 
 
 }
 }
+