无法从启用 cors 的 .net API 上的不同 Angular 项目 URL 获取令牌

问题描述 投票:0回答:1

我能够通过 Postman 接收令牌,但代码给我一个错误:

@Injectable()
export class AuthService {

  constructor(private http: HttpClient) {

  }

  login(username: string, password: string) {
    const httpOptions = {
      headers: new HttpHeaders({
        'Content-Type': 'application/x-www-form-urlencoded'
      })
    };
    const formData = new FormData();
    formData.append('username', username);
    formData.append('password', password);
    formData.append('grant_type', 'password');

    return this.http.post<any>(`${environment.apiUrl}token`, formData, httpOptions)
      .pipe(map(user => this.setSession(user)));
  }

  private setSession(authResult) {
    const expiresAt = moment().add(authResult.expiresIn, 'second');

    localStorage.setItem('id_token', authResult.idToken);
    localStorage.setItem("expires_at", JSON.stringify(expiresAt.valueOf()));
  }
}

我的标题:

:权限:本地主机:44302:方法:POST:路径:/api/token:方案: https 接受:application/json、text/plain、/ 接受编码:gzip、 deflate,br 接受语言:en-US,en;q=0.9 内容长度:372 内容类型:application/x-www-form-urlencoded 来源: https://localhost:44354 引荐来源网址:https://localhost:44354/login sec-fetch-dest:空 sec-fetch-mode:cors sec-fetch-site:同一站点 用户代理:Mozilla/5.0(Windows NT 10.0;Win64;x64) AppleWebKit/537.36(KHTML,如 Gecko)Chrome/80.0.3987.163 野生动物园/537.36

我的错误:

ERROR 
HttpErrorResponse {headers: HttpHeaders, status: 400, statusText: "OK", url: "https://localhost:44302/api/token", ok: false, …}
headers: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, lazyInit: ƒ}
status: 400
statusText: "OK"
url: "https://localhost:44302/api/token"
ok: false
name: "HttpErrorResponse"
message: "Http failure response for https://localhost:44302/api/token: 400 OK"
error: {error: "unsupported_grant_type"}
__proto__: HttpResponseBase

API 令牌部分:

public void ConfigureAuth(IAppBuilder app)
    {
        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
            LoginPath = new PathString("/Account/Login"),
            LogoutPath = new PathString("/Account/LogOff"),
            ExpireTimeSpan = TimeSpan.FromMinutes(5.0),
        });

        app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

        // Configure the application for OAuth based flow  
        PublicClientId = "self";
        OAuthOptions = new OAuthAuthorizationServerOptions
        {
            TokenEndpointPath = new PathString("/API/Token"),
            Provider = new OAuthAppProvider(PublicClientId),
            AuthorizeEndpointPath = new PathString("/Account/ExternalLogin"),
            AccessTokenExpireTimeSpan = TimeSpan.FromHours(4),
            AllowInsecureHttp = true //Don't do this in production ONLY FOR DEVELOPING: ALLOW INSECURE HTTP!  
        };

        app.UseOAuthBearerTokens(OAuthOptions);  
        app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5)); 
        app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);
    }
c# .net angular oauth-2.0 token
1个回答
1
投票

试试这个:

login(username: string, password: string) {
    const httpOptions = {
      headers: new HttpHeaders({
        'Content-Type': 'application/x-www-form-urlencoded'
      })
    };
    const formData = 'grant_type=password&username=' + encodeURIComponent(username) + '&password=' + encodeURIComponent(password);

    return this.http.post<any>(`${environment.apiUrl}token`, formData, httpOptions)
      .pipe(map(user => this.setSession(user)));
  }
© www.soinside.com 2019 - 2024. All rights reserved.