Spring boot 1.5.10:实施隐式授权

Spring boot 1.5.10 : implementing implicit grant

我正在尝试通过 spring 引导实现 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

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

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

spring 开机:1.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 安全中启用匿名并为 spring 安全和资源服务器

指定映射 URI 匹配器

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

安全

并负责排序(在版本 1.5.10 上)

application.properties

security.oauth2.resource.filter-order = 3