Spring boot security oauth2 authorization_code flow page login page не найдена

Привет, я пытаюсь реализовать OAuth2 с использованием безопасности Spring, пока мне удалось реализовать его с помощью grant_type=password, я получаю token, time, refresh token, и ресурсы защищены, как ожидалось.

Теперь мой следующий шаг - использовать реализацию authorization_code+pkce.

Я следил за этим руководство, когда я заменяю все учетные данные клиента данными моего сервера аутентификации, я получаю сообщение http://localhost:8080/oauth/loginNot Found. Запрос идет примерно так http://localhost:8080/auth/oauth/authorize?client_id=SampleClientId&redirect_uri=http://localhost:8083/ui2/login&response_type=code&state=5ppnu6

Мои файлы конфигурации и сервера следующие: это мой первый раз, когда я использую oauth на стороне сервера, поэтому я могу действовать бессмысленно, пожалуйста, помогите мне исправить это. AuthorizationServerConfig.java

@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private TokenStore tokenStore;

    @Autowired
    private AuthenticationManager manager;

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients
                .inMemory()
                .withClient("SampleClientId")
                .secret(passwordEncoder.encode("secret"))
                .authorizedGrantTypes("password", "authorization_code", "implicit", "refresh_token")
                .scopes(UserDetailsServiceImpl.Role.USER.name(),
                        UserDetailsServiceImpl.Role.MODERATOR.name(),
                        UserDetailsServiceImpl.Role.ADMIN.name())
                .redirectUris("http://localhost:8080/callback", "http://localhost:8083/ui2/login")
                .accessTokenValiditySeconds(3600)
                .refreshTokenValiditySeconds(4800);
    }


    @Override
    public void configure(final AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
        oauthServer.tokenKeyAccess("permitAll()")
                .checkTokenAccess("isAuthenticated()");
    }
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.tokenStore(tokenStore)
                .authenticationManager(manager);
    }


}

BeansConfig.java

@Configuration
public class BeansConfig {
    @Bean
    public TokenStore tokenStore() {
        return new InMemoryTokenStore();
    }

    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public UserDetailsServiceImpl userDetailsService() {
        return new UserDetailsServiceImpl();
    }

}

ResourceServerConfig.java

@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
    private static final String RESOURCE_ID = "resource_id";

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        resources.resourceId(RESOURCE_ID).stateless(false);
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http
                .anonymous().disable()
                .authorizeRequests()
                .antMatchers("/users/**").authenticated()
                .and().exceptionHandling().accessDeniedHandler(new OAuth2AccessDeniedHandler());
    }
}

SecurityConfig.java

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Resource(name = "userDetailsService")
    private UserDetailsServiceImpl userDetailsService;

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;


    public SecurityConfig() {
    }

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

    @Autowired
    public void globalUserDetails(AuthenticationManagerBuilder auth) throws Exception {
        auth
                .userDetailsService(userDetailsService)
                .passwordEncoder(passwordEncoder);
    }

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

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

UsersControllers.java

@RestController
public class UsersControllers {

    @RequestMapping(value = "/users", method = RequestMethod.GET)
    ResponseEntity<Map<String, String>> get() {
        final Map<String, String> map = new HashMap<>();
        map.put("status", "ok");
        return ResponseEntity.ok(map);
    }

    @GetMapping(value = "/user/me")
    Principal me(Principal principal) {
        final Map<String, String> map = new HashMap<>();
        map.put("status", "ok");
        return principal;
    }
}

UserDetailsImpl.java

public class UserDetailsImpl implements UserDetails {

    private final String username;
    private final String password;
    private final List<GrantedAuthority> roles;

    public UserDetailsImpl(String username, String password, List<GrantedAuthority> roles) {
        this.username = username;
        this.password = password;
        this.roles = roles;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return roles;
    }

    @Override
    public String getPassword() {
        return password;
    }

    @Override
    public String getUsername() {
        return this.username;
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }

}

UserDetailsServiceImpl.java

@Service("userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {

    private static final Logger LOGGER = Logger.getLogger(UserDetailsServiceImpl.class.getSimpleName());

    public enum Role {
        USER,
        MODERATOR,
        ADMIN
    }

    private final List<UserDetailsImpl> users = new ArrayList<>();


    public UserDetailsServiceImpl() {
    }

    public void init(BCryptPasswordEncoder passwordEncoder) {
        users.add(new UserDetailsImpl("john", passwordEncoder.encode("doe"), buildUserAuthorities()));
        users.add(new UserDetailsImpl("wow", passwordEncoder.encode("baby"), buildModeratorAuthorities()));
    }

    private List<GrantedAuthority> buildUserAuthorities() {
        final List<GrantedAuthority> authorityList = new ArrayList<>();
        authorityList.add(new SimpleGrantedAuthority(Role.USER.name()));
        return authorityList;
    }

    private List<GrantedAuthority> buildModeratorAuthorities() {
        final List<GrantedAuthority> authorityList = new ArrayList<>();
        authorityList.add(new SimpleGrantedAuthority(Role.MODERATOR.name()));
        return authorityList;
    }

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        for (UserDetailsImpl details : users) {
            if (details.getUsername().equals(s)) {
                LOGGER.warning("Found user: " + s);
                return details;
            }
        }
        throw new UsernameNotFoundException("User " + s + " notfound");
    }

    public List<UserDetailsImpl> getUsers() {
        return users;
    }
}

Некоторое содержимое из файла maven

<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.3.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.security.oauth</groupId>
            <artifactId>spring-security-oauth2</artifactId>
            <version>2.3.3.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.security.oauth.boot</groupId>
            <artifactId>spring-security-oauth2-autoconfigure</artifactId>
            <version>2.0.1.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>


    </dependencies>

Вы это решили? у меня та же проблема

Amir Choubani 13.06.2019 12:18

Я создал новое приложение, и, к счастью, оно сработало.

silentsudo 13.06.2019 15:53
Пользовательский скаляр GraphQL
Пользовательский скаляр GraphQL
Листовые узлы системы типов GraphQL называются скалярами. Достигнув скалярного типа, невозможно спуститься дальше по иерархии типов. Скалярный тип...
Поднятие тревоги для долго выполняющихся методов в Spring Boot
Поднятие тревоги для долго выполняющихся методов в Spring Boot
Приходилось ли вам сталкиваться с требованиями, в которых вас могли попросить поднять тревогу или выдать ошибку, когда метод Java занимает больше...
Версия Java на основе версии загрузки
Версия Java на основе версии загрузки
Если вы зайдете на официальный сайт Spring Boot , там представлен start.spring.io , который упрощает создание проектов Spring Boot, как показано ниже.
Документирование API с помощью Swagger на Springboot
Документирование API с помощью Swagger на Springboot
В предыдущей статье мы уже узнали, как создать Rest API с помощью Springboot и MySql .
0
2
483
0

Другие вопросы по теме