java - Spring Boot - OAuth2 - 所有请求都被禁止

标签 java spring oauth

我有一个 Spring Boot 应用程序,它支持使用 OAuth 的 REST(应用程序和资源服务器)。

MyApplication.java

@SpringBootApplication
@EnableResourceServer
public class MyApplication {
    public static void main(String[] args) {
        SpringApplication.run(MyApplication.class, args);
    }
}

OAuthConfig.java

@Configuration
@EnableAuthorizationServer
public class OAuthConfig extends AuthorizationServerConfigurerAdapter {
    @Autowired
    private UserDetailsService userDetailsService;
    private TokenStore tokenStore = new InMemoryTokenStore();
    @Autowired
    private AuthenticationManager authenticationManager;

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer configurer) throws Exception {
        configurer.authenticationManager(authenticationManager);
        configurer.userDetailsService(userDetailsService);
        configurer.tokenStore(tokenStore);
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients
        .inMemory()
        .withClient("app")
        .secret("secret")
        .accessTokenValiditySeconds(120)
        .refreshTokenValiditySeconds(600)
        .scopes("read", "write")
        .authorizedGrantTypes("password", "refresh_token")
        .resourceIds("resources");
    }
}

SimpleCorsFilter.java

@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class SimpleCorsFilter implements Filter {
    public SimpleCorsFilter() {
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) res;
        HttpServletRequest request = (HttpServletRequest) req;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with, authorization, content-type");

        if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
        } else {
            chain.doFilter(req, res);
        }
    }

    @Override
    public void init(FilterConfig filterConfig) {
    }

    @Override
    public void destroy() {
    }
}

WebSecurityConfig.java

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    public void configure(WebSecurity web) throws Exception {
        web
        .ignoring()
        .antMatchers("/signup");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();
    }
}

TestController.java

@RestController
public class TestController {
    @Autowired
    private PanelService testService;

    @PostMapping("/test")
    public Panel getTest() throws Exception {
        return testService.get();
    }
}

我成功地生成了 token ,并且还能够通过使用上述设置调用refresh_token来获取新 token 。 问题是,无论是否传递 ouath token ,我的其余调用也会返回数据。 /test 始终返回带或不带 token 的数据。

我还在 HTTP 安全性中尝试了不同的选项。即使我使用有效的 token ,下面的代码也总是抛出 Forbidden 。

http.csrf().disable();
.authorizeRequests()
.antMatchers("/signup").permitAll()
.and()
.authorizeRequests()
.anyRequest().authenticated()
.httpBasic();

我做错了什么?

最佳答案

我回答自己的问题是为了帮助所有面临类似问题的人。

在 application.properties 文件中设置以下属性

security.oauth2.resource.filter-order=3

还在 WebSecurityConfigurerAdapter 中添加以下行来配置 HttpSecurity(我不确定这段代码是如何使其工作的 - 我仍在调查)

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
    .sessionManagement()
    .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
    ...
}

下面两个例子引用了上面的代码(引用GitHub代码)

https://medium.com/@nydiarra/secure-a-spring-boot-rest-api-with-json-web-token-reference-to-angular-integration-e57a25806c50

http://www.svlada.com/jwt-token-authentication-with-spring-boot/

关于java - Spring Boot - OAuth2 - 所有请求都被禁止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46600938/

相关文章:

java - 如何让两个数组以完全相同的方式排序,以便

java - 无法使用异步任务将图像加载到 imageview 中

java - 使用 google-guice 注入(inject)列表的最佳方法是什么?

spring - 任何基于 Spring 的网络推送(如通知),我可以在网页中获取通知更新而无需刷新页面吗?

PHP - 使用 Twitter API 1.1 搜索主题标签

java - Spring JPA 查询 findByNameAndType 返回 null

java - Spring JPA 使用单引号内的参数编写 native 查询

java - 用于在 Spring 和 JSF 中检索 session bean 的静态类

c# - 返回无效或过期 token 的错误

authentication - 如何将社交登录集成到我现有的用户架构/登录系统?