RedirectView view not working with spring security

738 views
Skip to first unread message

eshwar chettri

unread,
Aug 7, 2018, 8:36:31 AM8/7/18
to AdWords Scripts Forum
Hi,
I want to redirect to gmail allow access page , I am using spring security Iam not understanding is it causing any problem or I my self doing any error 
here is my code.

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.netelixir.controller;

import com.google.api.client.auth.oauth2.AuthorizationCodeRequestUrl;
import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.auth.oauth2.TokenResponse;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.gmail.GmailScopes;
import com.google.api.services.gmail.model.ListMessagesResponse;
import com.netelixir.config.SecurityUtility;
import com.netelixir.domain.User;
import com.netelixir.domain.security.Role;
import com.netelixir.domain.security.UserRole;
import com.netelixir.model.ClientInfoService;
import com.netelixir.model.HeaderMappingDetails;
import com.netelixir.service.GmailService;
import com.netelixir.service.UserService;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.view.RedirectView;

/**
 *
 * @author netelixir
 */
@RestController
@Configuration
@PropertySource(value = {"classpath:application.properties"})
@RequestMapping("/user")
public class AddClientController {

    private static final Log LOGGER = LogFactory.getLog(AddClientController.class);
    @Value("${gmail.client.clientId}")
    private String CLIENT_ID;

    @Value("${gmail.client.redirectUri}")
    private String REDIRECT_URI;

    @Value("${gmail.client.clientSecret}")
    private String CLIENT_SECRET;

    GoogleClientSecrets clientSecrets;
    GoogleAuthorizationCodeFlow flow;
    Credential credential;
    private static HttpTransport httpTransport;
    private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();

    @Autowired
    private UserService userService;

    @Autowired
    GmailService gmailService;

    @Autowired
    ClientInfoService clientInformationService;

