Spring boot 如何限制OAuth2设置中定义的客户端访问?

Spring boot 如何限制OAuth2设置中定义的客户端访问?,spring-boot,spring-security,jhipster,spring-security-oauth2,Spring Boot,Spring Security,Jhipster,Spring Security Oauth2,在使用SpingBoot和OAuth2开发的RESTAPI中,是否可以根据授权服务器设置中定义的客户端限制用户访问 例如,在授权服务器中,我有以下客户端配置: clients.inMemory() .withClient(uaaProperties.getWebClientConfiguration().getClientId()) .secret(passwordEncoder.encode(uaaProperties.getWebClientC

在使用SpingBoot和OAuth2开发的RESTAPI中,是否可以根据授权服务器设置中定义的客户端限制用户访问

例如,在授权服务器中,我有以下客户端配置:

clients.inMemory()
            .withClient(uaaProperties.getWebClientConfiguration().getClientId())
            .secret(passwordEncoder.encode(uaaProperties.getWebClientConfiguration().getSecret()))
            .scopes("openid")
            .authorities("ROLE_TESTE")
            .autoApprove(true)
            .authorizedGrantTypes("implicit","refresh_token", "password", "authorization_code")
            .accessTokenValiditySeconds(accessTokenValidity)
            .refreshTokenValiditySeconds(refreshTokenValidity)
@Override
public void configure(HttpSecurity http) throws Exception {
http
    .csrf() 
    .ignoringAntMatchers("/h2-console/**")
    .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
.and()
    .addFilterBefore(corsFilter, CsrfFilter.class)
    .headers()
    .frameOptions()
    .disable()
.and()
    .sessionManagement()
    .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
    .authorizeRequests()
    .antMatchers("/api/**").hasAuthority(AuthoritiesConstants.ADMIN)
    .antMatchers("/management/health").permitAll()
    .antMatchers("/management/info").permitAll()
    .antMatchers("/management/**").hasAuthority(AuthoritiesConstants.ADMIN);
}
在HttpSecurity中Spring的安全配置部分,我有以下配置:

clients.inMemory()
            .withClient(uaaProperties.getWebClientConfiguration().getClientId())
            .secret(passwordEncoder.encode(uaaProperties.getWebClientConfiguration().getSecret()))
            .scopes("openid")
            .authorities("ROLE_TESTE")
            .autoApprove(true)
            .authorizedGrantTypes("implicit","refresh_token", "password", "authorization_code")
            .accessTokenValiditySeconds(accessTokenValidity)
            .refreshTokenValiditySeconds(refreshTokenValidity)
@Override
public void configure(HttpSecurity http) throws Exception {
http
    .csrf() 
    .ignoringAntMatchers("/h2-console/**")
    .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
.and()
    .addFilterBefore(corsFilter, CsrfFilter.class)
    .headers()
    .frameOptions()
    .disable()
.and()
    .sessionManagement()
    .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
    .authorizeRequests()
    .antMatchers("/api/**").hasAuthority(AuthoritiesConstants.ADMIN)
    .antMatchers("/management/health").permitAll()
    .antMatchers("/management/info").permitAll()
    .antMatchers("/management/**").hasAuthority(AuthoritiesConstants.ADMIN);
}
如何限制具有“ROLE_TESTE”权限的OAuth客户机不访问仅为ADMIN设置的api地址

已编辑…

我对代码进行了如下编辑:

UAA/OAuth2:

@Configuration
@EnableAuthorizationServer
public class UaaConfiguration extends AuthorizationServerConfigurerAdapter implements ApplicationContextAware {
    /**
     * Access tokens will not expire any earlier than this.
     */
    private static final int MIN_ACCESS_TOKEN_VALIDITY_SECS = 60;

    private ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    @EnableResourceServer
    public static class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {

        private final TokenStore tokenStore;

        private final JHipsterProperties jHipsterProperties;

        private final CorsFilter corsFilter;

        public ResourceServerConfiguration(TokenStore tokenStore, JHipsterProperties jHipsterProperties, CorsFilter corsFilter) {
            this.tokenStore = tokenStore;
            this.jHipsterProperties = jHipsterProperties;
            this.corsFilter = corsFilter;
        }

        @Override
        public void configure(HttpSecurity http) throws Exception {
            http
                .exceptionHandling()
                .authenticationEntryPoint((request, response, authException) -> response.sendError(HttpServletResponse.SC_UNAUTHORIZED))
            .and()
                .csrf()
                .disable()
                .addFilterBefore(corsFilter, UsernamePasswordAuthenticationFilter.class)
                .headers()
                .frameOptions()
                .disable()
            .and()
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .and()
                .authorizeRequests()
                .antMatchers("/api/register").permitAll()
                .antMatchers("/api/activate").permitAll()
                .antMatchers("/api/authenticate").permitAll()
                .antMatchers("/api/account/reset-password/init").permitAll()
                .antMatchers("/api/account/reset-password/finish").permitAll()
//                .antMatchers("/api/**").authenticated()
                .antMatchers("/management/health").permitAll()
                .antMatchers("/management/**").hasAuthority(AuthoritiesConstants.ADMIN)
                .antMatchers("/v2/api-docs/**").permitAll()
                .antMatchers("/swagger-resources/configuration/ui").permitAll()
                .antMatchers("/swagger-ui/index.html").hasAuthority(AuthoritiesConstants.ADMIN)
                .antMatchers("/api/**").access("#oauth2.clientHasRole('ROLE_TESTE')")
                ;
        }

        @Override
        public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
            resources.resourceId("jhipster-uaa").tokenStore(tokenStore);
        }
    }

    private final JHipsterProperties jHipsterProperties;

    private final UaaProperties uaaProperties;

    private final PasswordEncoder passwordEncoder;

    public UaaConfiguration(JHipsterProperties jHipsterProperties, UaaProperties uaaProperties, PasswordEncoder passwordEncoder) {
        this.jHipsterProperties = jHipsterProperties;
        this.uaaProperties = uaaProperties;
        this.passwordEncoder = passwordEncoder;
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        int accessTokenValidity = uaaProperties.getWebClientConfiguration().getAccessTokenValidityInSeconds();
        accessTokenValidity = Math.max(accessTokenValidity, MIN_ACCESS_TOKEN_VALIDITY_SECS);
        int refreshTokenValidity = uaaProperties.getWebClientConfiguration().getRefreshTokenValidityInSecondsForRememberMe();
        refreshTokenValidity = Math.max(refreshTokenValidity, accessTokenValidity);
        /*
        For a better client design, this should be done by a ClientDetailsService (similar to UserDetailsService).
         */
        clients.inMemory()
            .withClient(uaaProperties.getWebClientConfiguration().getClientId())
            .secret(passwordEncoder.encode(uaaProperties.getWebClientConfiguration().getSecret()))
            .scopes("openid")
            .authorities("ROLE_TESTE")
            .autoApprove(true)
            .authorizedGrantTypes("implicit","refresh_token", "password", "authorization_code")
            .accessTokenValiditySeconds(accessTokenValidity)
            .refreshTokenValiditySeconds(refreshTokenValidity)
            .and()
            .withClient(jHipsterProperties.getSecurity().getClientAuthorization().getClientId())
            .secret(passwordEncoder.encode(jHipsterProperties.getSecurity().getClientAuthorization().getClientSecret()))
            .scopes("web-app")
            .authorities("ROLE_ADMIN")
            .autoApprove(true)
            .authorizedGrantTypes("client_credentials")
            .accessTokenValiditySeconds((int) jHipsterProperties.getSecurity().getAuthentication().getJwt().getTokenValidityInSeconds())
            .refreshTokenValiditySeconds((int) jHipsterProperties.getSecurity().getAuthentication().getJwt().getTokenValidityInSecondsForRememberMe());
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        //pick up all  TokenEnhancers incl. those defined in the application
        //this avoids changes to this class if an application wants to add its own to the chain
        Collection<TokenEnhancer> tokenEnhancers = applicationContext.getBeansOfType(TokenEnhancer.class).values();
        TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
        tokenEnhancerChain.setTokenEnhancers(new ArrayList<>(tokenEnhancers));
        endpoints
            .authenticationManager(authenticationManager)
            .tokenStore(tokenStore())
            .tokenEnhancer(tokenEnhancerChain)
            .reuseRefreshTokens(false);             //don't reuse or we will run into session inactivity timeouts
    }

    @Autowired
    @Qualifier("authenticationManagerBean")
    private AuthenticationManager authenticationManager;

    /**
     * Apply the token converter (and enhancer) for token store.
     * @return the JwtTokenStore managing the tokens.
     */
    @Bean
    public JwtTokenStore tokenStore() {
        return new JwtTokenStore(jwtAccessTokenConverter());
    }

    /**
     * This bean generates an token enhancer, which manages the exchange between JWT acces tokens and Authentication
     * in both directions.
     *
     * @return an access token converter configured with the authorization server's public/private keys
     */
    @Bean
    public JwtAccessTokenConverter jwtAccessTokenConverter() {
        JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
        KeyPair keyPair = new KeyStoreKeyFactory(
             new ClassPathResource(uaaProperties.getKeyStore().getName()), uaaProperties.getKeyStore().getPassword().toCharArray())
             .getKeyPair(uaaProperties.getKeyStore().getAlias());
        converter.setKeyPair(keyPair);
        return converter;
    }

    @Override
    public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
        oauthServer.tokenKeyAccess("permitAll()").checkTokenAccess(
                "isAuthenticated()");
    }
}
尝试登录时,UAA控制台会出现以下错误:


