Clément Drouin
Clément Drouin

Reputation: 197

Validate Azure token in a Spring boot application

I have an application with a React FrontEnd and a spring boot backend. Here is my problem: I have to autorize my frontend in my back with my microsoft token. From here I manage to :

  1. From my front page when I click on my login button it redirect me to azure connection portal (I used msal.js library)

  2. After the redirection, I have an access token.

Now, I want to send this access token to my back (something like /api/auth), call the microsoft graph api to retrieve users informations, create the user in my DataBase if he doesn't exists and then return information with a token that will allow my front to be authorized when it requests protected endpoints

Upvotes: 2

Views: 7850

Answers (2)

Akhildbz
Akhildbz

Reputation: 11

Please use these samples for your reference. Mostly we will use either of the ADD resource server approach.

Hope you have the necessary dependencies in your application(azure-core, azure-spring-boot-starter-active-directory, spring-boot-starter-oauth2-client, spring-boot-starter-oauth2-resource-server and the normal spring web dependency).

The JWT token which you recived through frontend can be attached as a barer token with each request you are making to the spring boot app.

Include the below class for validating the azure JWT token.

import com.azure.spring.aad.webapi.AADJwtBearerTokenAuthenticationConverter;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable().authorizeRequests((requests) -> requests.anyRequest().authenticated())
                .oauth2ResourceServer()
                .jwt()
                .jwtAuthenticationConverter(new AADJwtBearerTokenAuthenticationConverter());
    }
}

In case you come acorss with corss issue please add a filter to attach corss orgin in header. Hope it will help.

Upvotes: 1

Nishant
Nishant

Reputation: 623

Spring Security can be used to validate the token, you can take a look at this sample.

Upvotes: 0

Related Questions