【问题标题】:RestController not working in oauth2 Spring BootRestController 在 oauth2 Spring Boot 中不起作用
【发布时间】:2017-10-23 21:50:35
【问题描述】:

我已经设置了一个身份验证服务器和资源服务器,如下文所述 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
    }

【问题讨论】:

  • 在你的主类中用@EnableAutoConfiguration替换@EnableResourceServer。让我知道状态。还要确保向服务器发出get 请求而不是post
  • @AtaurRahmanMunna 现在至少状态从 404 更改为 401,但现在我无法进行身份验证......即使我拥有正确的访问令牌,我也收到 401 Full authentication is required to access this resource@EnableResourceServer 用于使其成为 oauth right 的资源服务器
  • 我认为 spring 配置有问题。你在这里使用弹簧安全吗?如果答案是肯定的,那么请将您的HttpSecurity 配置放入WebSecurityConfigurerAdapterResourceServerConfigurerAdapter
  • 我正在使用spring-cloud-starter-security。这是我的 pom.xml bitbucket.org/hascode/spring-oauth2-example/src/…
  • 我看到你的pom.xml。在这里你包括spring-security。放置您的弹簧安全配置。你明白我的意思了吗?

标签: java spring spring-boot oauth-2.0 spring-security-oauth2


【解决方案1】:

通过在配置类上使用 @ComponentScan 或将 PersonController 移动到包 in 或em>在你的主类下用@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
    }
}

找到完整的源代码here。希望这会有所帮助。

注意:您可以根据上述答案自定义您的网址。

【讨论】:

  • 我已经根据你的参考添加了 ResourceServerConfiguration 配置,但我仍然无法在未经身份验证的情况下访问public 下的api。它给了我这样的{ "error": "unauthorized", "error_description": "Full authentication is required to access this resource" }
  • 你能检查我的更新 2
  • 那是因为现在您需要访问令牌才能访问所有受保护的 url。
  • 其实我希望那些公开的 api 应该需要在没有身份验证的情况下打开,在 oauth2 中我们可以这样做......我对这个很陌生......
  • 这违背了 Oauth 的全部目的。无论如何检查更新的@EnableResourceServer
【解决方案2】:

【讨论】:

  • 不,实际上我在属性文件server.contextPath: /resources中定义了contextPath (/resources)
  • “O”对不起。我错过了。如果你分享你的整个预测会更好。
  • 您可以从bitbucket.org/hascode/spring-oauth2-example/src 获得完整的项目,另外添加一个虚拟休息控制器和我的问题中显示的配置更新
  • 在项目中添加一个虚拟控制器并尝试访问它
  • 你遵循的项目样例还不够。我希望这个网址能帮助你理解。 github.com/dynamind/spring-boot-security-oauth2-minimal
猜你喜欢
  • 2018-09-24
  • 1970-01-01
  • 2017-01-13
  • 1970-01-01
  • 2020-03-23
  • 2018-05-12
  • 2017-04-23
  • 2021-06-18
  • 2017-07-28
相关资源
最近更新 更多