0

我想我在这里有一些奇怪的要求,因为无论我在哪里看,我都无法为我被要求做的事情举一个具体的例子。我创建了一个名为contacts 的虚拟项目来测试它。我想用 Oauth2 保护我的 api,但授权服务器不在同一个盒子上。

据我了解,客户端需要调用授权来获取令牌,然后带有令牌的请求将被发送到我的 api。

在我的服务器中,范围将确定用户是否有权访问。我没有在我的服务器上进行任何身份验证。

我似乎无法让它工作。

控制器

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping(value = "/contacts")
@PreAuthorize("#oauth2.hasScope('ec.edm.mdm')")
public class ContactsController {

    @Autowired
    ContactRepository customerRepo;

    @RequestMapping(method = RequestMethod.GET, produces = { "application/json" })
    public Page<Contact> findAllContacts(Pageable pagable) {
        return customerRepo.findAll(pagable);
    }
}

应用

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Profile;
import org.springframework.core.env.Environment;
import org.springframework.security.access.expression.method.MethodSecurityExpressionHandler;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.method.configuration.GlobalMethodSecurityConfiguration;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.provider.expression.OAuth2MethodSecurityExpressionHandler;



@EnableResourceServer
@SpringBootApplication
public class App {

    private static final Logger LOG = LoggerFactory.getLogger(App.class);
    @Autowired
    private Environment environment;



    public static void main(String[] args) throws Exception {
        SpringApplication.run(App.class, args);
    }

       /**
     * Allows for @PreAuthorize annotation processing.
     */
    @EnableGlobalMethodSecurity(prePostEnabled = true)
    protected static class GlobalSecurityConfiguration extends GlobalMethodSecurityConfiguration {
        @Override
        protected MethodSecurityExpressionHandler createExpressionHandler() {
            return new OAuth2MethodSecurityExpressionHandler();
        }
    }

}
4

0 回答 0