RestController не работает в oauth2 Spring Boot

Я установил сервер аутентификации и сервер ресурсов, как указано в статье ниже http://www.hascode.com/2016/03/setting-up-an-oauth2-authorization-server-and-resource-provider-with-spring-boot/

Я загрузил код, и он работает нормально. Теперь проблема в том, что в проекте поставщика ресурсов есть только один аннотированный класс RestController, как показано ниже.

package com.hascode.tutorial;

import java.util.UUID;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Scope;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
@RestController
@EnableResourceServer
public class SampleResourceApplication {
    public static void main(String[] args) {
        SpringApplication.run(SampleResourceApplication.class, args);
    }

    @RequestMapping("/")
    public String securedCall() {
        return "success (id: " + UUID.randomUUID().toString().toUpperCase() + ")";
    }
}

Теперь, когда я создаю другой класс, аннотированный с помощью @RestController, как показано ниже

@RestController
@RequestMapping("/public")
public class PersonController {

    @Autowired
    private PersonRepository personRepo;

    @RequestMapping(value = "/person", method = RequestMethod.GET)
    public ResponseEntity<Collection<Person>> getPeople() {
        return new ResponseEntity<>(personRepo.findAll(), HttpStatus.OK);
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public ResponseEntity<Person> getPerson(@PathVariable long id) {
        Person person = personRepo.findOne(id);

        if (person != null) {
            return new ResponseEntity<>(personRepo.findOne(id), HttpStatus.OK);
        } else {
            return new ResponseEntity<>(null, HttpStatus.NOT_FOUND);
        }
    }

    @RequestMapping(method = RequestMethod.POST)
    public ResponseEntity<?> addPerson(@RequestBody Person person) {
        return new ResponseEntity<>(personRepo.save(person), HttpStatus.CREATED);
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    public ResponseEntity<Void> deletePerson(@PathVariable long id, Principal principal) {
        Person currentPerson = personRepo.findByUsername(principal.getName());

        if (currentPerson.getId() == id) {
            personRepo.delete(id);
            return new ResponseEntity<Void>(HttpStatus.OK);
        } else {
            return new ResponseEntity<Void>(HttpStatus.UNAUTHORIZED);
        }
    }

    @RequestMapping(value = "/{id}/parties", method = RequestMethod.GET)
    public ResponseEntity<Collection<Party>> getPersonParties(@PathVariable long id) {
        Person person = personRepo.findOne(id);

        if (person != null) {
            return new ResponseEntity<>(person.getParties(), HttpStatus.OK);
        } else {
            return new ResponseEntity<>(null, HttpStatus.NOT_FOUND);
        }
    }

}

но когда я попытался получить доступ к службе (http://localhost:9001/resources/public/person) я получаю 404

{
    "timestamp": 1508752923085,
    "status": 404,
    "error": "Not Found",
    "message": "No message available",
    "path": "/resources/public/person"
}

когда я получаю доступ к http://localhost:9001/resources/, я получаю правильный результат, например

успех (id: 27DCEF5E-AF11-4355-88C5-150F804563D0)

Должен ли я регистрировать контроллер где-нибудь или мне не хватает какой-либо конфигурации

https://bitbucket.org/hascode/spring-oauth2-example

ОБНОВЛЕНИЕ 1

ResourceServerConfiguration.java

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;

@Configuration
@EnableResourceServer
public class ResourceServerConfiguration  extends ResourceServerConfigurerAdapter {

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http
        .anonymous().and()
        .authorizeRequests()
        .antMatchers("/resources/public/**").permitAll()
        .antMatchers("/resources/private/**").authenticated();
    }
}

OAuth2SecurityConfiguration.java

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
@EnableWebSecurity
public class OAuth2SecurityConfiguration extends WebSecurityConfigurerAdapter {
    @Override
    public void configure(HttpSecurity http) throws Exception {
        http
        .anonymous().and()
        .authorizeRequests()
        .antMatchers("/resources/public/**").permitAll()
        .antMatchers("/resources/private/**").authenticated();
    }
}

ОБНОВЛЕНИЕ 2

@Override
    public void configure(HttpSecurity http) throws Exception {
         http.authorizeRequests()
         .antMatchers("/resources/public/**").permitAll() //Allow register url
         .anyRequest().authenticated().and()
         .antMatcher("/resources/**").authorizeRequests() //Authenticate all urls with this body /api/home, /api/gallery
         .antMatchers("/resources/**").hasRole("ADMIN")
         .and().exceptionHandling().accessDeniedHandler(new OAuth2AccessDeniedHandler()); //This is optional if you want to handle exception
    }

person Alex Man    schedule 23.10.2017    source источник
comment
В вашем основном классе замените @EnableResourceServer на @EnableAutoConfiguration. позвольте мне узнать статус. Также убедитесь, что вы отправляете get запрос к серверу вместо post.   -  person Ataur Rahman Munna    schedule 23.10.2017
comment
@AtaurRahmanMunna теперь по крайней мере статус изменился с 404 на 401, но теперь я не могу аутентифицироваться ..... Я получаю 401 Full authentication is required to access this resource, хотя у меня есть правильный токен доступа. @EnableResourceServer предназначен для использования в качестве сервера ресурсов для прав oauth.   -  person Alex Man    schedule 23.10.2017
comment
Думаю, что в весенней комплектации что-то не так. Вы использовали здесь весеннюю безопасность? Если да, то поместите свою HttpSecurity конфигурацию в WebSecurityConfigurerAdapter и ResourceServerConfigurerAdapter   -  person Ataur Rahman Munna    schedule 23.10.2017
comment
Я использую spring-cloud-starter-security. это мой pom.xml bitbucket.org/hascode/spring-oauth2-example/src/   -  person Alex Man    schedule 23.10.2017
comment
Я вижу твою pom.xml. Здесь вы включаете spring-security. Ставьте свою весеннюю конфигурацию безопасности. Вы поняли мою точку зрения?   -  person Ataur Rahman Munna    schedule 23.10.2017
comment
@AtaurRahmanMunna Да ... Я добавил эту конфигурацию, вы можете проверить мое обновление 1. но я все равно получаю 401   -  person Alex Man    schedule 23.10.2017
comment
Я считаю, что ваш новый @RestController не подхвачен Spring boot. Проверьте, доступен ли контроллер для сканирования при загрузке Spring. Также, если вы поместите свой новый контроллер в тот же пакет, что и ваш @SpringBootApplication, он должен работать.   -  person Abdullah Khan    schedule 23.10.2017
comment
В вашем ResourceServerConfigurerAdapter используйте .antMatchers("/resources/public/**", "/resources/private/**").permitAll().and().exceptionHandling().accessDeniedHandler(new OAuth2AccessDeniedHandler()) и сообщите мне статус.   -  person Ataur Rahman Munna    schedule 23.10.2017
comment
@AbdullahKhan Да, когда я перехожу на тот же пакет, пружинные ботинки могут сканировать этот контроллер, но все равно получают 401   -  person Alex Man    schedule 23.10.2017
comment
@AtaurRahmanMunna Я добавил эти изменения, все те же .... получение 401   -  person Alex Man    schedule 23.10.2017
comment
@AbdullahKhan есть ли способ, которым мы можем явно упомянуть другой пакет, в котором другие контроллеры находятся в весенних ботинках   -  person Alex Man    schedule 23.10.2017
comment
@ComponentScan может вам помочь.   -  person Abdullah Khan    schedule 23.10.2017
comment
@AbdullahKhan Я поставил @ComponentScan в PersonController, все еще получаю 404   -  person Alex Man    schedule 23.10.2017
comment
@AbdullahKhan @ComponentScan работал ....   -  person Alex Man    schedule 23.10.2017
comment
@AbdullahKhan, как мы можем сделать api под /resources/public/ гостевым включенным (может получить доступ без аутентификации) и apis под /resources/private/ защищенным (не может получить доступ без аутентификации)   -  person Alex Man    schedule 23.10.2017
comment
Я отправляю ответ, пожалуйста, проверьте это.   -  person Abdullah Khan    schedule 23.10.2017


Ответы (2)


Сделайте свой новый контроллер PersonController обнаруживаемым с помощью Spring Boot либо с помощью _ 2_ в классе конфигурации или путем перемещения PersonController в пакет в или под основной класс, помеченный @SpringBootApplication.

Во-вторых, исправьте свой класс OAuth2SecurityConfiguration вот так

@Configuration
@EnableWebSecurity
public class OAuth2SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .csrf().disable()
            .anonymous().disable()
            .authorizeRequests()
            .antMatchers("/oauth/token").permitAll(); //This will permit the (oauth/token) url for getting access token from the oauthserver.
    }        

}

