首页 > 解决方案 > 带有 msal 的 Angular 将无效令牌发送到后端

问题描述

我有一个 Angular 10 应用程序和 msal 安全库。

我使用 msal 浏览器 2.7.0

我使用了这个例子 https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/samples/msal-angular-v2-samples/angular10-browser-sample/src/app/app。模块.ts

app.module.ts 的一部分

import { MsalInterceptorConfig } from './lib/msal/msal.interceptor.config';
import { MsalBroadcastService, MsalGuard, MsalInterceptor, MsalService, MSAL_INSTANCE } from './lib/msal';
import { MSAL_GUARD_CONFIG, MSAL_INTERCEPTOR_CONFIG } from './lib/msal/constants';
import { MsalGuardConfiguration } from './lib/msal/msal.guard.config';


function MSALInstanceFactory(): IPublicClientApplication {
    return new PublicClientApplication({

        auth: {

          clientId: 'd1851226-abe8-4da6-8332-af8700e0d999',
          redirectUri: 'https://localhost:4200/find',
          authority: 'https://login.microsoftonline.com/4fc25658-87c2-42bf-913c-cb9ae315a768',
          postLogoutRedirectUri: window.location.origin
        }
    });

}

function MSALInterceptorConfigFactory(): MsalInterceptorConfig {
    const protectedResourceMap = new Map<string, Array<string>>();
    protectedResourceMap.set('https://graph.microsoft.com/v1.0/me', ['user.read']);
    protectedResourceMap.set('http://localhost:8080/v2/**', ['openid' ]);
    protectedResourceMap.set('http://localhost:8081/v2/**', ['openid' ]);

    return {
      interactionType: InteractionType.Popup,
  //  interactionType: InteractionType.Redirect,
       protectedResourceMap,
    };

}

@NgModule({

    declarations: [
        AppComponent,
        FormValidationHintComponent
    ],

    imports: [

        AppRoutingModule,
        BrowserModule,
        FontAwesomeModule,
        HttpClientModule,
        DataTablesModule,
        ModalModule,
        FormsModule,
        ReactiveFormsModule,
        BrowserAnimationsModule,
        ToastrModule.forRoot({
        preventDuplicates: true
        }),

        TranslateModule.forRoot({

        loader: {
            provide: TranslateLoader,
            useClass: WebpackTranslateLoader
        },
        defaultLanguage: 'en'
        })
    ],

    providers: [

    DatePipe,
    {
        provide: HTTP_INTERCEPTORS,
        useClass: AppHttpInterceptor,
        multi: true
    },

    {
            provide: APP_INITIALIZER,
            useFactory: initializeApp,
            multi: true,
            deps: [HttpBackend, ConfigurationService]
    },

    {

        provide: HTTP_INTERCEPTORS,
        useClass: MsalInterceptor,
        multi: true
    },

    {
        provide: MSAL_INSTANCE,
        useFactory: MSALInstanceFactory
    },

    {
        provide: MSAL_GUARD_CONFIG,

        useValue: {
        //interactionType: InteractionType.Redirect,
        interactionType: InteractionType.Popup
        } as MsalGuardConfiguration
    },

    {
        provide: MSAL_INTERCEPTOR_CONFIG,
        useFactory: MSALInterceptorConfigFactory
    },

    MsalService,
    MsalGuard,
    MsalBroadcastService
    ],
    bootstrap: [AppComponent]
})

export class AppModule {}

访问令牌它被发送到后端,但是当它响应无效令牌时。我在 jwt.io 上测试过,它说签名无效。

如果我使用 id 令牌,后端响应正确。

我的后端部分

@Configuration
@EnableWebSecurity(debug = true)
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    private JwtAuthenticationConverter jwtAuthenticationConverter() {
        JwtGrantedAuthoritiesConverter jwtGrantedAuthoritiesConverter = new JwtGrantedAuthoritiesConverter();
        jwtGrantedAuthoritiesConverter.setAuthoritiesClaimName("roles");
        jwtGrantedAuthoritiesConverter.setAuthorityPrefix("ROLE_");
        JwtAuthenticationConverter jwtAuthenticationConverter = new JwtAuthenticationConverter();
        jwtAuthenticationConverter.setJwtGrantedAuthoritiesConverter(jwtGrantedAuthoritiesConverter);
        return jwtAuthenticationConverter;
}

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().configurationSource(request -> new CorsConfiguration().applyPermitDefaultValues())
            .and() // (1)
            .authorizeRequests().antMatchers("/api/**").hasRole("level1")
            .anyRequest().authenticated() // (2)
            .and()
            .oauth2ResourceServer().jwt() // (3)
            .jwtAuthenticationConverter(jwtAuthenticationConverter());

    }

}

在我的 application.properties 中,我有

spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://login.microsoftonline.com/4fc25658-87c2-42bf-913c-cb9ae315a768/discovery/v2.0/token

标签: spring-bootspring-securitymsalmsal.jsmsal-angular

解决方案


推荐阅读