2

I have an extremely simple sample app here: https://github.com/timtebeek/anonymous-principal

Relevant bits copied below:

ResourceConfig.java

@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");
    }
}

DemoApplication

@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?

Tim
  • 19,793
  • 8
  • 70
  • 95
  • @AuthenticationPrincipal User user is this work ? – ali akbar azizkhani Mar 23 '17 at 15:25
  • @ali it should, provided you have your UserDetailsProvider setup correctly. Also see the updated Github link and [test results](https://travis-ci.org/timtebeek/anonymous-principal) – Tim Mar 23 '17 at 22:52

0 Answers0