Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Boot Security OAuth2 with Form Login

I am following Part V of Getting Started with Spring Boot Security to secure my RESTful microservices.

The simple flow that I intend to implement is:-

  1. If unauthenticated, the user is redirected to a custom login page at say '/login'.

  2. User provides his credentials.

  3. On successful authentication user is redirected to home page ('/home'). I should be able to access my REST endpoint (behind a Zuul Proxy Server) after providing the access token in the request.

The Getting Started guide in the above mentioned link uses Basic Auth and dummy user configured in .properties or .yml file.

This is how I tried with my configuration:-

@Configuration
@EnableAuthorizationServer
public class OAuth2Config extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.authenticationManager(authenticationManager);
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory().withClient("acme").secret("acmesecret")
                .authorizedGrantTypes("authorization_code", "refresh_token", "password").scopes("openid")
                .accessTokenValiditySeconds(3600);
    }

    @Override
    public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
        oauthServer.tokenKeyAccess("isAnonymous()").checkTokenAccess("isAnonymous()")
                .allowFormAuthenticationForClients();
    }

}



@Configuration
@Import({ OptoSoftSecurityServiceConfig.class })
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService userDetailsService; // backed by MongoDB

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

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.httpBasic().disable().formLogin();// disabled basic auth and configured to use dafault Spring Security form login.
    }
}

Hitting the authorization endpoint redirects me to 'http://localhost:9999/uaa/login' with error message as:-

<oauth>
<error_description>
Full authentication is required to access this resource
</error_description>
<error>unauthorized</error>
</oauth>

PROBLEM

  1. How can I configure Authorization Server to use UserDetailsService instead of static user and use Form Login instead of Basic Auth.

  2. How can I configure Auto Approval while using 'authorization_code' as the grant type?

  3. Is it mandatory for /oauth/authorize endpoint to be protected by Basic Auth? Why 'Full authentication is required' to access the /oauth/authorize' endpoint. I believe we do not know who is the user before this endpoint. The user can only be identified once he has been authenticated using valid credentials which comes after form login.

like image 933
Kumar Sambhav Avatar asked Jul 18 '15 18:07

Kumar Sambhav


People also ask

Does Spring Security use default login form?

In this configuration Spring Security will render a default log in page. Most production applications will require a custom log in form. The configuration below demonstrates how to provide a custom log in form. public SecurityFilterChain filterChain(HttpSecurity http) { http .

What is form login in Spring Security?

Form-based login is one form of Username/password authentication that Spring Security provides support for. This is provided through an Html form. Whenever a user requests a protected resource, Spring Security checks for the authentication of the request.

Does Spring Security using OAuth2?

Spring Security provides comprehensive OAuth 2 support.


1 Answers

Finally got it working. The git repo in the mentioned blog already had this thing configured. Turns out it was pretty straight forward.

This is what worked for me (I have also configured auto approval to true):-

**
 * @author kumar
 *
 */
@SpringBootApplication
public class AuthenticationServerApplication {

    /**
     * @param args
     */
    public static void main(String[] args) {
        SpringApplication.run(AuthenticationServerApplication.class, args);

    }

    @Configuration
    protected static class LoginConfig extends WebSecurityConfigurerAdapter {

        @Autowired
        private AuthenticationManager authenticationManager;

        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.formLogin().permitAll().and().authorizeRequests().anyRequest().authenticated();//.and().userDetailsService(yourCustomerUserDetailsService);
        }

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

    @Configuration
    @EnableAuthorizationServer
    protected static class OAuth2Config extends AuthorizationServerConfigurerAdapter {

        @Autowired
        private AuthenticationManager authenticationManager;

        @Override
        public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
            endpoints.authenticationManager(authenticationManager);
        }

        @Override
        public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
            clients.inMemory().withClient("acme").secret("acmesecret")
                    .authorizedGrantTypes("authorization_code", "refresh_token", "password").scopes("openid")
                    .autoApprove(true);
        }

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

    }

}

application.yml:-

  security:
      user:
        password: password
    server:
      port: 9999
      context-path: /uaa
like image 96
Kumar Sambhav Avatar answered Sep 26 '22 00:09

Kumar Sambhav