Marc Polizzi
Marc Polizzi

Reputation: 9375

MSAL (Java) Rest API Authentication ( Authorization : Bearer Token )

I'd like to secure a Java Rest API against Azure AD B2C.

I understand that the caller is calling the service using the Authorization header with a value like: Bearer xxx-token

Is that an ID or Access Token ?

What are the steps the service should take to ensure this is a valid token? Java code using MSAL4J would be greatly appreciated.

Upvotes: 2

Views: 8518

Answers (2)

sgonzalez
sgonzalez

Reputation: 836

MSAL4J is for acquiring tokens so clients can access protected resources, not for validating tokens in your API.

Your API should be receiving an access token in the authorization header. This article explains what claims might be included in the access token and how to validate them.

Microsoft does not provide a Java library for this validation at the moment, but there are many third-party open source libraries that provide this functionality. For example, you can use jjwt

Upvotes: 3

Jenny
Jenny

Reputation: 1229

Have you seen this MSAL4J B2C sample, which calls a protected web api?

Here in the sample is where it's including the access token, from when the user signed-in and appending it to the header as a Bearer token. Then a middleware library, for example Spring Security for java, will validate the token.

private String callB2CApi(String accessToken){
   RestTemplate restTemplate = new RestTemplate();

   HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        headers.set("Authorization", "Bearer " + accessToken);

    HttpEntity<String> entity = new HttpEntity<>(null, headers);

    String result = restTemplate.exchange(authHelper.configuration.api, HttpMethod.GET,
                entity, String.class).getBody();

     return new Date() + result;
}

Here's more information on using MSAL4J to create a web app which signs-in users and then calls a protected web api. More code samples for calling a protected web api.

Here's an overview of the b2c token types. The idToken contains the claims about the user and the access token provides scoped permission to your web api.

Upvotes: 0

Related Questions