如何在Spring Boot中设置仅使用jwt令牌中的角色来允许访问的资源服务器?

时间:2018-12-07 10:01:19

标签: spring-boot oauth-2.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();
        }
    }

}

0 个答案:

没有答案