Какой из них является правильным потоком OAuth2 - PullRequest
0 голосов
/ 24 апреля 2020

Пытался реализовать OAuth2 весной. Но застрял в том, какой из них будет правильным потоком?

Один поток, который я держу @Order(1) in (WebSecurityConfigurerAdapter)

Здесь при нажатии на нижеприведенную страницу мне предоставляется страница входа по умолчанию, и я успешно захожу. http://localhost:8301/oauth/authorize?client_id=getidfromfacebook&response_type=code&redirect_uri=http://localhost:9191/xyz Перенаправляется на страницу авторизации и после принятия получает код http://localhost:9191/xyz?code=mkuyG4, который помогает в получении доступа и обновлении токена sh по curl http://localhost:8301/oauth/token -H"Content-type: application/x-www-form-urlencoded" -d'grant_type=authorization_code&redirect_uri=http://localhost:9191/xyz&code=LJQef7' -u getidfromfacebook:getit Я также могу получить токен доступа fre sh из данного обновления sh токен через curl --location --request POST 'http://localhost:8301/oauth/token?grant_type=refresh_token&client_id=getidfromfacebook&refresh_token=a045acd6-5d66-4db5-a509-4bdadca065e0' -u getidfromfacebook:getit

Проблема, с которой я здесь сталкиваюсь, заключается в том, что с данным токеном доступа я не могу получить доступ ни к одному из ресурсов, упомянутых в antMatchers("/api/**").authenticated() (ResourceServerConfigurerAdapter). Как и в почтальоне, заголовок снабжен Authorization и значением Bearer access-token или curl -H"Authorization: Bearer 1738520f-9f9c-43ef-8f7f-f5886075a7aa" http://localhost:8301/api/users/all/. Заметьте, я могу получить токены доступа и для других grant_types, а также обновить sh. Но нет доступа к ресурсам через токен. Обратите внимание: если я нажму на URL ресурса, у меня будет логин по умолчанию и я могу получить к нему доступ.

Другой поток I удалить @Order(1). Когда я пытаюсь go через поток кода авторизации, система жалуется на необходимость входа пользователя для запроса (аутентификационного) кода. Так что не могу продолжить, поскольку я не представлен на странице входа по умолчанию. Однако я могу продолжить с типом предоставления пароля curl http://localhost:8301/oauth/token -d"grant_type=password&username=username&password=userpassword" -H"Content-type:application/x-www-form-urlencoded; charset=utf-8" -u getidfromfacebook:getit Я также могу получить доступ к ресурсам через токен доступа.

Какой из них является правильным подходом? Почему я не могу получить доступ к ресурсам в прежнем подходе.

@Configuration
@EnableAuthorizationServer
@AllArgsConstructor                            
public class AuthorizationServerConfigAdapter extends AuthorizationServerConfigurerAdapter {

private final AuthenticationManager authenticationManager;
private final ClientService clientService;
private final UserService userService;

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

@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
    clients.withClientDetails(clientService);
}

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

/*****************************/

@Configuration
@EnableResourceServer
public class ResourceServerConfigAdapter extends ResourceServerConfigurerAdapter {
    @Override
    public void configure(HttpSecurity http) throws Exception {
         http
            .authorizeRequests()
            .antMatchers("/api/**").authenticated()
            .antMatchers("/").permitAll();
    }
}

/*****************************/

@Configuration
@EnableWebSecurity
@AllArgsConstructor
@Order(1) // Since we have this working as N, Z and R sever.
public class WebSecurityConfigAdapter extends WebSecurityConfigurerAdapter {

private final UserService userService;

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

    //http.csrf().disable();

    http
            .antMatcher("/**")
            .authorizeRequests()
            .antMatchers("/oauth/authorize**", "/login**", "/error**")
            .permitAll()
            .and()
            .authorizeRequests()
            .anyRequest().authenticated()
            .and()
            .formLogin().permitAll();
}

@Override
protected void configure(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {
    authenticationManagerBuilder
            .userDetailsService(userService)
            .passwordEncoder(passwordEncoder());
}

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

@Bean
public PasswordEncoder passwordEncoder() {
    return new BCryptPasswordEncoder(BCryptPasswordEncoder.BCryptVersion.$2A);
}

}

1 Ответ

0 голосов
/ 24 апреля 2020
@Override
    public void configure(HttpSecurity http) throws Exception {
        http
            .requestMatcher(request -> {
                String auth = request.getHeader("Authorization");
                return (auth != null && auth.startsWith("Bearer"));
            })
            .authorizeRequests()
            .antMatchers("/api/**").authenticated()
            .antMatchers("/").permitAll();
    }
...