azure - Full Authentication Is Requred to Access This Resource - Spring - Microsoft Graph API - App Only Permission - Stack Over

I am doing a project to read emails from Exchange using Microsoft Graph API in Java Spring.So far , I&

I am doing a project to read emails from Exchange using Microsoft Graph API in Java Spring.

So far , I've been following these tutorials :

I've set Mail.Read, Mail.ReadWrite, User.Read.All , all in app-only permission in API Permission, yet still failed.

I also tried Graph with delegated permission , EWS and Jakarta Mail way but keep returning Insufficient priviledge / Authentication Failed. As far as I know , I input email and password correct. Is there something I missing ?

Is there any alternative available ?

EDIT :

I am doing a project to read emails from Exchange using Microsoft Graph API in Java Spring.

So far , I've been following these tutorials :

https://learn.microsoft/en-us/azure/developer/java/identity/enable-spring-boot-webapp-authorization-entra-id

https://learn.microsoft/en-us/graph/tutorials/java?tabs=aad

https://learn.microsoft/en-us/graph/tutorials/java-app-only?tabs=aad

I've set Mail.Read, Mail.ReadWrite, User.Read.All , all in app-only permission in API Permission, yet still failed.

I also tried Graph with delegated permission , EWS and Jakarta Mail way but keep returning Insufficient priviledge / Authentication Failed. As far as I know , I input email and password correct. Is there something I missing ?

Is there any alternative available ?

EDIT :

Share Improve this question edited Nov 20, 2024 at 9:37 Ray asked Nov 20, 2024 at 7:47 RayRay 436 bronze badges 11
  • Could you confirm from what type of user account you are trying to access emails? personal Microsoft account or local account that ends with .onmicrosoft? – Sridevi Commented Nov 20, 2024 at 7:52
  • @Sridevi i am using at company which using exchange .. I've confirmed we are using full cloud service on exchange – Ray Commented Nov 20, 2024 at 8:36
  • Could you edit your question and add Portal images of API permissions from your app registration and user's properties overview image? – Sridevi Commented Nov 20, 2024 at 8:39
  • 1 Could you share the code how do you authenticate? – user2250152 Commented Nov 20, 2024 at 9:15
  • @user2250152 i am following the code just like in the tutorial above, on app-only .. then I change the params of client_id, tenant id and client secret – Ray Commented Nov 20, 2024 at 9:39
 |  Show 6 more comments

1 Answer 1

Reset to default 0

Initially, I registered one application and granted same API permissions of Application type with consent as below:

Now, I created Java Spring project named microsoft-graph-demo using Spring Initializr and added below Maven dependencies:

pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache./POM/4.0.0" xmlns:xsi="http://www.w3./2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache./POM/4.0.0 https://maven.apache./xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.3.6</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>microsoft-graph-demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>microsoft-graph-demo</name>
    <description>microsoft-graph-demo</description>
    <url/>
    <licenses>
        <license/>
    </licenses>
    <developers>
        <developer/>
    </developers>
    <scm>
        <connection/>
        <developerConnection/>
        <tag/>
        <url/>
    </scm>
    <properties>
        <java.version>17</java.version>
        <spring-cloud-azure.version>5.18.0</spring-cloud-azure.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>  
             <groupId>com.azure.spring</groupId>  
             <artifactId>spring-cloud-azure-starter-active-directory</artifactId>  
        </dependency>
        
        <!-- Azure Identity -->
        <dependency>
            <groupId>com.azure</groupId>
            <artifactId>azure-identity</artifactId>
            <version>1.9.0</version>
        </dependency>

        <!-- Microsoft Graph SDK -->
        <dependency>
            <groupId>com.microsoft.graph</groupId>
            <artifactId>microsoft-graph</artifactId>
            <version>5.41.0</version>
        </dependency>
    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>com.azure.spring</groupId>
                <artifactId>spring-cloud-azure-dependencies</artifactId>
                <version>${spring-cloud-azure.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

Open src/main/resources/application.properties and add below properties in it:

azure.graph.client-id=appID 
azure.graph.client-secret=secret
azure.graph.tenant-id=tenantID
spring.security.enabled=false

Now, navigate to src/main/java/com.example.microsoftgraphdemo/ and create classes with below code:

MicrosoftGraphService.java:

package com.example.microsoftgraphdemo;  
  
import com.azure.identity.ClientSecretCredential;  
import com.azure.identity.ClientSecretCredentialBuilder;  
import com.microsoft.graph.authentication.TokenCredentialAuthProvider;  
import com.microsoft.graph.models.Message;  
import com.microsoft.graph.requests.GraphServiceClient;  
import com.microsoft.graph.requests.MessageCollectionPage;  
import .springframework.beans.factory.annotation.Value;  
import .springframework.stereotype.Service;  
  
import java.util.Collections;  
import java.util.List;  
  
@Service  
public class MicrosoftGraphService {  
  
    @Value("${azure.graph.client-id}")  
    private String clientId;  
  
    @Value("${azure.graph.client-secret}")  
    private String clientSecret;  
  
    @Value("${azure.graph.tenant-id}")  
    private String tenantId;  
  
    private GraphServiceClient<?> graphClient;  
  
    // Initialize the Graph client  
  private void initializeGraphClient() {  
        if (graphClient == null) {  
            ClientSecretCredential credential = new ClientSecretCredentialBuilder()  
                    .clientId(clientId)  
                    .clientSecret(clientSecret)  
                    .tenantId(tenantId)  
                    .build();  
  
            TokenCredentialAuthProvider authProvider = new TokenCredentialAuthProvider(  
                    Collections.singletonList("https://graph.microsoft/.default"),  
                    credential  
            );  
  
            graphClient = GraphServiceClient.builder()  
                    .authenticationProvider(authProvider)  
                    .buildClient();  
        }  
    }  
  
    // Fetch emails for a specific user  
  public List<Message> getEmails(String userId) {  
        initializeGraphClient();  
        try {  
            MessageCollectionPage messages = graphClient.users(userId)  
                    .messages()  
                    .buildRequest()  
                    .get();  
  
            return messages.getCurrentPage();  
        } catch (Exception e) {  
            throw new RuntimeException("Error fetching messages: " + e.getMessage(), e);  
        }  
    }  
}

MicrosoftGraphController.java:

package com.example.microsoftgraphdemo;  
  
import com.microsoft.graph.models.Message;  
import .springframework.web.bind.annotation.GetMapping;  
import .springframework.web.bind.annotation.RequestParam;  
import .springframework.web.bind.annotation.RestController;  
  
import java.util.List;  
  
@RestController  
public class MicrosoftGraphController {  
  
    private final MicrosoftGraphService graphService;  
  
    public MicrosoftGraphController(MicrosoftGraphService graphService) {  
        this.graphService = graphService;  
    }  
  
    @GetMapping("/emails")  
    public List<Message> getEmails(@RequestParam String userId) {  
        return graphService.getEmails(userId);  
    }  
}

SecurityConfig.java

package com.example.microsoftgraphdemo;  
  
import .springframework.context.annotation.Bean;  
import .springframework.context.annotation.Configuration;  
import .springframework.security.config.annotation.web.builders.HttpSecurity;  
import .springframework.security.web.SecurityFilterChain;  
  
@Configuration  
public class SecurityConfig {  
  
    @Bean  
  public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {  
        http  
                .authorizeHttpRequests(auth -> auth  
                        .requestMatchers("/emails").permitAll() // Allow public access to `/emails`  
                        .anyRequest().authenticated() // Protect all other endpoints  
  );  
        return http.build();  
    }  
}

When I ran the project and visited http://localhost:8080/emails?userId=<USER-ID> in browser, I got the response with user's emails successfully:

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742373949a4431812.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信