I have this spring boot app and I'm new to spring boot. I have this controller created but it throws 404 and says No mapping for GET /me in the console. I couldn’t find the issue and I need to get this as soon as possible.
Here's the log: https://pastebin.com/Qf5W6MZU
Any other endpoints in this controller also doesn’t work.
import org.sefglobal.scholarx.exception.BadRequestException;
import org.sefglobal.scholarx.exception.NoContentException;
import org.sefglobal.scholarx.exception.ResourceNotFoundException;
import org.sefglobal.scholarx.exception.UnauthorizedException;
import org.sefglobal.scholarx.model.Mentee;
import org.sefglobal.scholarx.model.Profile;
import org.sefglobal.scholarx.model.Program;
import org.sefglobal.scholarx.service.IntrospectionService;
import org.sefglobal.scholarx.util.EnrolmentState;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
#RestController
#RequestMapping("/me")
public class AuthUserController {
private final IntrospectionService introspectionService;
public AuthUserController(IntrospectionService introspectionService) {
this.introspectionService = introspectionService;
}
#GetMapping
#ResponseStatus(HttpStatus.OK)
public Profile getLoggedInUser(#CookieValue(value = "profileId", defaultValue = "-1") long profileId)
throws ResourceNotFoundException, UnauthorizedException {
return introspectionService.getLoggedInUser(profileId);
}
#GetMapping("/programs/mentee")
#ResponseStatus(HttpStatus.OK)
public List<Program> getMenteeingPrograms(#CookieValue(value = "profileId") long profileId)
throws ResourceNotFoundException, NoContentException {
return introspectionService.getMenteeingPrograms(profileId);
}
#PutMapping("/mentor/{id}/confirmation")
#ResponseStatus(HttpStatus.OK)
public Mentee confirmMentor(#PathVariable long id,
#CookieValue(value = "profileId") long profileId)
throws ResourceNotFoundException, BadRequestException {
return introspectionService.confirmMentor(id, profileId);
}
}
I found the issue I haven’t included the package.
Related
I have a problem with Spring boot and Angular. I make a POST request which works on POSTMAN and locally but which gives me a 403 in production on tomcat with apache as reverse proxy. But it's working when I am with the embedded tomcat.
I have to try everything soon.
All the solutions I've seen say to disable CSFR but I have no authentication to access my webservice and therefore no spring-security dependency.
I tried anyway but the problem is still there. And in some cases it required me to log in which I don't want to do
import ch.megahertz.swissqrbillsgeneratorapi.properties.FileStorageProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
#SpringBootApplication(scanBasePackages = {"ch.megahertz.swissqrbillsgeneratorapi.*"})
#EnableConfigurationProperties({
FileStorageProperties.class
})
public class SwissQrBillsGeneratorApiApplication extends SpringBootServletInitializer {
static Logger logger = LoggerFactory.getLogger(SwissQrBillsGeneratorApiApplication.class);
public static void main(String[] args) {
logger.info("Run application");
SpringApplication.run(SwissQrBillsGeneratorApiApplication.class, args);
}
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(SwissQrBillsGeneratorApiApplication.class);
}
}
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
#Configuration
public class WebMvcConfig implements WebMvcConfigurer {
#Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedMethods("*")
.allowedHeaders("*")
.allowedOrigins("*")
.allowCredentials(false)
.maxAge(-1);
}
}
import ch.megahertz.swissqrbillsgeneratorapi.payload.Invoice;
import ch.megahertz.swissqrbillsgeneratorapi.service.CRMService;
import ch.megahertz.swissqrbillsgeneratorapi.service.FileStorageService;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
//#CrossOrigin(origins = {"https://swissqrbillsgenerator.megahertz.ch/","http://localhost:4200/"})
#Slf4j
#RestController
public class ApiController {
private static final Logger logger = LoggerFactory.getLogger(ApiController.class);
#Autowired
private FileStorageService fileStorageService;
#Autowired
private CRMService crmService;
#GetMapping
public String generateQRBills() {
log.info("Enter in GeT API");
return "Get ok";
}
#PostMapping("/generate")
public ResponseEntity<Resource> uploadFile(#RequestParam("file") MultipartFile file) throws IOException {
System.out.println("Enter in generate API");
logger.info("Enter in generate API");
log.info("Enter in generate POST API");
String fileName = fileStorageService.storeFile(file);
String fileDownloadUri = ServletUriComponentsBuilder.fromCurrentContextPath()
.path("/downloadFile/")
.path(fileName)
.toUriString();
Invoice facture = crmService.getFactureInfo(fileName);
File fileWithQR = fileStorageService.addQrToFile(fileName, facture);
Resource resource = new UrlResource(fileWithQR.toURI());
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_TYPE,Files.probeContentType(resource.getFile().toPath()))
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + fileName+ "\"")
.body(resource);
}
}
Do you have any idea?
If Postman is returning the query, then the problem is probably in the Angular front end. I believe I was getting a 403 error when I tried to send a String from my backend, it had to be wrapped in an object and unwrapped by Angular to be a string in Angular.
I'm new to Java and react web development and I'm having an issue with my postBody method. After sending a post request, the console prints the data posted from my frontend correctly, but it shows a whitelabel error page that says (type=Not Found, status=404) in localhost:8080/api and (type=Method Not Allowed, status=405) in localhost:8080/api/data. Below is the HelloController code.
package com.java.java.practice;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.http.MediaType;
import org.springframework.web.cors.CorsConfiguration;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Map;
#RestController
#RequestMapping("/api")
public class HelloController {
//this performes a post and get request
#CrossOrigin(origins = "http://localhost:3000/api")
#PostMapping(value="/n", consumes = MediaType.APPLICATION_JSON_VALUE)
public String postBody(#RequestBody String fullName) {
System.out.println(fullName);
return "Hello " + fullName; //returns response
}
}
Below is the main application
package com.java.java.practice;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
#SpringBootApplication
#ComponentScan(basePackages="com.java.java.practice")
public class PracticeApplication {
public static void main(String[] args) {
SpringApplication.run(PracticeApplication.class, args);
}
}
The weird thing is, when I replace my HelloController code with the one posted underneath, the whitelabel page goes away and shows text on the screen.
package com.java.java.practice;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.http.MediaType;
import org.springframework.web.cors.CorsConfiguration;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Map;
#RestController
public class HelloController {
//this performes a post and get request
#CrossOrigin(origins = "http://localhost:3000/api")
#RequestMapping("/api")
public String postBody() {
return "Hello"; //returns response
}
}
Any help would be much appreciated.
I can see a few issues as below,
When you try to call via a web browser it's always calling as HTTP GET. But in your RestController, there is no GET method. It only has a POST method. Try to use Postman or CURL to call post method instead of GET.
Your URL is wrong. Since you appending /n for the PostMapping annotation it should be (http://localhost:3000/api/n)
Only you want fullName as request body try to use PathVariable instead. No point to use RequestBody only for 1 parameter. Sample code as below.
#PostMapping(value="/{fullName}", consumes = MediaType.APPLICATION_JSON_VALUE)
public String postBody(#PathVariable String fullName) {
System.out.println(fullName);
return "Hello " + fullName; //returns response
}
I am currently working on a spring boot application, and I've got a handler which takes the HttpServletRequest as an argument.
I was wondering, is it possible to invoke a bean that - provided the session cookie - can return the information of who made the request? (e.g. username)
In the end I found this way to make the code work in the desired way.
package org.my.package;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.context.SecurityContextImpl;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.access.AccessDeniedHandlerImpl;
import org.springframework.security.web.csrf.InvalidCsrfTokenException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import static org.springframework.security.web.context.HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY;
#Slf4j
#Configuration
public class CsrfDeniedHandlerConfig {
#AllArgsConstructor
static class CsrfDeniedHandler implements AccessDeniedHandler {
private final AccessDeniedHandler accessDeniedHandler;
#Override
public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
if (accessDeniedException.getClass().equals(InvalidCsrfTokenException.class)) {
SecurityContextImpl securityContext = (SecurityContextImpl) request.getSession().getAttribute(SPRING_SECURITY_CONTEXT_KEY);
User user = (User) securityContext.getAuthentication().getPrincipal();
log.error("Invalid CSRF token request from {}: {}", user.getUsername().toUpperCase(), accessDeniedException.getMessage());
}
accessDeniedHandler.handle(request, response, accessDeniedException);
}
}
#Bean
public AccessDeniedHandler csrfDeniedHandler() {
return new CsrfDeniedHandler(new AccessDeniedHandlerImpl());
}
}
I have a rest controller, which has simple CRUD operations. I am trying to write integration test.
Below is my RestController:
package com.gasx.corex.scheduler.controller;
import java.awt.*;
import java.util.List;
import com.gasx.corex.scheduler.service.SchedulerJobServiceI;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.gasx.corex.ext.scheduler.domain.SchedulerJob;
import com.gasx.corex.scheduler.service.SchedulerJobService;
#RestController
#RequestMapping("/gasx/restscd")
public class SchedulerJobController {
#Autowired
private SchedulerJobServiceI schedulerJobService;
#RequestMapping(method = RequestMethod.GET , path="/getschedulerjobs" , produces= MediaType.APPLICATION_JSON_VALUE)
public List<SchedulerJob> getAllSchedulerJobs() {
return schedulerJobService.getAllSchedulerJobs();
}
#RequestMapping(method = RequestMethod.POST, value = "/addschedulerjob")
public void addSchedulerJob(#RequestBody SchedulerJob schedulerJob) {
schedulerJobService.addSchedulerJob(schedulerJob);
}
#RequestMapping(method = RequestMethod.POST, value = "/updateschedulerjob")
public void updateSchedulerJob(#RequestBody SchedulerJob schedulerJob) {
schedulerJobService.updateSchedulerJob(schedulerJob);
}
#RequestMapping(method = RequestMethod.POST, value = "/deleteschedulerjob")
public void deleteSchedulerJob(#RequestBody SchedulerJob schedulerJob) {
schedulerJobService.deleteSchedulerJob(schedulerJob);
}
}
I have written Integration test for all of the endpoints in RestController
Integration test class :-
package com.gasx.corex.ext.scheduler.integrationtest.domain;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.gasx.corex.base.configuration.CoreConfiguration;
import com.gasx.corex.ext.scheduler.domain.SchedulerJob;
import com.gasx.corex.ext.scheduler.domain.utils.SchedulerJobType;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.context.annotation.Import;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.http.HttpHeaders;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.context.WebApplicationContext;
import sun.security.krb5.internal.Ticket;
import org.springframework.http.HttpMethod;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import java.io.IOException;
import java.util.Base64;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
#RunWith(SpringRunner.class)
#SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT , properties = {
"management.server.port=0", "management.context-path=/admin" ,"security.basic.enabled=false"} )
#EnableAutoConfiguration
#ContextConfiguration( classes = {CoreConfiguration.class } )
#AutoConfigureMockMvc
public class SchedulerJobTestInt {
#LocalServerPort
private int port ;
#Autowired
private TestRestTemplate testRestTemplate;
#Autowired
WebApplicationContext context;
#Autowired
private MockMvc mockMvc;
#Before
public void setUp() {
this.mockMvc = MockMvcBuilders
.webAppContextSetup(context)
.build();
}
#Test
public void getAllSchedulerJobsIntTest() throws Exception {
ResponseEntity<String> response = testRestTemplate.getForEntity("http://localhost:" + port +"/gasx/restscd/getschedulerjobs", String.class);
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
ObjectMapper objectMapper = new ObjectMapper();
JsonNode responseJson = objectMapper.readTree(response.getBody());
assertThat(responseJson.isMissingNode()).isFalse();
assertThat(responseJson.toString()).isEqualTo("[]");
}
#Test
public void addSchedulerJobIntTest() throws Exception{
SchedulerJob schedulerJob = new SchedulerJob();
schedulerJob.setName("ALB Cleanup");
schedulerJob.setDescription("Cleanup of alb jobs. Please do not deactivate!");
schedulerJob.setType(SchedulerJobType.REST);
schedulerJob.setActive(true);
schedulerJob.setStartMissedRun(false);
schedulerJob.setCategory("SYSTEM");
schedulerJob.setCronExpression(null);
schedulerJob.setScheme("testScheme");
schedulerJob.setIdRegion(1);
schedulerJob.setAlbEndpoint("testAlbEndPoint");
schedulerJob.setAlbPayload("SCHED_ALB");
schedulerJob.setAlbPrio(1);
schedulerJob.setAlbJobUser("MKRAUS");
schedulerJob.setScriptParams("testScriptParams");
schedulerJob.setShellScriptParams("clear_tmp 15");
schedulerJob.setSoapEndpointAlias("");
schedulerJob.setSoapImportPath("CORE/CORE2003/imp/price");
schedulerJob.setSoapExportPath("testExportPath");
schedulerJob.setSoapPayload("<api:readPartnersByIdRequest>");
schedulerJob.setSoapAction("urn:readPartnersById");
schedulerJob.setRestEndpointAlias("testEndpointAlias");
schedulerJob.setRestUrl("testUrl");
schedulerJob.setRestEntityContent("");
schedulerJob.setRestExportPath("testRestExportPath");
schedulerJob.setHookScriptName("testHookScriptName");
schedulerJob.setMinutes("");
schedulerJob.setHours("");
String plainCredentials="gasx:gasx!";
String base64Credentials = Base64.getEncoder().encodeToString(plainCredentials.getBytes());
HttpHeaders headers = new HttpHeaders();
headers.add("Authorization", "Basic " + base64Credentials);
headers.add("Accept" , "application/json");
HttpEntity<String> entity = new HttpEntity<String>(asJsonString(schedulerJob), headers);
// ResponseEntity<Void> response = testRestTemplate.postForEntity("http://localhost:"+port +"/gasx/restscd/addschedulerjob", entity,Void.class);
ResponseEntity<Void> response = testRestTemplate.postForEntity("http://localhost:" + port +"/gasx/restscd/addschedulerjob", asJsonString(schedulerJob),Void.class);
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
}
private String createURLWithPort(String uri) {
return "http://localhost:" + port + uri;
}
#Test
public void updateSchedulerJobTest(){
SchedulerJob schedulerJob = new SchedulerJob();
schedulerJob.setName("ALB Cleanup");
schedulerJob.setDescription("Cleanup of alb jobs. Please do not deactivate!");
schedulerJob.setType(SchedulerJobType.REST);
schedulerJob.setActive(true);
schedulerJob.setStartMissedRun(false);
schedulerJob.setCategory("SYSTEM");
schedulerJob.setCronExpression(null);
schedulerJob.setScheme("testScheme");
schedulerJob.setIdRegion(1);
schedulerJob.setAlbEndpoint("testAlbEndPoint");
schedulerJob.setAlbPayload("SCHED_ALB");
schedulerJob.setAlbPrio(1);
schedulerJob.setAlbJobUser("MKRAUS");
schedulerJob.setScriptParams("testScriptParams");
schedulerJob.setShellScriptParams("clear_tmp 15");
schedulerJob.setSoapEndpointAlias("");
schedulerJob.setSoapImportPath("CORE/CORE2003/imp/price");
schedulerJob.setSoapExportPath("testExportPath");
schedulerJob.setSoapPayload("<api:readPartnersByIdRequest>");
schedulerJob.setSoapAction("urn:readPartnersById");
schedulerJob.setRestEndpointAlias("testEndpointAlias");
schedulerJob.setRestUrl("testUrl");
schedulerJob.setRestEntityContent("");
schedulerJob.setRestExportPath("testRestExportPath");
schedulerJob.setHookScriptName("testHookScriptName");
schedulerJob.setMinutes("");
schedulerJob.setHours("");
ResponseEntity<Void> response = testRestTemplate.withBasicAuth("gasx" ,"gasx!").postForEntity("http://localhost:" + port +"/gasx/restscd/updateschedulerjob", schedulerJob,Void.class);
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
}
#Test
public void deleteSchedulerJob(){
SchedulerJob schedulerJob = new SchedulerJob();
schedulerJob.setName("ALB Cleanup");
schedulerJob.setDescription("Cleanup of alb jobs. Please do not deactivate!");
schedulerJob.setType(SchedulerJobType.REST);
schedulerJob.setActive(true);
schedulerJob.setStartMissedRun(false);
schedulerJob.setCategory("SYSTEM");
schedulerJob.setCronExpression(null);
schedulerJob.setScheme("testScheme");
schedulerJob.setIdRegion(1);
schedulerJob.setAlbEndpoint("testAlbEndPoint");
schedulerJob.setAlbPayload("SCHED_ALB");
schedulerJob.setAlbPrio(1);
schedulerJob.setAlbJobUser("MKRAUS");
schedulerJob.setScriptParams("testScriptParams");
schedulerJob.setShellScriptParams("clear_tmp 15");
schedulerJob.setSoapEndpointAlias("");
schedulerJob.setSoapImportPath("CORE/CORE2003/imp/price");
schedulerJob.setSoapExportPath("testExportPath");
schedulerJob.setSoapPayload("<api:readPartnersByIdRequest>");
schedulerJob.setSoapAction("urn:readPartnersById");
schedulerJob.setRestEndpointAlias("testEndpointAlias");
schedulerJob.setRestUrl("testUrl");
schedulerJob.setRestEntityContent("");
schedulerJob.setRestExportPath("testRestExportPath");
schedulerJob.setHookScriptName("testHookScriptName");
schedulerJob.setMinutes("");
schedulerJob.setHours("");
ResponseEntity<Void> response = testRestTemplate.withBasicAuth("gasx" ,"gasx!").postForEntity("http://localhost:" + port +"/gasx/restscd/deleteschedulerjob", schedulerJob,Void.class);
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
}
public static String asJsonString(final Object obj) {
try {
return new ObjectMapper().writeValueAsString(obj);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
My problems:
1.)Wheneever I put breakpoint in Rest Controller, it doesnt' stop there, actually it is not getting invoked.
2.)When I run the test for GET it returns sign-in html page from response.getBody()
3.)When I run the test for POST it returns status 401 unauthorized
tried numerious possible solutions on google
even disabled spring security by commenting the the configuration still it doesn't work.
I can call the same Rest Controller from my Unit test and can stop the breakpoints.
My security configurations:-
package com.gasx.corex.scheduler.server;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
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;
import org.springframework.security.config.http.SessionCreationPolicy;
import com.gasx.corex.ext.user.domain.DefaultRoles;
#Configuration
#EnableWebSecurity
#Order(1)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
// #formatter:off
httpSecurity.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
.httpBasic().and()
.authorizeRequests()
.antMatchers("/gasx/**").hasAnyAuthority(DefaultRoles.ROOT.getName(), DefaultRoles.ADMIN.getName(), DefaultRoles.ACTUATOR.getName())
.antMatchers("/webjars/**").hasAnyAuthority(DefaultRoles.ROOT.getName(), DefaultRoles.ADMIN.getName(), DefaultRoles.ACTUATOR.getName())
.antMatchers("/monitor/**").hasAnyAuthority(DefaultRoles.ROOT.getName(), DefaultRoles.ACTUATOR.getName())
// dev urls
.antMatchers("/h2-console/**").hasAuthority(DefaultRoles.ROOT.getName())
.antMatchers("/swagger*/**","/v2/**").hasAnyAuthority(DefaultRoles.ROOT.getName(), DefaultRoles.ADMIN.getName())
.anyRequest().denyAll();
// #formatter:on
httpSecurity.csrf().disable();
httpSecurity.headers().frameOptions().disable();
}
}
Tried one more thing, added below class to my package :-
package com.gasx.corex.ext.scheduler.integrationtest.domain;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
#Configuration
public class AllowAnonymousWebAccess extends WebSecurityConfigurerAdapter {
#Override
public void configure(HttpSecurity web) throws Exception {
web.antMatcher("**/*").anonymous();
}
}
and now it gives 404.
I don't know anything about this project's SecurityConfiguration (you should provide some more information about it), but I think that you should provide some authorization data (Like a JWT in the Authorization header, or so)
Could you give me some more information about the SecurityConfig? (look for org.springframework.security.config.something.something... imports )
EDIT
I took a look at your code, and actually this part
httpSecurity.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
.httpBasic().and()
.authorizeRequests()
.antMatchers("/gasx/**").hasAnyAuthority(DefaultRoles.ROOT.getName(), DefaultRoles.ADMIN.getName(), DefaultRoles.ACTUATOR.getName())
is protecting your API with an httpBasic type authorization. You shold provide the credentials in the header to test your application.
Try to hit my web service through rest client http://localhost:8080/gurukul/userList but it shows error 'Not Found'.
{
"timestamp": 1462078050576
"status": 404
"error": "Not Found"
"message": "No message available"
"path": "/gurukul/userList"
}
below is My controller in which I add path by RequestMapping but still not found the path after spring-boot
package controller;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import bean.UserList;
import common.Status;
import constants.Constants;
import constants.Messages;
import dao.UserListDAO;
#EnableAutoConfiguration
#Controller
#RestController
#RequestMapping("gurukul")
public class GurukulController {
#RequestMapping(value = "/userList", method = RequestMethod.GET)
#ResponseBody
public Map<String, Object> getUsersList() {
ApplicationContext context = new ClassPathXmlApplicationContext("Spring-Module.xml");
UserListDAO userListDAO = (UserListDAO) context.getBean("userListDAO");
Map<String, Object> resultMap = new HashMap<>();
List<UserList> listResult = userListDAO.getUsers();
if (listResult != null) {
resultMap.put(Constants.RESULT, listResult);
resultMap.put(Constants.STATUS, Status.SUCCESS);
} else {
resultMap.put(Constants.RESULT, Messages.UNABLE_TO_GET_USERS_LIST);
resultMap.put(Constants.STATUS, Status.FAILURE);
}
return resultMap;
}
}
enter code here
your URL should have been http://localhost:8080/context root/Controller class Path/serivice method path
Use http://localhost:8080/context root path/gurukul/userList