Теперь исправьте свой сервер ресурсов вот так

@Configuration
@EnableResourceServer
public class ResourceServerConfiguration  extends ResourceServerConfigurerAdapter {

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
            .antMatchers("/api/v1/register", "/api/v1/publicOne", "/api/v1/publicTwo").permitAll() //Allow urls
            .anyRequest().authenticated().and()
            .antMatcher("/api/**").authorizeRequests() //Authenticate all urls with this body /api/home, /api/gallery
            .antMatchers("/api/**").hasRole("ADMIN")
            .and().exceptionHandling().accessDeniedHandler(new OAuth2AccessDeniedHandler()); //This is optional if you want to handle exception
    }
}

Полный исходный код можно найти здесь. Надеюсь это поможет.

Примечание. Вы можете настроить свои URL-адреса на основе приведенного выше ответа.

person Abdullah Khan    schedule 23.10.2017
comment
Я добавил конфигурацию ResourceServerConfiguration со ссылкой на вашу, но все же я не могу получить доступ к apis под public без аутентификации. Это дает мне вот так { "error": "unauthorized", "error_description": "Full authentication is required to access this resource" } - person Alex Man; 23.10.2017
comment
Вы можете проверить мое ОБНОВЛЕНИЕ 2 - person Alex Man; 23.10.2017
comment
Это потому, что теперь вам нужны токены доступа для доступа ко всем защищенным URL-адресам. - person Abdullah Khan; 23.10.2017
comment
На самом деле я хочу, чтобы те apis, которые являются общедоступными, должны быть открыты без аутентификации. В oauth2 мы можем это сделать ... Я новичок в этом ... - person Alex Man; 23.10.2017
comment
Это разрушает всю цель Oauth. В любом случае проверьте обновленный @EnableResourceServer. - person Abdullah Khan; 23.10.2017
comment
что означают эти publicOne и publicTwo ... могут ли они быть доступны без аутентификации - person Alex Man; 23.10.2017
comment
Это просто, чтобы показать вам, как исключить URL-адреса из проверки oauth. Таким образом вы можете исключить URL-адреса, но вам также необходимо иметь @RequestMapping для этих URL-адресов в любом из ваших классов контроллера. - person Abdullah Khan; 23.10.2017
comment
можем ли мы что-нибудь сделать с @Override public void configure(WebSecurity web) throws Exception { web.ignoring().antMatchers("/public/**"); } - person Alex Man; 23.10.2017
comment
Да оформить заказ это . - person Abdullah Khan; 23.10.2017

Почему ваш URL-адрес запроса http://localhost:9001/resources/public/person

Я думаю, это должно быть похоже на http://localhost:9001/public/person

person Zenith    schedule 23.10.2017
comment
нет, на самом деле я определяю contextPath (/resources) в моем файле свойств server.contextPath: /resources - person Alex Man; 23.10.2017
comment
О, прости. Я пропустил это. Будет лучше, если вы поделитесь своим мнением. - person Zenith; 23.10.2017
comment
вы можете получить полный проект из bitbucket.org/hascode/spring-oauth2-example/src, дополнительно добавьте фиктивный контроллер отдыха и конфигурацию, показанную в моих обновлениях вопросов. - person Alex Man; 23.10.2017
comment
добавить в проект фиктивный контроллер и попытаться получить к нему доступ - person Alex Man; 23.10.2017
comment
Образца проекта, которому вы следовали, недостаточно. Надеюсь, этот URL-адрес поможет вам понять. github.com/dynamind/spring-boot-security-oauth2-minimal - person Zenith; 23.10.2017