尝试获取REST服务的身份验证令牌时,需要完全身份验证才能访问此资源

时间:2018-01-03 07:12:54

标签: java spring oauth-2.0

我的个人项目需要oauth2,因此我将在Spring网站上浏览this教程。

我的配置主要来自他们的example project安全模块。

然而,当我启动应用程序时,我无法获得令牌。当我尝试向http://localhost:8080/oauth/token发出POST请求时,服务器会一直显示“访问此资源需要完全身份验证”。

我正在使用Postman创建请求。使用导入转换它:

curl -X POST -vu android-bookmarks:123456 http://localhost:8080/oauth/token -H "Accept: application/json" -d "password=password&username=defaultuser&grant_type=password&scope=write&client_secret=123456&client_id=android-gps_tracker_server"

我花了一些时间寻找答案,但我找到的所有案例都不适合我。可能是什么问题?

这是配置代码: WebSecurityConfiguration:

@Configuration
public class WebSecurityConfiguration extends GlobalAuthenticationConfigurerAdapter{
    final private PlayerRepository playerRepository;

    @Autowired
    public WebSecurityConfiguration(PlayerRepository playerRepository) {
        this.playerRepository = playerRepository;
    }

    @Override
    public void init(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService());
    }

    @Bean
    UserDetailsService userDetailsService() {
        return (username) -> playerRepository.findByUserName(username)//@formatter:off
             .map(a -> new User(a.getUserName(), a.getPassword(), true, true, true, true, AuthorityUtils.createAuthorityList("ROLE_USER", "write")))
             .orElseThrow(() -> new UsernameNotFoundException("could not find the user '" + username + "'"));//@formatter:on
    }
}

OAuth2配置:

@Configuration
@EnableResourceServer
@EnableAuthorizationServer
public class OAuth2Configuration extends AuthorizationServerConfigurerAdapter{

    private final String applicationName = "gps_tracker_server";        
    private final AuthenticationManagerBuilder authenticationManager;

    @Autowired
    public OAuth2Configuration(AuthenticationManagerBuilder authenticationManager) {
        this.authenticationManager = authenticationManager;
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.authenticationManager(new AuthenticationManager(){
            @Override
            public Authentication authenticate(Authentication authentication) throws AuthenticationException {
                return authenticationManager.getOrBuild().authenticate(authentication);
            }
        });
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {

        clients.inMemory()
               .withClient("android-" + applicationName)
               .authorizedGrantTypes("password", "authorization_code", "refresh_token")
               .authorities("ROLE_USER")
               .scopes("write")
               .resourceIds(applicationName)
               .secret("123456");
    }

主应用程序:

@SpringBootApplication
public class GpsTrackerServerApplication{

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

    @Bean
    FilterRegistrationBean corsFilter(@Value("${tagit.origin:http://localhost:9000}") String origin) {
        return new FilterRegistrationBean(new Filter(){
            public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
                HttpServletRequest request = (HttpServletRequest) req;
                HttpServletResponse response = (HttpServletResponse) res;
                String method = request.getMethod();

                response.setHeader("Access-Control-Allow-Origin", origin);
                response.setHeader("Access-Control-Allow-Methods", "POST,GET,OPTIONS,DELETE");
                response.setHeader("Access-Control-Max-Age", Long.toString(60 * 60));
                response.setHeader("Access-Control-Allow-Credentials", "true");
                response.setHeader("Access-Control-Allow-Headers", "Origin,Accept,X-Requested-With,Content-Type,Access-Control-Request-Method,Access-Control-Request-Headers,Authorization");
                if ("OPTIONS".equals(method)) {
                    response.setStatus(HttpStatus.OK.value());
                } else {
                    chain.doFilter(req, res);
                }
            }

            public void init(FilterConfig filterConfig) { }

            public void destroy() { }
        });
    }

}

还有两个YML文件,一个是application-https.yml,另一个是application.yml。后者只保存DB cridentials和“profiles.active:https”。第一个看起来像这样:

server:
    port: 8443
    ssl:
        key-store: classpath:tomcat.keystore
        key-store-password: defaultuser
        key-password: defaultuser

1 个答案:

答案 0 :(得分:0)

我找到了答案。我必须将client_id和client_secret放入Postman的“授权”选项卡的“用户名”和“密码”字段中,并启用选项“基本验证”。然后我就能获得一个访问令牌 当使用从Curl语句导入时,Postman将id和secret放入x-www-form-urlencoded主体,这不起作用。