我有一个在localhost:// 4200上运行的angular项目和一个在locathost:// 8081上运行的spring boot项目。当我尝试向gmail api发送授权请求时,出现以下错误。
登录:1未能加载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:所请求的资源上没有'Access-Control-Allow-Origin'标头。因此,不允许访问原始“空”。
SecurityConfig.java
@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/**"
};
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable().cors().configurationSource(request -> {
return new CorsConfiguration().applyPermitDefaultValues();
}).and().httpBasic().and().authorizeRequests()
.antMatchers(PUBLIC_MATCHERS).permitAll().anyRequest().authenticated();
}
}
}
RequestFilter.java
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class RequestFilter implements Filter{
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) {
HttpServletRequest request = (HttpServletRequest) req;
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", "x-requested-with, x-auth-token");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Credentials", "true");
if(!(request.getMethod().equalsIgnoreCase("OPTIONS"))) {
try {
chain.doFilter(req, res);
} catch (IOException | ServletException e) {
}
} else {
System.out.println("Pre-fight");
response.setHeader("Access-Control-Allowed-Methods", "POST, GET, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "authorization, content-type, x-auth-token, " +
"access-control-request-headers,access-control-request-method,accept,origin,authorization,x-requested-with");
response.setStatus(HttpServletResponse.SC_OK);
}
}
@Override
public void init(FilterConfig filterConfig) {}
@Override
public void destroy() {}
}
restController中从angular调用的方法
@RequestMapping(value="/gleConsole",method=RequestMethod.GET)
public RedirectView googleConnectionStatus(HttpServletResponse response) throws Exception {
// response.sendRedirect(authorize());
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<>();
return new ResponseEntity(headerColumns, HttpStatus.OK);
}
client.service.ts
gleConsole(){
let url = "http://localhost:8081/gleConsole";
return this.http.get(url,'');
}