    @RequestMapping(value = "/newUser", method = RequestMethod.POST)
    public ResponseEntity addNewClient(HttpServletRequest request, @RequestBody HashMap<String, String> mapper, HttpSession session, HttpServletResponse response) {
        String username = mapper.get("username");
        String password = mapper.get("password");
        String email = mapper.get("email");
        if (userService.findByUsername(username) != null) {
            return new ResponseEntity("usernameExists", HttpStatus.BAD_REQUEST);
        }

        if (userService.findByEmail(email) != null) {
            return new ResponseEntity("emailExists", HttpStatus.BAD_REQUEST);
        }
        User user = new User();
        user.setUsername(username);
        user.setEmail(email);
        user.setPassword(SecurityUtility.passwordEncoder().encode(password));

        Role role = new Role();
        role.setRoleId(1);
        role.setName("ROLE_USER");
        Set<UserRole> userRoles = new HashSet<>();
        userRoles.add(new UserRole(user, role));
        User newUser = userService.createUser(user, userRoles);
        RedirectView redirectView = new RedirectView();
        if (userService.findByUsername(username) != null) {
            try {
                session.setAttribute("clientId", newUser.getId());
                session.setAttribute("clientEmailId", newUser.getEmail());
                redirectView = googleConnectionStatus(response);
                LOGGER.info(redirectView.getUrl());
              response.sendRedirect(redirectView.getUrl());    
             return null;           
            } catch (Exception ex) {
                Logger.getLogger(AddClientController.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

        return new ResponseEntity(redirectView.getUrl(), HttpStatus.OK);
    }

    public RedirectView googleConnectionStatus(HttpServletResponse response) throws Exception {
             return new RedirectView(authorize());
    }

    private String authorize() throws Exception {
        AuthorizationCodeRequestUrl authorizationUrl;
        if (flow == null) {
            GoogleClientSecrets.Details web = new GoogleClientSecrets.Details();
            web.setClientId(CLIENT_ID);
            web.setClientSecret(CLIENT_SECRET);
            clientSecrets = new GoogleClientSecrets().setWeb(web);
            httpTransport = GoogleNetHttpTransport.newTrustedTransport();
            flow = new GoogleAuthorizationCodeFlow.Builder(httpTransport, JSON_FACTORY, clientSecrets,
                    Collections.singleton(GmailScopes.GMAIL_READONLY)).build();
        }
        authorizationUrl = flow.newAuthorizationUrl().setRedirectUri(REDIRECT_URI).setAccessType("offline").setApprovalPrompt("force");

        System.out.println("gamil authorizationUrl ->" + authorizationUrl);
        return authorizationUrl.build();
    }

    @RequestMapping(value = "user/login/gmailCallback", method = RequestMethod.GET, params = "code")
    public ResponseEntity<Map<String, ArrayList<String>>> oauth2Callback(@RequestParam(value = "code") String code, HttpSession session, Model model) {
        Map<String, ArrayList<String>> headerColumns = new LinkedHashMap<>();
        try {
            TokenResponse response = flow.newTokenRequest(code).setRedirectUri(REDIRECT_URI).execute();
            credential = flow.createAndStoreCredential(response, "userID");
            Integer clientId = (Integer) session.getAttribute("clientId");
            clientInformationService.saveTokens(response, clientId);
            ListMessagesResponse MsgResponse = gmailService.getGmailMessage(credential, clientId);
            headerColumns = gmailService.readMessgeAndProcess(session, MsgResponse, false, clientId);
        } catch (IOException e) {

            LOGGER.debug("error is due to: " + e);

        }
        session.setAttribute("headerColumns", headerColumns);
        model.addAttribute("headerColumns", headerColumns);
        model.addAttribute("clientId", session.getAttribute("clientId"));
        model.addAttribute("emailId", session.getAttribute("clientEmailId"));
        model.addAttribute("mapHeaders", new HeaderMappingDetails());
        return new ResponseEntity(headerColumns, HttpStatus.OK);
    }

}


SecurityConfig.java


package com.netelixir.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

import com.netelixir.service.UserSecurityService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClientService;
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
import org.springframework.session.web.http.HeaderHttpSessionIdResolver;
import org.springframework.session.web.http.HttpSessionIdResolver;
import java.util.List;


@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private Environment env;

    @Autowired
    private UserSecurityService userSecurityService;

    private PasswordEncoder passwordEncoder() {
        return SecurityUtility.passwordEncoder();
    }

    private static final String[] PUBLIC_MATCHERS = {
        "/css/**",
        "/js/**",
        "/user/**",
        "/o/**"
    };

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable().cors().disable().httpBasic().and().authorizeRequests()
                .antMatchers(PUBLIC_MATCHERS).permitAll().anyRequest().authenticated().and().oauth2Login();
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userSecurityService).passwordEncoder(passwordEncoder());
    }

    @Bean
    public HttpSessionIdResolver httpSessionIdResolver() {
        return HeaderHttpSessionIdResolver.xAuthToken();
    }
    }
Even I tried to redirect from angular but its throwing an error 

Failed to load https://accounts.google.com/o/oauth2/auth?access_type=offline&approval_prompt=force&client_id=954782724108-ifm1o8if53ma6g6saalvn1suj20i5dqh.apps.googleusercontent.com&redirect_uri=http://localhost:8081/user/login/gmailCallback&response_type=code&scope=https://www.googleapis.com/auth/gmail.readonly: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. The response had HTTP status code 405.

gleConsole(gleUrl: string){    
    let url = gleUrl;
    let tokenHeader = new Headers({
  'Content-Type' : 'application/json',
  'x-auth-token' : localStorage.getItem('xAuthToken')
  });
  return this.http.get(url,{headers: headers});
    
}

Anthony Madrigal

unread,
Aug 7, 2018, 2:53:51 PM8/7/18
to AdWords Scripts Forum
Hi Eshwar,

This issue doesn't appear to be AdWords Scripts related. It looks like you are trying to connect to Gmail redirect via Spring Boot. For help on this, I suggest reaching out to the Gmail support team.

Regards,
Anthony
AdWords Scripts Team
Reply all
Reply to author
Forward
0 new messages