首页 > 解决方案 > 如何在我的 Spring Boot Security OAuth2 应用程序中仅为某些类启用 OAuth2?

问题描述

我按照本指南添加 OAuth2

https://spring.io/guides/tutorials/bookmarks/#_securing_a_rest_service

但现在它要求对每一页进行身份验证!

$ curl -s http://localhost:8080/login 
{"error":"unauthorized","error_description":"Full authentication is required to access this resource"}

我只想在一个特定类的 API 上使用 OAuth2。我尝试阅读 Spring Boot 的参考资料

https://docs.spring.io/spring-boot/docs/1.5.14.BUILD-SNAPSHOT/reference/htmlsingle/#boot-features-security

但这根本没有帮助!它给出了 0 个例子。

要自定义它,您通常使用 WebSecurityConfigurerAdapter 类型的外部属性和 bean(例如添加基于表单的登录)。
以上所有内容都可以使用外部属性(security.*)打开和关闭或修改。要在不更改任何其他自动配置功能的情况下覆盖访问规则,请添加带有 @Order(SecurityProperties.ACCESS_OVERRIDE_ORDER) 的 WebSecurityConfigurerAdapter 类型的 @Bean 并对其进行配置以满足您的需求。

是怎么定制的?!哪些属性?!您如何配置以满足您的需求?!

我试过设置application.properties

security.basic.enabled = false
security.ignored = /login

但它仍然需要 OAuth2 身份验证。我只想为该类启用 OAuth2IShortUrlApiInteface并为所有其他@Controllers.

标签: javaspringspring-bootspring-securityspring-security-oauth2

解决方案


Create a new class, extend ResourceServerConfigurerAdapter, and override method configure(HttpSecurity).

@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

    String [] ignoredPaths = new String[]{
            "/robots.txt", "/error", "/login", "/doLogut", "/home", "/pageNotFound", 
            "/css/**", "/js/**", "/fonts/**", "/img/**", ...
    };

    @Override
    public void configure(HttpSecurity http) throws Exception{

        http.authorizeRequests()
            .antMatchers(ignoredPaths).permitAll()
            .anyRequest().authenticated()
        .and()
            .httpBasic();   
    }

推荐阅读