0
votes

Is it possible to implement OAuth implicit flow with spring security? I want to create both auth and resource server in the same application. I need standard auth endpoints for authentication and authorization and some custom endpoints for handling with users (create/update/list...).

Requirements:

  • implicit flow
  • custom login page (/my_login_page)
  • silent mode for obtaining token (/oauth/authorize?...&prompt=none)
  • secured custom endpoints with OAuth (/users)

I'm stuck with configuration. Whatever I do, the requirements above never work together.

Spring WebSecurityConfig

@Configuration
@Order(-10)
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    private MyAuthenticationProvider authenticationProvider;
    private MyAuthenticationDetailsSource authenticationDetailsSource;

    @Autowired
    public SecurityConfig(MyAuthenticationProvider authenticationProvider, MyAuthenticationDetailsSource authenticationDetailsSource) {
        this.authenticationProvider = authenticationProvider;
        this.authenticationDetailsSource = authenticationDetailsSource;
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

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

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http

            .sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.NEVER)
            .sessionFixation().newSession()
            .and()

            .authorizeRequests()
            .antMatchers("/assets/**", "/swagger-ui.html", "/webjars/**", "/swagger-resources/**", "/v2/**").permitAll()
            .anyRequest().authenticated()
            .and()

            .formLogin()
            .loginPage("/my_login_page")
            .loginProcessingUrl("/my_process_login")
            .usernameParameter("my_username")
            .passwordParameter("pmy_assword")
            .authenticationDetailsSource(authenticationDetailsSource)
            .permitAll();
    }
}

Spring AuthorizationServerConfig

@Configuration
@EnableAuthorizationServer
public class OAuth2AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    private ResourceLoader resourceLoader;
    private AuthProps authProps;

    @Autowired
    public OAuth2AuthorizationServerConfig(ResourceLoader resourceLoader, AuthProps authProps) {
        this.resourceLoader = resourceLoader;
        this.authProps = authProps;
    }

    @Bean
    public TokenStore tokenStore() {
        return new JwtTokenStore(accessTokenConverter());
    }

    @Bean
    @Qualifier("jwtAccessTokenConverter")
    public JwtAccessTokenConverter accessTokenConverter() {
        KeyStoreKeyFactory keyStoreKeyFactory = new KeyStoreKeyFactory(resourceLoader.getResource(authProps.getAuthServerPrivateCertPath()), authProps.getAuthServerPrivateCertKey().toCharArray());
        JwtAccessTokenConverter converter = new MYJwtAccessTokenConverter();   
        converter.setKeyPair(keyStoreKeyFactory
            .getKeyPair(authProps.getAuthServerPrivateCertAlias()));

        final Resource resource = resourceLoader.getResource(authProps.getAuthServerPublicCertPath());
        String publicKey;
        try {
            publicKey = IOUtils.toString(resource.getInputStream());
        } catch (final IOException e) {
            throw new RuntimeException(e);
        }
        converter.setVerifierKey(publicKey);

        return converter;
    }

    @Bean
    @Primary
    public DefaultTokenServices tokenServices() {
        DefaultTokenServices defaultTokenServices = new DefaultTokenServices();
        defaultTokenServices.setTokenStore(tokenStore());
        return defaultTokenServices;
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
        endpoints
            .tokenStore(tokenStore())
            .accessTokenConverter(accessTokenConverter());
    }

    @Override
    public void configure(AuthorizationServerSecurityConfigurer oauthServer) {
       oauthServer
            .tokenKeyAccess("permitAll()")
            .checkTokenAccess("isAuthenticated()");
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
            .withClient("my-secured-client")
            .secret("foo")
            .authorizedGrantTypes("implicit")
            .scopes("read", "write")
            .resourceIds("my-resource")
            .authorities("CLIENT")
            .redirectUris(
                    "http://localhost:4200"
            )
            .accessTokenValiditySeconds(300)
            .autoApprove(true);
    }
}

Spring ResourceServerConfig

@Configuration
@EnableResourceServer
public class OAuth2ResourceServerConfig extends ResourceServerConfigurerAdapter {