2019-06-07 16:04:59.727调试32186---[XNIO-2任务-7]c.t.uaa.aop.LoggingAspect:输入:com.testando.uaa.repository.CustomAuditEventRepository.add(),参数[s]=[AuditEvent[时间戳=2019-06-07T19:04:59.727Z,主体=admin,类型=授权\失败,数据={details=remoteAddress=172.17.1.155,tokenType=BearertokenValue=,type=org.springframework.security.access.AccessDeniedException,message=访问被拒绝}]]

在资源服务器配置中,您可以将Spring Security基于表达式的访问控制与
#oauth2.clientHasRole一起使用,请参阅:

检查OAuth2客户端(不是用户)是否指定了角色。要检查用户角色,请参阅#hasRole(String)

另见:

配置OAuth感知的表达式处理程序

您可能希望利用Spring Security基于表达式的访问控制。默认情况下,将在
@enableSourceServer
设置中注册表达式处理程序。表达式包括#oauth2.clientHasRole、#oauth2.clientHasAnyRole和#oath2.denyClient,可用于提供基于oaut角色的访问h客户端(有关全面列表,请参见
OAuth2SecurityExpressionMethods


@user2831852:您添加了“.antMatchers(“/api/**”).access(“#oauth2.clientHasRole('ROLE_TESTE')”),因此只有具有角色
ROLE_TESTE
的客户端才能访问
/api/**
。您想要这个吗?@user2831852我问,因为在您的问题中您写了:““ROLE_TESTE”为了不访问api地址,您做了相反的操作。@user2831852我不知道JHipster。什么是网关配置?哪是您的资源配置?您可以添加完整的类,这样我就可以看到继承了吗?很抱歉造成混淆!在这种情况下,当尝试登录系统时,OAuth无法应用规则,即失败通过允许或拒绝访问角色_TESTE。我将在问题中添加类,以便您可以查看。谢谢。我通过添加完整的类和错误更改了问题中的代码,我没有资源代码,因为测试登录失败,我无法测试对资源的访问。代码来自网关和UAA。我如果您想测试()的话,还添加了GitHub中的代码,如果您想查看这个代码,那么这里有关于我在测试中使用的结构的信息。