【问题标题】:How to get Jhipster to return different results for authenticated and anonymous users如何让 Jhipster 为经过身份验证的用户和匿名用户返回不同的结果
【发布时间】:2018-04-18 22:45:10
【问题描述】:

我使用 Jhispter 开发了一个搜索 API,如果用户通过身份验证,它会返回带有用户收藏夹的搜索结果(例如图片)。现在我想返回相同的结果,但没有匿名用户的用户收藏。当我在 SecurityConfiguration 中添加到 antMatchers 的路由时,API 变得不安全。虽然我仍在发送令牌,但安全上下文得到一个空值。我想我的问题是如何在发送令牌以获得个性化结果时允许匿名用户但仍然具有安全上下文。

public void configure(WebSecurity web) throws Exception {
    web.ignoring()
        .antMatchers(HttpMethod.OPTIONS, "/**")
        .antMatchers("/v2/api-docs")
        .antMatchers("/swagger-ui/index.html")
        .antMatchers("/api/b2c/register")
        .antMatchers("/api/b2c/activate")
        .antMatchers("/api/b2c/reset_password/init")
        .antMatchers("/api/b2c/reset_password/finish")
        .antMatchers("/api/contact-us")
        .antMatchers("/api/search/picture")
}

@Override
public void configure(HttpSecurity http) throws Exception {
    http
        .httpBasic().realmName("server")
        .and()
            .sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
        .and()
            .requestMatchers().antMatchers("/oauth/authorize")
        .and()
            .authorizeRequests()
            .antMatchers("/oauth/authorize").authenticated();
}

【问题讨论】:

  • Welcome To StackOverflow - 请阅读我们的How to Ask 页面以改进此问题
  • 你能分享你的安全配置吗?
  • 当然。非常感谢。
  • 您可以尝试从web.ignoring() 中删除匹配器并将其添加到具有permitAll() 访问权限的OAuth2ServerConfiguration 中吗?
  • 我已将匹配器从 web ignoring 移至 OAuth2ServerConfiguration 并尝试使用 permitAll() 和匿名访问。仍然是同样的问题,但现在没有令牌访问被拒绝,但使用令牌可以正常工作。

标签: spring spring-security jhipster


【解决方案1】:

尝试从 web.ignoring() 中删除您的匹配器,并将其添加到 OAuth2ServerConfiguration 中具有 permitAll() 访问权限的匹配器

然后注册 OAuth2AuthenticationProcessingFilter 以应用于您的端点。

@Bean
public FilterRegistrationBean customFilterRegistration(OAuth2AuthenticationProcessingFilter oAuth2AuthenticationProcessingFilter) {
    FilterRegistrationBean registration = new FilterRegistrationBean();
    registration.setFilter(oAuth2AuthenticationProcessingFilter);
    registration.addUrlPatterns("/api/search/picture");
    registration.setName("customFilter");
    registration.setOrder(3);
    return registration;
}

【讨论】:

  • 感谢您的回复。我仍然不太确定如何实现这一点以及应该在哪里添加这个 bean。你能澄清一下吗?
  • 你可以在任何你想要的@Configuration 类中添加这个bean。 OAuth2ServerConfiguration 将是一个不错的选择。
【解决方案2】:

问题出在 OAuth2ServerConfiguration 类中的 antmatchers 的顺序上。

.antMatchers("/api/**").authenticated() 应该在具有 permitAll() 访问权限的 antmatchers 之后。

【讨论】:

    猜你喜欢
    • 2018-12-16
    • 2017-04-20
    • 1970-01-01
    • 1970-01-01
    • 2023-03-28
    • 2017-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多