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