我在这里有一个非常简单的示例应用:https://github.com/timtebeek/anonymous-principal
下面复制的相关位:
@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();
}
}
在此设置中,/authprincipal
和/authentication
都有效,但/principal
在用户未经过身份验证时失败,因为主要参数为null
。我想和我的匿名用户一起使用普通的Principal
rest方法参数,因为这给了我最干净的代码。
如何让我的休息方法中的Principal
参数适用于匿名用户?