    private AuthProps authProps;
    private TokenStore tokenStore;
    private DefaultTokenServices tokenServices;

    @Autowired
    public OAuth2ResourceServerConfig(AuthProps authProps, TokenStore tokenStore, DefaultTokenServices tokenServices) {
        this.authProps = authProps;
        this.tokenStore = tokenStore;
        this.tokenServices = tokenServices;
    }

    @Override
    public void configure(final ResourceServerSecurityConfigurer config) {
        config
            .resourceId("my-resource")
                .tokenStore(tokenStore)
                .tokenServices(tokenServices);
    }

    @Override
    public void configure(final HttpSecurity http) throws Exception {
        http
            .sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .and()
            .authorizeRequests()
            .antMatchers(HttpMethod.OPTIONS).permitAll()
            .antMatchers("/**").authenticated()
            .and()
            .csrf().disable();
    }
}

I placed WebSecurityConfig before ResourceServerConfig otherwise login page doesn't work. But now I can't access my custom endpoint for users (I'm redirected to the login page). If I place ResourceServerConfig before WebSecurityConfig login page stop working. I get 404 not found response when I submit login page form.

I also have an issue with silent mode to obtain a new access token. When calling /oauth/authorize with still valid access_token I'm redirected to the login page.

2

2 Answers

1
votes

Finally I found a solution:

  1. ResourceServerConfig have to be before WebSecurityConfig
  2. loginProcessingUrl should be /oauth/authorize
  3. Silent refresh works by default until session is valid (login form)
  4. Custom endpoint for logout where invalidate current session

EDITED:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    private MyAuthenticationProvider authenticationProvider;
    private MyAuthenticationDetailsSource authenticationDetailsSource;

    @Autowired
    public SecurityConfig(MyAuthenticationProvider authenticationProvider, MyAuthenticationDetailsSource authenticationDetailsSource) {
        this.authenticationProvider = authenticationProvider;
        this.authenticationDetailsSource = authenticationDetailsSource;
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

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

    @Override
    public void configure(WebSecurity web) {
        web
                .debug(true)
                .ignoring()
                .antMatchers(HttpMethod.OPTIONS)
                .antMatchers("/my-custom-login-page", "/my-custom-logout-page")
                .antMatchers("/assets/**", "/swagger-ui.html", "/webjars/**", "/swagger-resources/**", "/v2/**");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
                .and()

                .authorizeRequests()
                .anyRequest().authenticated()
                .and()

                .formLogin()
                .loginPage("/my-custom-login-page")
                .loginProcessingUrl("/oauth/authorize")
                .usernameParameter("myUsernameParam")
                .passwordParameter("myPasswordParam")
                .authenticationDetailsSource(authenticationDetailsSource)
                .permitAll()
                .and()

                .csrf().disable();
    }
}

@Configuration
@EnableAuthorizationServer
public class OAuth2AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    private ResourceLoader resourceLoader;
    private AuthProps authProps;

    @Autowired
    public OAuth2AuthorizationServerConfig(ResourceLoader resourceLoader, AuthProps authProps) {
        this.resourceLoader = resourceLoader;
        this.authProps = authProps;
    }

    @Bean
    public TokenStore tokenStore() {
        return new JwtTokenStore(accessTokenConverter());
    }

    @Bean
    @Qualifier("jwtAccessTokenConverter")
    public JwtAccessTokenConverter accessTokenConverter() {
        KeyStoreKeyFactory keyStoreKeyFactory = new KeyStoreKeyFactory(resourceLoader.getResource(authProps.getAuthServerPrivateCertPath()), authProps.getAuthServerPrivateCertKey().toCharArray());
        JwtAccessTokenConverter converter = new MyJwtAccessTokenConverter();
        converter.setKeyPair(keyStoreKeyFactory.getKeyPair(authProps.getAuthServerPrivateCertAlias()));

        final Resource resource = resourceLoader.getResource(authProps.getAuthServerPublicCertPath());
        String publicKey;
        try {
            publicKey = IOUtils.toString(resource.getInputStream());
        } catch (final IOException e) {
            throw new RuntimeException(e);
        }
        converter.setVerifierKey(publicKey);

        return converter;
    }

    @Bean
    @Primary
    public DefaultTokenServices tokenServices() {
        DefaultTokenServices defaultTokenServices = new DefaultTokenServices();
        defaultTokenServices.setTokenStore(tokenStore());
        return defaultTokenServices;
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
        endpoints
                .tokenStore(tokenStore())
                .accessTokenConverter(accessTokenConverter());
    }

    @Override
    public void configure(AuthorizationServerSecurityConfigurer oauthServer) {
        oauthServer
                .tokenKeyAccess("permitAll()")
                .checkTokenAccess("isAuthenticated()");
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
                .withClient(authProps.getAuthServerClientId())
                .secret(authProps.getAuthServerClientSecret())
                .authorizedGrantTypes("implicit")
                .scopes("read", "write")
                .resourceIds(authProps.getAuthServerResourceId())
                .authorities("CLIENT")
                .redirectUris(
                        "http://localhost:4200/#/login",
                        "http://localhost:4200/assets/silent-refresh.html",
                        "http://localhost:8080/my-api/webjars/springfox-swagger-ui/oauth2-redirect.html"
                )
                .accessTokenValiditySeconds(authProps.getAuthServerAccessTokenValiditySeconds())
                .autoApprove(true);
    }
}

