Sharepoint connection with thymeleaf website to retrieve the sharepoint list

Vimales D/O Krishnan 0 Reputation points
2023-06-26T05:39:24.48+00:00
org.springframework.web.client.HttpClientErrorException$Forbidden: 403 Forbidden: "{"odata.error":{"code":"-2147024891, System.UnauthorizedAccessException","message":{"lang":"en-US","value":"Attempted to perform an unauthorized operation."}}}". I get this error when I'm trying to create connection between thymeleaf website spring boot java and sharepoint. How to solve this problem? Please help me. Almost 3 weeks, I'm struggling to find the solution. Thank you.	


Controller
@GetMapping("/sharepoint-data")

	public String getSharePointItems(Model model) {

		List<SharePoint> items= sharePointService.getListItems();

		model.addAttribute("items", items);

		return "views/sharepoint-data";

	}

	    private final RestTemplate restTemplate;

	    public SharePointService(RestTemplateBuilder restTemplateBuilder) {

	        this.restTemplate = restTemplateBuilder.build();

	    }

	    public List<SharePoint> getListItems() {

	        HttpHeaders headers = new HttpHeaders();

//	        headers.set("Accept", "application/json");

	        headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));

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

	        ResponseEntity<SharePoint[]> response = restTemplate.exchange(

	                SHAREPOINT_API_URL,

	                HttpMethod.GET,

	                entity,

	                SharePoint[].class

	        );

	        if (response.getStatusCode() == HttpStatus.OK) {

	            SharePoint[] items = response.getBody();

	            if (items != null) {

	                return Arrays.asList(items);

	            }

	        }

	        return Collections.emptyList();

	    }

sharepoint.html
<!DOCTYPE html>

<html xmlns:th="http://www.thymeleaf.org">

<head>

    <title>SharePoint Items</title>

</head>

<body>

    <h1>SharePoint Items</h1>

    <table>

        <thead>

            <tr>

                <th>ID</th>

                <th>Title</th>

                <!-- Add other column headers if needed -->

            </tr>

        </thead>

        <tbody>

            <tr th:each="item : ${items}">

          <!--      <td th:text="${item.id}"></td> -->

                <td th:text="${item.title}"></td>

                <!-- Display other item properties if needed -->

            </tr>

        </tbody>

    </table>

</body>

  <script src="/assets/js/sharepoint.js"></script>

</html>


WebSecurityConfig
@Bean 

	  public SecurityFilterChain configure(HttpSecurity http) throws Exception { 

		  return http 

				.authorizeRequests(auth -> { 

					auth.antMatchers("/index").permitAll(); 

					auth.antMatchers("/assets/**","/css/**","/js/**","/images/**").permitAll();					 

				    auth.antMatchers("/index", "/article","/bulletin","/barChart","/calendar","/eventss","/healthdata","/leaderboard","/leave","/leavedet","/newsletter","/upcomingEvent", "/sharepoint-files", "/sharepoint-items", "/sharepoint-data").permitAll();			 

				    auth.antMatchers("/newBulletin", "/newEvent", "/newHealthdata", "/newLeave", "/newLeaveDetail", 

				      		"/newNewsletter", "/newUpcomingEvent", "/updateLeave", "/newArticle", 

				      		"/update", "/updateBulletin", "/updateEvent", "/updateHealthdata", "/updateArticle", 

				      		"/updateLeaveDetail", "/updateUpcomingEvent", "/sharepoint-data").permitAll(); 

 

				    auth.antMatchers(HttpMethod.GET, "/article", "/add").permitAll(); 

				     

					//update Option 

					auth.antMatchers(HttpMethod.GET, "/updateArticle/{id}/**").permitAll(); 

					auth.antMatchers(HttpMethod.GET, "/updateBulletin/{id}/**").permitAll(); 

				     

				    //add Option 

				    auth.antMatchers(HttpMethod.GET, "/add").permitAll(); 

				    auth.antMatchers(HttpMethod.GET, "/addEvent/**").permitAll(); 

				    auth.antMatchers(HttpMethod.GET, "/addNew/**").permitAll(); 

				    auth.antMatchers(HttpMethod.GET, "/addBulletin/**").permitAll(); 

				    auth.antMatchers(HttpMethod.GET, "/page/{pageNo").permitAll(); 

	 

				    //save Option 

					auth.antMatchers(HttpMethod.POST, "/saveBulletin").permitAll(); 

					auth.antMatchers(HttpMethod.POST, "/saveArticle").permitAll(); 

					 

					//delete Option 

				    auth.antMatchers(HttpMethod.GET, "/deleteBulletin/{id}/**").permitAll(); 

				    auth.antMatchers(HttpMethod.GET, "/deleteArticle/{id}/**").permitAll(); 

				    auth.antMatchers(HttpMethod.GET, "/deleteEvent/{id}/**").permitAll(); 

				     

				    auth.antMatchers(HttpMethod.GET, "/sharepoint-data").permitAll(); 

				     

				    auth.anyRequest().authenticated(); 

				}) 

 

				.csrf(csrf -> csrf.disable()) 

				.formLogin() 

					.defaultSuccessUrl("/", true) 

					.loginPage("/index") 

				.and() 

				.oauth2Login() 

				.and() 

				.build(); 

	  }

  public void configure(WebSecurity web) throws Exception {

      web

      .ignoring()

      .antMatchers("/static/**")

      .antMatchers("/resources/**")

      .antMatchers("/css/**")     

      .antMatchers("/scripts/**")

      .antMatchers("/images/**");

  }
Microsoft 365 and Office | SharePoint | For business | Windows
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Anonymous
    2023-06-26T06:22:55.1633333+00:00

    Hi @Vimales D/O Krishnan

    The "org.springframework.web.client.HttpClientErrorException$Forbidden: 403 Forbidden" error indicates that a request to SharePoint was denied due to insufficient permissions or unauthorized access. To resolve this issue, you need to ensure that your application has the required permissions to access the SharePoint list data.

    Here are a few steps you can take to troubleshoot and resolve the issue:

    1. Check SharePoint permissions:
    • Verify that the user account or authentication mechanism used by the Spring Boot application has the required permissions to access the SharePoint list.
    • Make sure the account has read permissions to the SharePoint site and target list.
    • If you are using SharePoint Online, make sure the account has been granted the necessary permissions through SharePoint Online Administration.
    1. Using application-only authentication (SharePoint Online):
    • If you're using SharePoint Online, you can use app-only authentication to give apps the permissions they need to access SharePoint resources.
    • Register the application in Azure Active Directory (AAD) and grant the required permissions to the application.
    • Get the client ID and client secret for a registered application.
    • Modify the code to authenticate using app-only authentication. Access tokens can be obtained from client credentials (client ID and client secret) using the Microsoft Authentication Library (MSAL) for Java and included in the request headers.

    If the answer is helpful, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best Regards

    Cheng Feng

    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.