【发布时间】:2021-06-01 18:55:34
【问题描述】:
您好,我创建了一个 Angular 应用程序,它连接到 Identity Server 4 以进行身份验证。我使用 AllowedCorsOrigins 注册了 Angular 客户端,并且 Scopes 正在访问 API。我还有其他客户端“.net core MVC”,它们也具有相同的范围(访问 API)。我对 MVC 客户端没有任何问题,但是有角度我收到了 CORS 错误。
身份服务器客户端
new Client
{
ClientId = "clientangularSLO",
ClientName = "Angular Client",
AllowedGrantTypes = GrantTypes.Code,
RequireClientSecret = false,
AllowedScopes = new List<string>
{
IdentityServerConstants.StandardScopes.OpenId,
IdentityServerConstants.StandardScopes.Profile,
"api1",
"roles"
},
RedirectUris = new List<string> {"http://localhost:4200", "http://localhost:4300"},
PostLogoutRedirectUris = new List<string> {"http://localhost:4200", "http://localhost:4300"},
AllowedCorsOrigins = new List<string> { "http://localhost:4200", "http://localhost:4300" },
AccessTokenLifetime = 120, //2mins
RequireConsent= true,
RequirePkce = true,
AllowAccessTokensViaBrowser = true,
AllowOfflineAccess = true,
}
API 范围
public static IEnumerable<ApiScope> ApiScopes =>
new List<ApiScope>
{
new ApiScope("api1", "Test API",new List<string>() { "role" })
};
Angular 客户端 我正在使用 angular-auth-oidc-client 11.5.1
export function configureAuth(oidcConfigService: OidcConfigService) {
return () =>
oidcConfigService.withConfig({
stsServer: 'https://localhost:5001',
redirectUrl: window.location.origin,
clientId: 'clientangularSLO',
scope: 'openid profile api1',
responseType: 'code',
triggerAuthorizationResultEvent: true,
postLogoutRedirectUri: `${window.location.origin}/unauthorized`,
logLevel: LogLevel.Debug,
historyCleanupOff: true,
});
我尝试在 API 中添加 Cors,我不确定这是不是正确的 wasy
API --> StartUp.cs
public void ConfigureServices(IServiceCollection services)
{
//services.AddCors(c =>
//{
// c.AddPolicy("AllowOrigin", options =>
// options.WithOrigins("http://localhost:4200", "http://localhost:4300")
// .AllowAnyMethod()
// .AllowAnyHeader()
// );
//});
services.AddSingleton<ICorsPolicyService>((container) => {
var logger = container.GetRequiredService<ILogger<DefaultCorsPolicyService>>();
return new DefaultCorsPolicyService(logger)
{
//AllowedOrigins = { "http://localhost:4200", "http://localhost:4300" }
AllowAll = true
};
});
services.AddAuthorization(opt =>
{
opt.AddPolicy("Apiscope", policy =>
{
policy.RequireAuthenticatedUser();
policy.RequireClaim("Scope", "api1");
});
});
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseCors(options => options.AllowAnyOrigin());
//app.UseCors(options => options.WithOrigins("http://localhost:4200", "http://localhost:4300"));
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers()
.RequireAuthorization("ApiScope"); //checking the policy "Apiscope"
});
}
HttpInterceptor 添加令牌
private getToken(){
return this.oidcSecurityService.getToken();
}
intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
if(this.tokenValue){
request = request.clone( {
setHeaders: {
Authorization : `Bearer ${this.getToken()}`
}
})
}
return next.handle(request);
}
我正在使用 Angular11 和身份服务器 v4.0.0 。请告诉我,解决这个问题的正确方法。
【问题讨论】:
标签: angular api cors identityserver4