I have an extremely simple sample app here: https://github.com/timtebeek/anonymous-principal
Relevant bits copied below:
@Configuration
@EnableResourceServer
public class ResourceConfig extends ResourceServerConfigurerAdapter {
@Override
public void configure(final HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers(HttpMethod.GET, "/**").permitAll()
.anyRequest().denyAll();
// Anonymous user should authenticate as guest for authorization
http.anonymous().principal("guest");
}
@Override
public void configure(final ResourceServerSecurityConfigurer resources) {
resources.resourceId("myresource");
}
}
@SpringBootApplication
@RestController
@SuppressWarnings("static-method")
public class DemoApplication {
public static void main(final String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@RequestMapping(value = "/principal", method = RequestMethod.GET)
public String get(final Principal user) {
Assert.notNull(user);
return user.getName();
}
@RequestMapping(value = "/authprincipal", method = RequestMethod.GET)
public String get(@AuthenticationPrincipal final String user) {
Assert.notNull(user);
return user;
}
@RequestMapping(value = "/authentication", method = RequestMethod.GET)
public String get() {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
Assert.notNull(auth);
return auth.getName();
}
}
In this setup both /authprincipal
and /authentication
work, but /principal
fails when the user is not authenticated, as the principal argument is null
. I'd wanted to use the plain Principal
rest method argument with my anonymous users as well, as that gives me the cleanest code.
What can I do to make Principal
argument in my rest methods work for anonymous users?