'Open API with authentication JAVA SpringBoot

We have an application with react + java + spring boot. We have few open apis which can be accessed by anyone(no security/no authentication required) and few secured apis(requires authentication).

I want to expose few APIs to all but I want do authentication for those APIs.

Can someone suggest me what can be done? Should I look more into spring security or checkout spring OPEN-API or is there any other better approach?

Thanks in advance.



Solution 1:[1]

You need to implement spring security in your project. It will allow you apply Filter to your API depending on your users ROLE or AUTHORITY.

Looking at this sample code below, you can see what it looks like:

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.csrf().disable()
            .authorizeRequests()
            .antMatchers("/", "index", "/css/*", "/js/*")
            .permitAll()
            .antMatchers("/api/**").hasRole(STUDENT.name())
            .antMatchers(HttpMethod.DELETE, "/management/api/**").hasAnyAuthority(COURSE_WRITE.getPermission())
            .antMatchers(HttpMethod.POST, "/management/api/**").hasAnyAuthority(COURSE_WRITE.getPermission())
            .antMatchers(HttpMethod.PUT, "/management/api/**").hasAnyAuthority(COURSE_WRITE.getPermission())
            .antMatchers(HttpMethod.GET, "/management/api/**").hasAnyRole(ADMIN.name(), ADMIN_TRAINEE.name())
            .anyRequest()
            .authenticated()
            .and()
            .httpBasic();
}

More details here.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Harry Coder