@Configuration
@EnableResourceServer
public class OAuth2ResourceServerConfig extends ResourceServerConfigurerAdapter {

    private AuthProps authProps;
    private TokenStore tokenStore;
    private DefaultTokenServices tokenServices;

    @Autowired
    public OAuth2ResourceServerConfig(AuthProps authProps, TokenStore tokenStore, DefaultTokenServices tokenServices) {
        this.authProps = authProps;
        this.tokenStore = tokenStore;
        this.tokenServices = tokenServices;
    }

    @Override
    public void configure(final ResourceServerSecurityConfigurer config) {
        config.resourceId(authProps.getAuthServerResourceId()).tokenStore(tokenStore);
        config.resourceId(authProps.getAuthServerResourceId()).tokenServices(tokenServices);
    }

    @Override
    public void configure(final HttpSecurity http) throws Exception {
        http
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()

                .authorizeRequests()
                .anyRequest().hasRole(AppRole.ROLE_APP_USER.split("ROLE_")[1])
                .and()

                .csrf().disable();
    }
}

@Controller
public class MainController {

    @Autowired
    public MainController() {
        ...
    }

    @GetMapping("/my-custom-login-page")
    public ModelAndView loginPage(HttpServletRequest request, HttpServletResponse response) {
        ModelAndView mv = new ModelAndView("login-page");
        return mv;
    }

    @GetMapping("/my-custom-logout-page")
    public ModelAndView logoutPage(HttpServletRequest request) {
        ModelAndView mv = new ModelAndView("logout-page");

        HttpSession session = request.getSession(false);
        if (Objects.isNull(session)) {
            mv.addObject("msg", "NO SESSION");
            return mv;
        }
        session.invalidate();
        mv.addObject("msg", "SUCCEEDED");
        return mv;
    }
}

0
votes

In addition to @user3714967 answer, I add some tips maybe It helps someone. The problem is that we are defining multiple HttpSecurity (The resourceServer is a WebSecurityConfigurerAdapter with order 3). The solution is to use HttpSecurity.requestMatchers() with the specific value.

Example

First Class:

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.requestMatchers().antMatchers("url1", "url2", ...).and()
            .authorizeRequests()
                .antMatchers(...).and()...
    }
}

Second Class:

@Configuration
@EnableResourceServer
public class OAuth2ResourceServerConfig extends ResourceServerConfigurerAdapter {
   @Override
    public void configure(HttpSecurity http) throws Exception {
         @Override
         protected void configure(HttpSecurity http) throws Exception {
             http
               .requestMatchers().antMatchers("url3", "url4", ...)
                .and()
                 .authorizeRequests()
                    .antMatchers(...).and()...
    }
   }
 }

This will be useful when we have more than flow (password && implicit flows for my case).