2

我在这里有一个非常简单的示例应用程序:https ://github.com/timtebeek/anonymous-principal

相关位复制如下:

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();
    }
}

在此设置中,两者都可以/authprincipal工作/authentication,但是/principal当用户未通过身份验证时会失败,因为主要参数是null. 我也想对Principal我的匿名用户使用普通的 rest 方法参数,因为这给了我最干净的代码。

我该怎么做才能使Principal我的休息方法中的参数对匿名用户有用?

4

0 回答 0