简体   繁体   English

Spring引导oauth2管理httpbasic认证

[英]Spring boot oauth2 management httpbasic authentication

I've got a spring boot application that uses oauth2 for authentication. 我有一个使用oauth2进行身份验证的spring启动应用程序。 The oauth2 mechanism is working and clients can authenticate and receive their access tokens. oauth2机制正在运行,客户端可以验证并接收其访问令牌。

I want to secure the actuators endpoints with httpbasic authentication, ie not requiring the user to first use oauth2 for authentication and then access the actuator endpoints. 我想用httpbasic身份验证来保护执行器端点,即不要求用户首先使用oauth2进行身份验证,然后访问执行器端点。 What i've done so far is to set the following in properties file: 到目前为止我所做的是在属性文件中设置以下内容:

management.context-path=/admin/actuators
management.security.enabled=true
management.security.role=ADMIN

security.user.name=admin
security.user.password=password

I've tried various ways to set configuration with a ResourceServerConfigurerAdapter and WebSecurityConfigurerAdapter. 我已经尝试了各种方法来使用ResourceServerConfigurerAdapter和WebSecurityConfigurerAdapter设置配置。

None of my attempts are working and it keeps on telling me 我的尝试都没有奏效,它一直在告诉我

<oauth>
<error_description>
Full authentication is required to access this resource
</error_description>
<error>unauthorized</error>
</oauth>

What is the correct way to get OAUTH2 and the management endpoint to work? 让OAUTH2和管理端点工作的正确方法是什么?

The problem is that @EnableResourceServer imports ResourceServerConfiguration , which has an order of 3, far superior to ManagementServerProperties.ACCESS_OVERRIDE_ORDER . 问题是@EnableResourceServer导入ResourceServerConfiguration ,其顺序为3,远远优于ManagementServerProperties.ACCESS_OVERRIDE_ORDER
See Spring Boot documentation on actuator security and ordering config classes : http://docs.spring.io/spring-boot/docs/1.4.3.RELEASE/reference/htmlsingle/#boot-features-security-actuator 有关执行器安全性和订购配置类的信息,请参阅Spring Boot文档: http//docs.spring.io/spring-boot/docs/1.4.3.RELEASE/reference/htmlsingle/#boot-features-security-actuator

The default actuator security config is a lot more clever than just allowing access to the /health endpoint and blocking the rest, it actually changes depending on management.port and management.contextPath , and it can get pretty hard to find the correct management endpoint URLs without leaving gaping holes in your security or messing with your own resources. 默认的执行器安全配置比仅允许访问/health端点并阻塞其余部分要聪明得多,它实际上会根据management.portmanagement.contextPath而改变,并且很难找到正确的管理端点URL不会在您的安全措施中留下漏洞或弄乱您自己的资源。

If you want to keep the benefit of the autoconfigured management security, two options : 如果您想保留自动配置的管理安全性的好处,有两个选择:

EDIT : a) Lower ResourceServerConfiguration order using a BeanPostProcessor 编辑:a)使用BeanPostProcessor降低ResourceServerConfiguration顺序

This improvement has been suggested by @dsyer on the github thread : @dsyer在github线程上提出了这种改进:

@Component
@Slf4j
public class ResourceServerConfigurationPostProcessor implements BeanPostProcessor {

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        if (bean instanceof ResourceServerConfiguration) {
            LOGGER.debug("Lowering order of ResourceServerConfiguration bean : {}", beanName);
            ResourceServerConfiguration config = (ResourceServerConfiguration) bean;
            config.setOrder(SecurityProperties.ACCESS_OVERRIDE_ORDER);
        }
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        return bean;
    }

}

I just replaced my code below with this class, and it works perfectly. 我刚用这个类替换了下面的代码,它完美无缺。


EDIT : b) Manually overriding ResourceServerConfiguration order 编辑:b)手动覆盖ResourceServerConfiguration命令

If you don't like post processors for some reason, you can replace the @EnableResourceServer with another configuration class whose order will come after the default management security : 如果由于某种原因不喜欢后处理器,可以将@EnableResourceServer替换为其命令将在默认管理安全性之后的另一个配置类:

/** 
 * Extend the default resource server config class, and downgrade its order
 */
public class ResourceServerLowPrecedenceConfiguration extends ResourceServerConfiguration {

     /**
     * This is enough to override Spring Boot's default resource security,
     * but it does not takes over the management.
     */
    @Override
    public int getOrder() {
        return SecurityProperties.ACCESS_OVERRIDE_ORDER;
    }
}

