由于CORS,角度授权不起作用[重复]

Posted

技术标签:

【中文标题】由于CORS,角度授权不起作用[重复]【英文标题】:Angular authorization doesn't work due to CORS [duplicate] 【发布时间】:2020-02-05 13:41:40 【问题描述】:

我有登录和授权的角度项目,问题是授权不适用于错误消息Access to XMLHttpRequest at 'https://myserver/api/auth' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request.

我已经阅读了有关此主题的几个问题,主要解决方案是直接在浏览器中禁用 CORS 或借助扩展程序。有没有可能以另一种方式解决这个问题,也许用一些角度的代码?

这是我的 login.ts 组件:

import  Component, OnInit  from '@angular/core';
import  Router, ActivatedRoute  from '@angular/router';
import  FormBuilder, FormGroup, Validators  from '@angular/forms';
import  first  from 'rxjs/operators';

import  AuthenticationService  from '@services/auth.service';

@Component(
  selector: 'app-login-page',
  templateUrl: './login-page.component.html',
  styleUrls: ['./login-page.component.css']
)
export class LoginPageComponent implements OnInit 
  loginForm: FormGroup;
  loading = false;
  submitted = false;
  returnUrl: string;
  error = '';

  constructor(
    private formBuilder: FormBuilder,
    private route: ActivatedRoute,
    private router: Router,
    private authenticationService: AuthenticationService
  ) 
    // redirect to home if already logged in
    if (this.authenticationService.currentUserValue) 
      this.router.navigate(['/']);
    
  

  ngOnInit() 
    this.loginForm = this.formBuilder.group(
      username: ['', Validators.required],
      password: ['', Validators.required]
    );

    this.registerForm = this.formBuilder.group(
      email: [''],
      password: [''],
      first_name: [''],
      last_name: [''],
      phone: ['']
    );

    // get return url from route parameters or default to '/'
    this.returnUrl = this.route.snapshot.queryParams['/feed'] || '/';
  

  // convenience getter for easy access to form fields
  get f()  return this.loginForm.controls; 

  onLogin() 
    this.submitted = true;

    // stop here if form is invalid
    if (this.loginForm.invalid) 
      return;
    

    this.loading = true;
    this.authenticationService.login(this.f.username.value, this.f.password.value)
      .pipe(first())
      .subscribe(
        data => 
          this.router.navigate([this.returnUrl]);
        ,
        error => 
          this.error = error;
          this.loading = false;
        );
  

还有 auth.service.ts:

import  Injectable  from '@angular/core';
import  HttpClient  from '@angular/common/http';
import  BehaviorSubject, Observable  from 'rxjs';
import  map  from 'rxjs/operators';

import  environment  from '../../environments/environment';
import  User  from '@models/user.model';

@Injectable( providedIn: 'root' )
export class AuthenticationService 
  private currentUserSubject: BehaviorSubject<User>;
  public currentUser: Observable<User>;

  constructor(private http: HttpClient) 
    this.currentUserSubject = new BehaviorSubject<User>(JSON.parse(localStorage.getItem('currentUser')));
    this.currentUser = this.currentUserSubject.asObservable();
  

  public get currentUserValue(): User 
    return this.currentUserSubject.value;
  

  login(username: string, password: string) 
    return this.http.post<any>(`$environment.apiUrl/api/auth`,  username, password )
      .pipe(map(user => 
        // store user details and jwt token in local storage to keep user logged in between page refreshes
        localStorage.setItem('currentUser', JSON.stringify(user));
        this.currentUserSubject.next(user);
        return user;
      ));
  

  logout() 
    // remove user from local storage to log user out
    localStorage.removeItem('currentUser');
    this.currentUserSubject.next(null);
  

也许我可以通过在我的请求中添加标头来避免这种行为?感谢您的帮助。

【问题讨论】:

【参考方案1】:

是的,禁用 CORS 可能很危险 - 在浏览编码提示时忘记启用它几次。我使用代理解决了这个问题。

    在项目的根文件夹中创建代理配置文件,例如。 proxy.conf.json 内容:

"/api/v1": "target": "https://www.example.com/", "secure": true, "changeOrigin": true

如果端点是 HTTPS,则将安全设置为 true,如果是 HTTP,则设置为 false。上述设置假设您的 API 位于 example.com 的 /api/v1 中。相应调整。

    将 package.json 中的启动命令修改为:

"start": "ng serve --proxy-config proxy.conf.json"

代理仅适用于本地主机。编译后的代码不会调用proxy.conf.json。

【讨论】:

以上是关于由于CORS,角度授权不起作用[重复]的主要内容,如果未能解决你的问题,请参考以下文章

角度和节点应用程序中的 CORS 不起作用

AngularJS和rails cors标头不起作用

飞镖 CORS 不起作用

应用 jwt auth 包装器时,Flask-cors 包装器不起作用。

使用 Spring Security 的 Thymeleaf 授权不起作用[重复]

为啥我的 Express.js 后端的 CORS 设置不起作用?