Spring boot 1.5.10:实现隐式授权

时间:2018-03-09 16:06:47

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

我正在尝试使用弹簧启动实现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;
    }
}

application.properties

security.oauth2.resource.filter-order = 3

资源服务器位于同一个授权服务器(Same Application)上,我正在尝试实现隐式授权(密码授权工作正常)

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

春季靴子:1.5.10, 春季安全Oauth2:2.0.14

1 个答案:

答案 0 :(得分:0)

最后,我设法让它发挥作用

安全配置:

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中启用anonymous,并为spring security和resource server指定映射URI匹配器

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

并负责订购(版本1.5.10)

application.properties

security.oauth2.resource.filter-order = 3