春季启动时出现错误“ org.springframework.web.client.HttpClientErrorException:404 null”

时间:2018-11-12 15:07:01

标签: java spring

我获得了授权代码,也获得了访问令牌并在控制台中刷新了令牌,但是之后,当用户登录并在路径/oauth/authorize中批准并将页面重定向到http://localhost:8090/showEmployees?code=kc0KuO时,它会引发错误,我们在其中找到错误控制台

  

org.springframework.web.client.HttpClientErrorException:404 null

     

Whitelabel错误页面

     

此应用程序没有针对/ error的显式映射,因此您看到了    作为后备。       星期一11月12日19“ :: 59:32       发生意外错误(类型=内部服务器错误,状态= 500)。       404 null

我很长一段时间都没有收到错误消息

@Configuration
    @EnableAuthorizationServer
    public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {       

        @Autowired
        private AuthenticationManager authenticationManager; 
        @Autowired
        private RedisConnectionFactory connectionFactory; 
        @Autowired
        private TokenStore tokenStore;
        @Autowired
        private UserDetailsServiceImpl userDetailsServiceImpl;
        @Autowired
        private AuthenticationProviderImpl authenticationProviderImpl;

        @Bean
        public TokenStore tokenStore() {
            return new RedisTokenStore(connectionFactory);
        }    

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

            configurer
            .inMemory()
            .withClient(Constants.CLIENT_ID)
            .secret(Constants.CLIENT_SECRET)
            .authorizedGrantTypes(Constants.GRANT_TYPE_PASSWORD, Constants.AUTHORIZATION_CODE, Constants.REFRESH_TOKEN)                 
            .scopes(Constants.SCOPE_READ, Constants.SCOPE_WRITE, Constants.TRUST).authorities("CLIENT")         
            .accessTokenValiditySeconds(Constants.ACCESS_TOKEN_VALIDITY_SECONDS)
            .refreshTokenValiditySeconds(Constants.REFRESH_TOKEN_VALIDITY_SECONDS);
        }   

        @Override
        public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
            oauthServer.tokenKeyAccess("permitAll()")
            .checkTokenAccess("isAuthenticated()");
        }    

        protected void configure(AuthenticationManagerBuilder auth) throws Exception {
            auth.authenticationProvider(authenticationProviderImpl);        
        }

        @Override
        public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {

            endpoints.authenticationManager(authenticationManager);
            endpoints.userDetailsService(userDetailsServiceImpl);
            endpoints.tokenStore(tokenStore);
        }
    }

SucurityConfig类别:

    @Configuration
    @EnableWebSecurity
    public class SecurityConfiguration extends WebSecurityConfigurerAdapter {   

        @Override
        public void configure(WebSecurity web) throws Exception {
            web.ignoring().antMatchers("/resources/**");
        }   

        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.authorizeRequests().antMatchers("/").permitAll().antMatchers("/user/getEmployeesList")
                .hasAnyRole("ADMIN").anyRequest().authenticated().and().formLogin()
                .permitAll().and().logout().permitAll();

            http.csrf().disable();
        }

        @Override
        public void configure(AuthenticationManagerBuilder authenticationMgr) throws Exception {
            authenticationMgr.inMemoryAuthentication().withUser("admin").password("admin")
                .authorities("ROLE_ADMIN");
        }

    }

类ResourceServer

@Configuration
        @EnableResourceServer
        class ResourceServer extends ResourceServerConfigurerAdapter {
            //Here we specify to allow the request to the url /user/getEmployeesList with valid access token and scope read 
            @Override
            public void configure(HttpSecurity http) throws Exception {
                http.requestMatchers().antMatchers("/user/getEmployeesList/**").and().authorizeRequests().anyRequest()
                        .access("#oauth2.hasScope('read')");
            }
        }




class Employee

public class Employee {

            private String empId;
            private String empName;

            ...getters/setters
        }

这是服务器端的控制器:

    @Controller
    public class ServerEmployeeController {

    @RequestMapping(value = "/user/getEmployeesList", method = RequestMethod.GET)

        public List<Employee> getEmployeesList() {
            List<Employee> employees = new ArrayList<>();
            Employee emp = new Employee();
            emp.setEmpId("emp1");
            emp.setEmpName("emp1");
            employees.add(emp);
            return employees;

        }
    }