And your own configuration class : 而你自己的配置类:

/** @EnableResourceServer is replaced by @Import using the low precedence config */
@Configuration
@Import(ResourceServerLowPrecedenceConfiguration.class)
public class YourOwnOAuth2Config extends ResourceServerConfigurerAdapter {
    @Override
    public void configure(final HttpSecurity http) throws Exception {
        // Secure your resources using OAuth 2.0 here
    }
}

EDIT : You can also rewrite your own @EnableResourceServer annotation to shortcut the @Import : 编辑:您还可以改写你自己@EnableResourceServer注释快捷方式@Import

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Import(ResourceServerLowPrecedenceConfiguration.class)
public @interface EnableResourceServer {
}

IMHO this should be the default behavior when spring-security-oauth is on the classpath. 恕我直言,当spring-security-oauth在类路径上时,这应该是默认行为。
See discussion on GitHub issue : https://github.com/spring-projects/spring-boot/issues/5072 请参阅有关GitHub问题的讨论: https//github.com/spring-projects/spring-boot/issues/5072

application.yml中的security.oauth2.resource.filter-order = 3可以解决这个问题

With Spring-Security you can have Multiple HttpSecurity configuration. 使用Spring-Security,您可以拥有多个HttpSecurity配置。

<http pattern="/actuators/**/*" request-matcher="ant" authentication-manager-ref="basicAuthManager">
    <security:intercept-url pattern="/**" access="isAuthenticated()" />
    <http-basic />
<http>
<http use-expressions="false">
   ... your oauth config
</http>

<authentication-manager id="basicAuthManager">
    <authentication-provider>
        <user-service>
            <user name="user1" password="user1Pass" authorities="ROLE_USER" />
        </user-service>
    </authentication-provider>
</authentication-manager>

... your oath config stuff

(I prefere xml, but you can do this with java config too) (我喜欢xml,但你也可以用java配置这样做)

@See http://docs.spring.io/spring-security/site/docs/current/reference/htmlsingle/#nsa-http @参见http://docs.spring.io/spring-security/site/docs/current/reference/htmlsingle/#nsa-http

(But think that you could not do this by plain spring-boot configuration.) (但是认为你不能通过普通的spring-boot配置来做到这一点。)

Ok, got it to work using the following java config. 好的,使用以下java配置使其工作。

The endpoint, /admin/actuators/health, is accessible by anyone and all other /admin/actuators/* endpoints are authenticated. 任何人都可以访问端点/ admin / actuator / health,并且所有其他/ admin / actuator / *端点都经过身份验证。

@Configuration
@Order(1)
protected static class ApiWebSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter {
    protected void configure(HttpSecurity http) throws Exception {

        http
                .authorizeRequests()
                .antMatchers(HttpMethod.GET, "/admin/actuators/health").permitAll()
            .and()
                .antMatcher("/admin/actuators/**")
                .authorizeRequests()
                .anyRequest()
                .hasRole("ADMIN")
                .and()
                .httpBasic();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Spring Boot 结合 OAuth2 和 HttpBasic 登录与自定义表单 - Spring Boot combine OAuth2 and HttpBasic Login with Custom Form 使用Spring Boot在oauth2中进行用户身份验证 - User authentication in oauth2 with Spring Boot Spring开机、zuul、oauth2认证问题 - Spring boot, zuul, oauth2 authentication problem 在 Spring 引导应用程序上启用 Spring JWT 身份验证和 OAuth2 身份验证 - Enable Spring JWT Authentication and OAuth2 Authentication on Spring Boot Application Spring Boot Security OAuth2身份验证服务器和业务服务器的拆分 - Spring Boot Security OAuth2 Authentication server and business server splitting Spring Boot OAuth2具有基本身份验证和自定义UserDetailsS​​ervice - Spring Boot OAuth2 with basic authentication and custom UserDetailsService Spring引导基本身份验证和OAuth2在同一个项目中? - Spring boot Basic Authentication and OAuth2 in same project? 如何使用 Spring Boot feign 客户端进行 Oauth2 身份验证? - How to use Spring Boot feign client for Oauth2 authentication? 使用Spring Boot进行OAuth2身份验证后无法正确重定向 - Unable to properly redirect after OAuth2 authentication using Spring Boot 如何使用Spring Boot将OAuth2身份验证与前端绑定 - How bind angular front with oauth2 authentication with spring boot
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM