lambad
lambad

Reputation: 1066

cors in spring boot app

I have a table called student with column name, password, domain. I have a method in my controller that provides token to student for getting some resources.

@CrossOrigin(origins = "*")
@RequestMapping(value = "/getToken")
public String provideToken() {
  return "tokenvalue"
}

In the database, there are multiple students and multiple student have different domain that calls the above method. E.g. something.com/provideToken?username="user"&password="pass"

In different domain there is a page that calls the above url. Now, How do i make sure that only those domain that are in the database can access above provideToken function.

 public static void main(String[] args) throws InterruptedException {
            SpringApplication.run(Application.class, args);
        }

        @Bean
        public WebMvcConfigurer corsConfigurer() {

            List<User> allUsers = userDao.findAll();
            List<String> originList = new ArrayList<>();
            for(User user: allUsers) {
                originList.add(user.getDomainName());
            }

            return new WebMvcConfigurerAdapter() {
                @Override
                public void addCorsMappings(CorsRegistry registry) {
                    String[] origins = new String[originList.size()];
                    origins = originList.toArray(origins);
                    registry.addMapping("/getToken").allowedOrigins(origins);
                }
            };
        }

Upvotes: 0

Views: 140

Answers (1)

acdcjunior
acdcjunior

Reputation: 135862

You can use a WebMvcConfigurer for programmatic configuration of origins per mapping:

@SpringBootApplication
@RestController
public class MySpringBootApplication {

    @Autowired
    private MyDatabase myDatabase;

    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurerAdapter() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                String[] origins = myDatabase.getAllowedOriginsForGetToken(); // example

                registry.addMapping("/getToken").allowedOrigins(origins);
            }
        };
    }

...

As you can see, it allows you to go to the database (or any other source) for getting the origins information.

Upvotes: 2

Related Questions