这是客户端的控制器:

    @Controller
    public class ClientEmployeeController {

        private static final Logger logger = LoggerFactory.getLogger(EmployeeController.class); 

        @RequestMapping(value = "/getEmployees", method = RequestMethod.GET)
        //@GetMapping(value="/getEmployees")
        public ModelAndView getEmployeeInfo() {
            logger.info("inside employee controller");
           return new ModelAndView("getEmployees");
        }       

    @RequestMapping(value = "/showEmployees", method = RequestMethod.GET)
    public ModelAndView showEmployees(@RequestParam("code") String code) throws JsonProcessingException, IOException {
            ResponseEntity<String> response = null;
            System.out.println("Authorization Ccode------" + code);

            RestTemplate restTemplate = new RestTemplate();

            String credentials = "phynart-client:phynart-secret";
            String encodedCredentials = new String(Base64.encodeBase64(credentials.getBytes()));

            HttpHeaders headers = new HttpHeaders();
            headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
            headers.add("Authorization", "Basic " + encodedCredentials);

            HttpEntity<String> request = new HttpEntity<String>(headers);

            String access_token_url = "http://localhost:8080/oauth/token";
            access_token_url += "?code=" + code;
            access_token_url += "&grant_type=authorization_code";
            access_token_url += "&redirect_uri=http://localhost:8090/showEmployees";

            response = restTemplate.exchange(access_token_url, HttpMethod.POST, request, String.class);

            System.out.println("Access Token Response ---------" + response.getBody());

            // Get the Access Token From the recieved JSON response
            ObjectMapper mapper = new ObjectMapper();
            JsonNode node = mapper.readTree(response.getBody());
            String token = node.path("access_token").asText();

            String url = "http://localhost:8080/user/getEmployeesList";

            // Use the access token for authentication
            HttpHeaders headers1 = new HttpHeaders();
            headers1.add("Authorization", "Bearer " + token);
            HttpEntity<String> entity = new HttpEntity<>(headers1);
            logger.info("error11");


            ResponseEntity<Employee[]> employees = restTemplate.exchange(url, HttpMethod.GET, entity, Employee[].class);

            System.out.println(employees);

            Employee[] employeeArray = employees.getBody();

            ModelAndView model = new ModelAndView("showEmployees");
            model.addObject("employees", Arrays.asList(employeeArray));
            return model;
        }
    }

客户端的jsp页面:

    <%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <title>Get Employees</title>
    </head>
    <body>
        <h3 style="color: red;">Get Employee Info</h3>

        <div id="getEmployees">
            <form:form action="http://localhost:8080/oauth/authorize"
                method="post" modelAttribute="emp">
                <p>
                    <label>Enter Employee Id</label>
                     <input type="text" name="response_type" value="code" /> 
                     <input type="text" name="client_id" value="phynart-client" />
                     <input type="text" name="redirect_uri" value="http://localhost:8090/showEmployees" />
                     <input type="text" name="scope" value="read" /> 
                     <input type="SUBMIT" value="Get Employee info" />
            </form:form>
        </div>

    </body>
    </html>

客户端的jsp页面:

    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
    <%@page session="false"%>
    <html>
    <head>
    <title>Show Employees</title>
    </head>
    <body>

        <h3 style="color: red;">Show All Employees</h3>
        <ul>
            <c:forEach var="listValue" items="${employees}">
                <li>${listValue}</li>
            </c:forEach>
        </ul>
    </body>
    </html>

日志文件:

  

