فهرست منبع

Fix oAuth authentication

Blazej 3 سال پیش
والد
کامیت
43c6ae39c3

+ 1 - 1
src/main/java/com/example/plantsforyou/appuser/AppUser.java

@@ -65,7 +65,7 @@ public class AppUser implements UserDetails {
         this.email = email;
         this.appUserRole = appUserRole;
         this.oAuth = true;
-        this.password = null;
+        this.password = "none";
         this.enabled = true;
     }
 

+ 21 - 8
src/main/java/com/example/plantsforyou/filter/CustomAuthenticationFilter.java

@@ -5,9 +5,12 @@ import com.auth0.jwt.algorithms.Algorithm;
 import com.example.plantsforyou.appuser.AppUser;
 import com.example.plantsforyou.appuser.LoginCredentials;
 import com.example.plantsforyou.oAuth.oAuthService;
+import com.example.plantsforyou.registration.RegistrationService;
 import com.fasterxml.jackson.databind.ObjectMapper;
 import com.google.api.client.googleapis.auth.oauth2.GoogleIdToken;
 import lombok.extern.slf4j.Slf4j;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Configurable;
 import org.springframework.security.authentication.AuthenticationManager;
 import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
 import org.springframework.security.core.Authentication;
@@ -16,8 +19,13 @@ import org.springframework.security.core.GrantedAuthority;
 import org.springframework.security.core.userdetails.UserDetails;
 import org.springframework.security.core.userdetails.UsernameNotFoundException;
 import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
+import org.springframework.stereotype.Component;
+import org.springframework.web.context.WebApplicationContext;
+import org.springframework.web.context.support.SpringBeanAutowiringSupport;
+import org.springframework.web.context.support.WebApplicationContextUtils;
 
 import javax.servlet.FilterChain;
+import javax.servlet.ServletContext;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
 import java.io.BufferedReader;
@@ -26,6 +34,7 @@ import java.security.GeneralSecurityException;
 import java.util.Date;
 import java.util.HashMap;
 import java.util.Map;
+import java.util.Optional;
 import java.util.stream.Collectors;
 
 import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;
@@ -34,8 +43,8 @@ import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;
 public class CustomAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
     private final AuthenticationManager authenticationManager;
     private final ObjectMapper objectMapper = new ObjectMapper();
-    private final oAuthService authService = new oAuthService();
 
+    private oAuthService authService;
 
     public CustomAuthenticationFilter(AuthenticationManager authenticationManager){
         this.authenticationManager = authenticationManager;
@@ -44,6 +53,11 @@ public class CustomAuthenticationFilter extends UsernamePasswordAuthenticationFi
     @Override
     public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) {
         log.info("New login request!");
+        if(authService == null){
+            ServletContext servletContext = request.getServletContext();
+            WebApplicationContext webApplicationContext = WebApplicationContextUtils.getWebApplicationContext(servletContext);
+            authService = webApplicationContext.getBean(oAuthService.class);
+        }
         try {
             BufferedReader reader = request.getReader();
             StringBuilder stringBuilder = new StringBuilder();
@@ -63,15 +77,13 @@ public class CustomAuthenticationFilter extends UsernamePasswordAuthenticationFi
                 GoogleIdToken idToken = authService.validate(password);
                 if(idToken != null) {
                     GoogleIdToken.Payload payload =  idToken.getPayload();
-                    try {
-                        UserDetails userDetails = authService.findByEmail(payload.getEmail());
-                        authenticationToken = new UsernamePasswordAuthenticationToken(userDetails.getUsername(), null);
-                    }
-                    catch(UsernameNotFoundException e){
+                    String payloadEmail = payload.getEmail();
+                    String payloadName = (String) payload.get("name");
+                    if(!authService.findByEmail(payloadEmail).isPresent()){
                         authService.singUpUser(payload);
-                        authenticationToken = new UsernamePasswordAuthenticationToken(payload.getEmail(), null);
-
                     }
+                    AppUser user = authService.findByEmail(payloadEmail).get();
+                    authenticationToken = new UsernamePasswordAuthenticationToken(user.getUsername(), "none");
                 }
             }
             else{
@@ -84,6 +96,7 @@ public class CustomAuthenticationFilter extends UsernamePasswordAuthenticationFi
             throw new IllegalStateException(e.getMessage());
         }
         catch(IOException e){
+            log.error(e.getMessage());
             throw new IllegalArgumentException(e.getMessage());
         } catch (GeneralSecurityException e) {
             throw new IllegalStateException(e.getMessage());

+ 13 - 5
src/main/java/com/example/plantsforyou/oAuth/oAuthService.java

@@ -8,10 +8,15 @@ import com.example.plantsforyou.appuser.AppUserService;
 import com.google.api.client.googleapis.auth.oauth2.GoogleIdToken;
 import com.google.api.client.googleapis.auth.oauth2.GoogleIdTokenVerifier;
 import com.google.api.client.http.HttpTransport;
+import com.google.api.client.http.javanet.NetHttpTransport;
 import com.google.api.client.json.JsonFactory;
+import com.google.api.client.json.gson.GsonFactory;
 import lombok.AllArgsConstructor;
 import lombok.RequiredArgsConstructor;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.Bean;
 import org.springframework.security.core.userdetails.UserDetails;
+import org.springframework.stereotype.Component;
 import org.springframework.stereotype.Service;
 
 import javax.servlet.http.HttpServletRequest;
@@ -22,13 +27,16 @@ import java.util.Optional;
 
 @Service
 public class oAuthService {
-    HttpTransport transport;
-    JsonFactory factory;
-    AppUserService userService;
+    private AppUserService userService;
+
+    @Autowired
+    private void setUserService(AppUserService userService){
+        this.userService = userService;
+    }
 
     public GoogleIdToken validate(String token) throws GeneralSecurityException, IOException {
         try {
-            GoogleIdTokenVerifier verifier = new GoogleIdTokenVerifier.Builder(transport, factory)
+            GoogleIdTokenVerifier verifier = new GoogleIdTokenVerifier.Builder(new NetHttpTransport(), new GsonFactory())
                     .setAudience(Collections.singletonList("676799456601-hu3k0k4ko7h7s52t8p7quk7kqho87umb.apps.googleusercontent.com"))
                     .build();
             return verifier.verify(token);
@@ -37,7 +45,7 @@ public class oAuthService {
             return null;
         }
     }
-    public UserDetails findByEmail(String email){ return userService.loadUserByUsername(email); }
+    public Optional<AppUser> findByEmail(String email){ return userService.getAppUser(email); }
 
     public void singUpUser(GoogleIdToken.Payload payload){
         AppUser user = new AppUser((String) payload.get("name"), (String) payload.get("family_name"), payload.getEmail(), AppUserRole.USER);