Spring security - implement oauth2 sso

hamed :

I want to implement central authentication system with spring security and oauth2 sso. In other words, I have a spring boot application that is responsible for authorization and one simple client. My client has rest API. First I get token from the authorization server, then send a request to client API with an authorization header contains bearer token from above request. But this request always gets me server login page.

Here is the implementation of the server and the client:

Server

AuthorizationServerConfig.java

@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

@Autowired
private AuthenticationManager authenticationManager;


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



@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
    clients.inMemory()
            .withClient("SampleClientId")
            .secret("{noop}secret")
            .authorizedGrantTypes("password")
            .scopes("user_info")
            .autoApprove(true);
}

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

ApplicationConfig:

@SpringBootApplication
@EnableResourceServer
public class ApplicationConfig extends SpringBootServletInitializer {

public static void main(String[] args) {
    SpringApplication.run(ApplicationConfig.class, args);
}

}

SecurityConfig:

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {


@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    //this is just example
    auth.inMemoryAuthentication().withUser("user").password("{noop}1234").roles("user");
}

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.requestMatchers()
            .antMatchers("/login", "/oauth/authorize", "/oauth/token")
            .and()
            .authorizeRequests()
            .anyRequest().authenticated()
            .and()
            .formLogin().permitAll();

}

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

application.yml:

server:
  port: 8900
  servlet:
    context-path: /auth

Client:

ApplicationConfig:

@SpringBootApplication
public class ApplicationConfig {

public static void main(String[] args) {
    SpringApplication.run(ApplicationConfig.class, args);
}

}

SecurityConfig:

@Configuration
@EnableOAuth2Sso
public class ApplicationSecurityConfig extends WebSecurityConfigurerAdapter {

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.csrf().disable()
            .authorizeRequests()
            .antMatchers("/", "/login**")
            .permitAll()
            .anyRequest()
            .authenticated();
}
}

TestController:

@RestController
public class HomeController {

@GetMapping("/")
public String index() {
    return "home";
}

@RequestMapping("/admin")
public String admin() {
    return "admin";
}
}

application.yml:

server:
  port: 9000
  servlet:
    context-path: /client1
security:
  basic:
    enabled: false
  oauth2:
    client:
      clientId: SampleClientId
      clientSecret: secret
      accessTokenUri: http://localhost:8900/auth/oauth/token
      userAuthorizationUri: http://localhost:8900/auth/oauth/authorize
    resource:
      userInfoUri: http://localhost:8900/auth/user/me

First, I send client_id and secret code along side with username, password and grant_type to localhost:8900/auth/oauth/token and get a result like this:

{
  "access_token": "603b505f-e701-43d0-b8b8-976a2178f7ea",
  "token_type": "bearer",
  "expires_in": 43199,
  "scope": "user_info"
}

Now, I pickup above token and send a request to localhost:9000/client1/admin with header contains above token. But it seems the client application ignores the header and shows server login page as result. How can I fix this problem?

jzheaux :

@EnableOAuth2Sso is an annotation for using OAuth 2.0 as an end-user authentication mechanism (e.g. "A Login with Google" button). This annotation is wiring your app to redirect to a login page on your authorization server where you would log in and then get redirected back to your app.

If this is your intent, then you'll need to update your Authorization Server to support the authorization_code grant flow instead of the password grant flow.

However, if your client is strictly a REST API, then you are more likely to need to wire the client using @EnableResourceServer instead of @EnableOAuth2Sso. A Resource Server is what takes a token as authorization, via the Authorization HTTP header.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=133609&siteId=1