授权Ccode ------ kc0KuO访问令牌响应   --------- {“ access_token”:“ 2148555e-424f-4c00-b144-b5b3f8ee9336”,“ token_type”:“ bearer”,“ refresh_token”:“ cc2a35ca-1dcd-45bb-8246-0c958e8def6f”, “ expires_in”:488,“ scope”:“ read”}   2018-11-12 19:59:32.129错误23998 --- [nio-8090-exec-4]   o.a.c.c.C。[。[。[/]。[dispatcherServlet]:的Servlet.service()   路径[]中的servlet [dispatcherServlet]抛出异常   [请求处理失败;嵌套异常为   org.springframework.web.client.HttpClientErrorException:404 null]   根本原因

     

org.springframework.web.client.HttpClientErrorException:404 null at   org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:63)   〜[spring-web-4.3.9.RELEASE.jar:4.3.9.RELEASE]在   org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:700)   〜[spring-web-4.3.9.RELEASE.jar:4.3.9.RELEASE]在   org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:653)   〜[spring-web-4.3.9.RELEASE.jar:4.3.9.RELEASE]在   org.springframework.web.client.RestTemplate.execute(RestTemplate.java:613)   〜[spring-web-4.3.9.RELEASE.jar:4.3.9.RELEASE]在   org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:531)   〜[spring-web-4.3.9.RELEASE.jar:4.3.9.RELEASE]在   OAuth.oAuth.client.controller.EmployeeController.showEmployees(EmployeeController.java:109)   〜[classes /:na]在sun.reflect.NativeMethodAccessorImpl.invoke0(本机   方法)〜[na:1.8.0_181]在   sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)   〜[na:1.8.0_181]在   sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)   〜[na:1.8.0_181]在java.lang.reflect.Method.invoke(Method.java:498)   〜[na:1.8.0_181]在   org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)   〜[spring-web-4.3.9.RELEASE.jar:4.3.9.RELEASE]在   org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133)   〜[spring-web-4.3.9.RELEASE.jar:4.3.9.RELEASE]在   org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:97)   〜[spring-webmvc-4.3.9.RELEASE.jar:4.3.9.RELEASE]在   org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)   〜[spring-webmvc-4.3.9.RELEASE.jar:4.3.9.RELEASE]在   org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)   〜[spring-webmvc-4.3.9.RELEASE.jar:4.3.9.RELEASE]在   org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)   〜[spring-webmvc-4.3.9.RELEASE.jar:4.3.9.RELEASE]在   org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:967)   〜[spring-webmvc-4.3.9.RELEASE.jar:4.3.9.RELEASE]在   org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:901)   〜[spring-webmvc-4.3.9.RELEASE.jar:4.3.9.RELEASE]在   org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)   〜[spring-webmvc-4.3.9.RELEASE.jar:4.3.9.RELEASE]在   org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861)   〜[spring-webmvc-4.3.9.RELEASE.jar:4.3.9.RELEASE]在   javax.servlet.http.HttpServlet.service(HttpServlet.java:635)   〜[tomcat-embed-core-8.5.15.jar:8.5.15]在   org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)   〜[spring-webmvc-4.3.9.RELEASE.jar:4.3.9.RELEASE]在   javax.servlet.http.HttpServlet.service(HttpServlet.java:742)   〜[tomcat-embed-core-8.5.15.jar:8.5.15]在   org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)   〜[tomcat-embed-core-8.5.15.jar:8.5.15]在   org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)   〜[tomcat-embed-core-8.5.15.jar:8.5.15]在   org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)   〜[tomcat-embed-websocket-8.5.15.jar:8.5.15]在   org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)   〜[tomcat-embed-core-8.5.15.jar:8.5.15]在   org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)   〜[tomcat-embed-core-8.5.15.jar:8.5.15]在   org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:208)   〜[spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]在   org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:177)   〜[spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]在   org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346)   〜[spring-web-4.3.9.RELEASE.jar:4.3.9.RELEASE]在   org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:262)   〜[spring-web-4.3.9.RELEASE.jar:4.3.9.RELEASE]在   org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)   〜[tomcat-embed-core-8.5.15.jar:8.5.15]在   org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)   〜[tomcat-embed-core-8.5.15.jar:8.5.15]在   org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197)   〜[spring-web-4.3.9.RELEASE.jar:4.3.9.RELEASE]在   org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)   〜[spring-web-4.3.9.RELEASE.jar:4.3.9.RELEASE]在   org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)   〜[tomcat-embed-core-8.5.15.jar:8.5.15]在   org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)   〜[tomcat-embed-core-8.5.15.jar:8.5.15]在   org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198)   〜[tomcat-embed-core-8.5.15.jar:8.5.15]在   org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)   [tomcat-embed-core-8.5.15.jar:8.5.15]在   org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:478)   [tomcat-embed-core-8.5.15.jar:8.5.15]在   org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)   [tomcat-embed-core-8.5.15.jar:8.5.15]在   org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:80)   [tomcat-embed-core-8.5.15.jar:8.5.15]在   org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)   [tomcat-embed-core-8.5.15.jar:8.5.15]在   org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342)   [tomcat-embed-core-8.5.15.jar:8.5.15]在   org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:799)   [tomcat-embed-core-8.5.15.jar:8.5.15]在   org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)   [tomcat-embed-core-8.5.15.jar:8.5.15]在   org.apache.coyote.AbstractProtocol $ ConnectionHandler.process(AbstractProtocol.java:861)   [tomcat-embed-core-8.5.15.jar:8.5.15]在   org.apache.tomcat.util.net.NioEndpoint $ SocketProcessor.doRun(NioEndpoint.java:1455)   [tomcat-embed-core-8.5.15.jar:8.5.15]在   org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)   [tomcat-embed-core-8.5.15.jar:8.5.15]在   java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)   [na:1.8.0_181]在   java.util.concurrent.ThreadPoolExecutor $ Worker.run(ThreadPoolExecutor.java:624)   [na:1.8.0_181]在   org.apache.tomcat.util.threads.TaskThread $ WrappingRunnable.run(TaskThread.java:61)   [tomcat-embed-core-8.5.15.jar:8.5.15]在   java.lang.Thread.run(Thread.java:748)[na:1.8.0_181]

0 个答案:

没有答案