В файле HttpSecurity отсутствует метод oauth2Login () - PullRequest
1 голос
/ 04 апреля 2019

Я делаю Spring Security Oauth2. На стороне клиента я переопределяю configure(HttpSecurity http) метод и хотите использовать oauth2Login() метод в файле HttpSecurity. Но у HttpSecurity такого нет функция. Я уже добавляю зависимость spring-security-oauth2-client, spring-boot-starter-security and spring-security-oauth2 в pom.xml. В HttpSecurity файле написано «Copyright 2002-2016 оригинал Автор или авторы ". Как я могу обновить это?

    @EnableWebSecurity
     public class OauthConfig extends WebSecurityConfigurerAdapter{


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

        http
                .authorizeRequests()
                .antMatchers("/", "/login**")
                .permitAll()
                .anyRequest()
                .authenticated();
    }
}

Ответы [ 2 ]

0 голосов
/ 20 июля 2019

Пожалуйста, убедитесь, что ваша версия spring-boot-starter-parent верна.
Ниже приведен пример:
pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

<groupId>com.example</groupId>
<artifactId>your-artifactId</artifactId>
<version>your-version</version>
<packaging>jar</packaging>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.6.RELEASE</version>
    <relativePath/>
</parent>

<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.security</groupId>
        <artifactId>spring-security-oauth2-client</artifactId>
    </dependency>

    <!--if you need to generate token-->
    <dependency>
        <groupId>io.jsonwebtoken</groupId>
        <artifactId>jjwt</artifactId>
        <version>0.5.1</version>
    </dependency>
</dependencies>



<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

<repositories>
    <repository>
        <id>spring-milestones</id>
        <name>Spring Milestones</name>
        <url>https://repo.spring.io/milestone</url>
        <snapshots>
            <enabled>false</enabled>
        </snapshots>
    </repository>
</repositories>


</project>

Как настроить класс WebSecurityConfigurerAdapter:

1. с по умолчанию реализации:

@Configuration
public class SimpleTestSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .anyRequest().authenticated()
                .and()
                .oauth2Login();
    }
}
  1. с настроенной реализацией для loginPage, authorizationEndpoint, TokenEndpoint, redirectionEndpoint, userInfoEndpoint:
    @Configuration
    public class SimpleTestSecurityConfig extends WebSecurityConfigurerAdapter {

        private String[] PERMIT_ALL = {"unsecured-endpoint1", "unsecured-endpoint2", "..."};

        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.authorizeRequests()
                    .antMatchers(PERMIT_ALL).permitAll()
                    .anyRequest().authenticated()
                    .and()
                    .oauth2Login()
                    .loginPage("/login")
                    .defaultSuccessUrl("/home")
                    .failureUrl("/error")

                    .authorizationEndpoint()
                    .baseUri("/oauth2/authorize-client") //default is "/oauth2/authorization"
                    .and()

                    .tokenEndpoint()
                    .accessTokenResponseClient(accessTokenResponseClient())
                    .and()

                    //.redirectionEndpoint()
                    //.baseUri("/oauth2/redirect") //base for google is "/login/oauth2/code"
                    //.and()

                    .userInfoEndpoint().oidcUserService(new OidcUserService(){
                        @Override
                        public OidcUser loadUser(OidcUserRequest userRequest) throws OAuth2AuthenticationException {
                            return super.loadUser(userRequest);
                        }
            });

        }

        @Bean
        public AuthorizationRequestRepository<OAuth2AuthorizationRequest> authorizationRequestRepository(){
            return new HttpSessionOAuth2AuthorizationRequestRepository();
        }


        @Bean
        public OAuth2AccessTokenResponseClient<OAuth2AuthorizationCodeGrantRequest> accessTokenResponseClient(){
            return new NimbusAuthorizationCodeTokenResponseClient();
        }

    }

  1. application.yml:
    spring:
        security:
            oauth2:
                client:
                    registration:
                        google:
                            client-id: your-client-id
                            client-secret: your-client-secret
                            redirectUriTemplate: "http://localhost:8080/login/oauth2/code/google"
                            scope:
                                - email
                                - profile
0 голосов
/ 04 апреля 2019

Поскольку вы используете весеннюю загрузку, вы можете использовать следующие зависимости для автоматической настройки безопасности пружины для oauth2:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.security.oauth.boot</groupId>
    <artifactId>spring-security-oauth2-autoconfigure</artifactId>
    <version>2.0.0.RELEASE</version>
</dependency>

После добавления вышеуказанной зависимости, если вы хотите что-то переопределить. Spring Boot 2.x класс автоконфигурации для поддержки клиента OAuth: OAuth2ClientAutoConfiguration .

. Он выполняет следующие задачи:

  • Регистрирует репозиторий ClientRegistrationRepository @ Bean , состоящий из ClientRegistration (ов) из настроенных свойств клиента OAuth.

  • Предоставляет WebSecurityConfigurerAdapter @ Configuration и включает OAuth 2.0. Вход через httpSecurity.oauth2Login ().

Если вам необходимо переопределить автоконфигурацию в зависимости от вашей конкретнойтребований, вы можете сделать это следующими способами:

  • Зарегистрировать репозиторий ClientRegistrationRepository @ Bean
  • Предоставить WebSecurityConfigurerAdapter
  • Полностью переопределить автоконфигурацию

Переопределив WebSecurityConfigurerAdapter следующим образом:

@EnableWebSecurity
public class OAuth2LoginSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .oauth2Login()
                .clientRegistrationRepository(this.clientRegistrationRepository())
                .authorizedClientService(this.authorizedClientService())
                .loginPage("/login")
                .authorizationEndpoint()
                    .baseUri(this.authorizationRequestBaseUri())
                    .authorizationRequestRepository(this.authorizationRequestRepository())
                    .and()
                .redirectionEndpoint()
                    .baseUri(this.authorizationResponseBaseUri())
                    .and()
                .tokenEndpoint()
                    .accessTokenResponseClient(this.accessTokenResponseClient())
                    .and()
                .userInfoEndpoint()
                    .userAuthoritiesMapper(this.userAuthoritiesMapper())
                    .userService(this.oauth2UserService())
                    .oidcUserService(this.oidcUserService())
                    .customUserType(GitHubOAuth2User.class, "github");
    }
}

Для справки см .:

https://docs.spring.io/spring-security/site/docs/5.0.7.RELEASE/reference/html/oauth2login-advanced.html

и

https://docs.spring.io/spring-security/site/docs/current/reference/html/jc.html

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...