从Angular调用B2C Graph API的步骤如下:
@azure/msal-angular
库,该库提供了与Azure AD B2C进行身份验证的功能。MsalModule
并配置它,包括你的Azure AD B2C租户的相关信息,如客户端ID、授权终结点等。import { MsalModule, MsalInterceptor } from '@azure/msal-angular';
import { HTTP_INTERCEPTORS } from '@angular/common/http';
@NgModule({
imports: [
MsalModule.forRoot({
auth: {
clientId: 'your-client-id',
authority: 'https://your-tenant-name.b2clogin.com/your-tenant-name.onmicrosoft.com/B2C_1A_signup_signin',
redirectUri: 'http://localhost:4200',
},
cache: {
cacheLocation: 'localStorage',
storeAuthStateInCookie: true,
},
}),
],
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: MsalInterceptor,
multi: true,
},
],
})
export class AppModule {}
确保替换clientId
和authority
为你的Azure AD B2C租户的相关值。
MsalService
和HttpClient
,并在构造函数中注入它们。import { MsalService } from '@azure/msal-angular';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-your-component',
templateUrl: './your-component.component.html',
styleUrls: ['./your-component.component.css'],
})
export class YourComponent implements OnInit {
constructor(private msalService: MsalService, private http: HttpClient) {}
ngOnInit(): void {}
callGraphApi(): void {
const accessToken = this.msalService.getAccount()?.idTokenClaims?.accessToken;
this.http.get('https://your-tenant-name.b2clogin.com/your-tenant-name.onmicrosoft.com/B2C_1A_signup_signin/v2.0/your-api-endpoint', {
headers: {
Authorization: `Bearer ${accessToken}`,
},
})
.subscribe((response) => {
console.log(response);
});
}
}
确保替换your-tenant-name
、B2C_1A_signup_signin
和your-api-endpoint
为你的Azure AD B2C租户的相关值和你想要调用的API的端点。
callGraphApi
方法。<button (click)="callGraphApi()">Call Graph API</button>
现在,当用户点击按钮时,Angular应用程序将使用MSAL库进行身份验证,并使用获取的访问令牌调用B2C Graph API。
请注意,这只是一个基本的示例,实际情况可能会更复杂,具体取决于你的应用程序需求和B2C Graph API的配置。
领取专属 10元无门槛券
手把手带您无忧上云