java - Spring 启动1.5.10 : implementing implicit grant

标签 java spring spring-boot oauth-2.0 spring-security-oauth2

我正在尝试使用 Spring Boot 实现 Oauth2,配置如下

安全配置:

@Configuration
@EnableWebSecurity(debug = true)
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(authenticationProvider());
        auth.userDetailsService(userDetailsService);
    }

    public AuthenticationProvider authenticationProvider(){
        DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider();
        daoAuthenticationProvider.setUserDetailsService(userDetailsService);
        daoAuthenticationProvider.setPasswordEncoder(passwordEncoder);
        return daoAuthenticationProvider;
    }

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

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable().anonymous().disable().authorizeRequests()
                .antMatchers("/oauth2/login","/logout").permitAll()
                .anyRequest().authenticated()
                .and().formLogin().loginPage("/oauth2/login").loginProcessingUrl("/login").permitAll();
    }
}

授权配置

@Configuration
@EnableAuthorizationServer
public class AuthServerConfiguration extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private TokenStore tokenStore;

    @Autowired
    private ClientDetailsService clientDetailsService;

    @Bean
    public TokenStore tokenStore(DataSource dataSource){
        return new JdbcTokenStore(dataSource);
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        TokenEnhancerChain enhancerChain = new TokenEnhancerChain();
        enhancerChain.setTokenEnhancers(Arrays.asList(tokenEnhancer()));
        endpoints.authenticationManager(authenticationManager)
                .tokenStore(tokenStore)
                .tokenEnhancer(enhancerChain)
                .tokenGranter(new CompositeTokenGranter(getCustomizedTokenGranters()))
                .tokenServices(tokenServices())
                .approvalStoreDisabled();

    }

    @Bean
    @Primary
    public AuthorizationServerTokenServices tokenServices() {
        DefaultTokenServices tokenServices = new DefaultTokenServices();
        tokenServices.setSupportRefreshToken(true);
        tokenServices.setTokenEnhancer(tokenEnhancer());
        tokenServices.setTokenStore(tokenStore);
        tokenServices.setClientDetailsService(clientDetailsService);
        return tokenServices;
    }

    @Bean
    public TokenEnhancer tokenEnhancer(){
        return (accessToken, authentication) -> {
            if(!"client_credentials".equalsIgnoreCase(authentication.getOAuth2Request().getRequestParameters().get(OAuth2Utils.GRANT_TYPE)))
            {
                ExtendedUser principal = (ExtendedUser) authentication.getPrincipal();
                Map<String, Object> additionalInfo = Maps.newHashMap();
                additionalInfo.put("user_id", principal.getUserId());
                ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo);
            }

            return accessToken;
        };
    }

    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        security.checkTokenAccess("permitAll()")
        .tokenKeyAccess("permitAll()");
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.withClientDetails(clientDetailsService);
    }

    @Bean
    public ClientDetailsService clientDetailsService(DataSource dataSource){
        return new CachedClientDetailsService(dataSource);
    }

    private List<TokenGranter> getCustomizedTokenGranters() {
        AuthorizationServerTokenServices tokenServices = tokenServices();
        ClientDetailsService clientDetails = clientDetailsService;
        OAuth2RequestFactory requestFactory = new DefaultOAuth2RequestFactory(clientDetails);

        RefreshTokenGranter refreshTokenGranter = new RefreshTokenGranter(tokenServices, clientDetails, requestFactory);
        ImplicitTokenGranter implicit = new ImplicitTokenGranter(tokenServices, clientDetails, requestFactory);
        ClientCredentialsTokenGranter clientCredentialsTokenGranter = new ClientCredentialsTokenGranter(tokenServices, clientDetails, requestFactory);
        clientCredentialsTokenGranter.setAllowRefresh(true);//custom config, see AuthorizationServerEndpointsConfigurer.getDefaultTokenGranters

        List<TokenGranter> tokenGranters = Lists.newArrayList();
        tokenGranters.add(refreshTokenGranter);
        tokenGranters.add(implicit);
        tokenGranters.add(clientCredentialsTokenGranter);
        if (authenticationManager != null) {
            tokenGranters.add(new ResourceOwnerPasswordTokenGranter(authenticationManager, tokenServices, clientDetails, requestFactory));
        }
        return tokenGranters;
    }
}

资源服务器配置:

@Configuration
@EnableResourceServer
public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {


    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/api/**").authenticated();
    }

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        resources.resourceId("identity-service");
    }

    @Bean
    public ResourceServerTokenServices resourceServerTokenServices(TokenStore tokenStore){
        DefaultTokenServices tokenServices = new DefaultTokenServices();
        tokenServices.setSupportRefreshToken(true);
        tokenServices.setTokenStore(tokenStore);
        return tokenServices;
    }
}

应用程序属性

security.oauth2.resource.filter-order = 3

资源服务器位于同一授权服务器(同一应用程序)上,我正在尝试实现隐式授予(密码授予工作正常)

当我尝试登录以完成隐式授予(oauth/authorize 端点需要身份验证)时,我收到/login 404 ?

Spring 启动:10.5.10, Spring 安全 Oauth2:2.0.14

最佳答案

我终于成功了

安全配置:

protected void configure(HttpSecurity http) throws Exception {
    http.requestMatchers().antMatchers("/**").and().csrf().disable().authorizeRequests()
            .antMatchers("/oauth2/login","/logout").permitAll()
            .antMatchers("/oauth/authorize").authenticated()
            .and().formLogin().loginPage("/oauth2/login").loginProcessingUrl("/login").permitAll();
}

资源服务器配置

public void configure(HttpSecurity http) throws Exception {
    http.requestMatchers().antMatchers("/api/**").and().anonymous().disable().authorizeRequests()
           .anyRequest().authenticated();
}

我必须在 Spring Security 中启用匿名并为 Spring Security 和资源服务器指定映射 URI 匹配器

/api/** 上的资源服务器 ,Spring 安全性/**

以及处理排序(1.5.10 版本)

应用程序属性

security.oauth2.resource.filter-order = 3

关于java - Spring 启动1.5.10 : implementing implicit grant,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49197716/

相关文章:

spring-boot - Spring Boot排除了在Maven构建期间连接到数据库的问题

spring - 如何使用 Spring Data JPA 启用基本缓存

Spring Boot Webflux/Netty - 检测关闭的连接

java - 如何通过 Springboot 服务的 2 个实例从共享位置并行访问文件?

java - Spring batch writer节流

java - 使用 Spring RestTemplate 进行 POST 时获取 400 BAD 请求

java - 如何拆分字符串并查看它是否是字符串中的最后一个条目?

java - Zxing扫描停止

java - JPA中@javax.persistence.Lob注解有什么意义?

Java 格式化输出