简体   繁体   English

Spring Boot Oauth2 OAuth /令牌在初始化时未映射

[英]Spring Boot Oauth2 oauth/token not mapped on initialization

I am applying OAuth2 security to my Spring Boot Application. 我正在将OAuth2安全性应用于我的Spring Boot应用程序。 My issue is that when I run the application /oauth/token path is not mapped at the time of application initialization. 我的问题是,当我运行应用程序时,/ oauth / token路径在应用程序初始化时未映射。

AuthorizationServerConfig.java AuthorizationServerConfig.java

package com.example.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;

@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private AuthenticationManager authenticationManager;

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

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory().withClient("clientid")
        .secret("secret")
        .authorizedGrantTypes("authorization_code")
        .scopes("user_info")
        .autoApprove(true);
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.authenticationManager(authenticationManager);
    }
}

ResourceServerConfig.java ResourceServerConfig.java

package com.example.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;

@EnableResourceServer
@Configuration
public class ResourceServerConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.requestMatchers().antMatchers("/").and().authorizeRequests().anyRequest().authenticated();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.parentAuthenticationManager(authenticationManager)
        .inMemoryAuthentication().withUser("admin")
        .password("admin")
        .roles("ADMIN");
    }
}

ProductRestController.java ProductRestController.java

@RestController
@RequestMapping("/product")
public class ProductRestController {

    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    @ResponseBody
    public String getProductById(@PathVariable("id") int id) {

        System.out.println("In Controller");

        return "Hello";
    }

Application Console Log: 应用程序控制台日志:

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v1.5.7.RELEASE)

2017-09-22 11:40:51.155  INFO 10744 --- [  restartedMain] c.o.inventory.launch.Application         : Starting Application on Twinkle-PC with PID 10744 (D:\OrderhiveSpring\orderhive-inventory\bin started by Twinkle in D:\OrderhiveSpring\orderhive-inventory)
2017-09-22 11:40:51.155  INFO 10744 --- [  restartedMain] c.o.inventory.launch.Application         : No active profile set, falling back to default profiles: default
2017-09-22 11:40:51.155  INFO 10744 --- [  restartedMain] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@9cbf79e: startup date [Fri Sep 22 11:40:51 UTC 2017]; root of context hierarchy
2017-09-22 11:40:52.050  INFO 10744 --- [  restartedMain] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8888 (http)
2017-09-22 11:40:52.050  INFO 10744 --- [  restartedMain] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2017-09-22 11:40:52.051  INFO 10744 --- [  restartedMain] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/8.5.20
2017-09-22 11:40:52.063  INFO 10744 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2017-09-22 11:40:52.064  INFO 10744 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 909 ms
2017-09-22 11:40:52.124  INFO 10744 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'characterEncodingFilter' to: [/*]
2017-09-22 11:40:52.124  INFO 10744 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2017-09-22 11:40:52.124  INFO 10744 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2017-09-22 11:40:52.124  INFO 10744 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'requestContextFilter' to: [/*]
2017-09-22 11:40:52.124  INFO 10744 --- [ost-startStop-1] .s.DelegatingFilterProxyRegistrationBean : Mapping filter: 'springSecurityFilterChain' to: [/*]
2017-09-22 11:40:52.124  INFO 10744 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean  : Mapping servlet: 'dispatcherServlet' to [/]
2017-09-22 11:40:58.354  INFO 10744 --- [  restartedMain] j.LocalContainerEntityManagerFactoryBean : Building JPA container EntityManagerFactory for persistence unit 'default'
2017-09-22 11:40:58.355  INFO 10744 --- [  restartedMain] o.hibernate.jpa.internal.util.LogHelper  : HHH000204: Processing PersistenceUnitInfo [
    name: default
    ...]
2017-09-22 11:40:58.362  INFO 10744 --- [  restartedMain] org.hibernate.dialect.Dialect            : HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
2017-09-22 11:40:58.592  INFO 10744 --- [  restartedMain] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2017-09-22 11:40:58.856  INFO 10744 --- [  restartedMain] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@9cbf79e: startup date [Fri Sep 22 11:40:51 UTC 2017]; root of context hierarchy
2017-09-22 11:40:58.871  INFO 10744 --- [  restartedMain] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/product/{id}],methods=[GET]}" onto public java.lang.String com.orderhive.inventory.controller.ProductRestController.getProductById(int)
2017-09-22 11:40:58.871  INFO 10744 --- [  restartedMain] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2017-09-22 11:40:58.871  INFO 10744 --- [  restartedMain] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2017-09-22 11:40:58.887  INFO 10744 --- [  restartedMain] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-09-22 11:40:58.887  INFO 10744 --- [  restartedMain] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-09-22 11:40:58.902  INFO 10744 --- [  restartedMain] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-09-22 11:40:58.949  INFO 10744 --- [  restartedMain] b.a.s.AuthenticationManagerConfiguration : 

Using default security password: a1f8d8ad-e937-4dd6-8be2-2648a9ed9a80

2017-09-22 11:40:58.964  INFO 10744 --- [  restartedMain] o.s.s.web.DefaultSecurityFilterChain     : Creating filter chain: OrRequestMatcher [requestMatchers=[Ant [pattern='/css/**'], Ant [pattern='/js/**'], Ant [pattern='/images/**'], Ant [pattern='/webjars/**'], Ant [pattern='/**/favicon.ico'], Ant [pattern='/error']]], []
2017-09-22 11:40:58.964  INFO 10744 --- [  restartedMain] o.s.s.web.DefaultSecurityFilterChain     : Creating filter chain: OrRequestMatcher [requestMatchers=[Ant [pattern='/**']]], [org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter@6a1033a9, org.springframework.security.web.context.SecurityContextPersistenceFilter@35d7fa68, org.springframework.security.web.header.HeaderWriterFilter@7d6e8d02, org.springframework.security.web.authentication.logout.LogoutFilter@e859232, org.springframework.security.web.authentication.www.BasicAuthenticationFilter@40b3d30, org.springframework.security.web.savedrequest.RequestCacheAwareFilter@57b0571b, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter@5e3fd672, org.springframework.security.web.authentication.AnonymousAuthenticationFilter@48992772, org.springframework.security.web.session.SessionManagementFilter@69c735a2, org.springframework.security.web.access.ExceptionTranslationFilter@723216e7, org.springframework.security.web.access.intercept.FilterSecurityInterceptor@e7327d0]
2017-09-22 11:40:59.002  INFO 10744 --- [  restartedMain] o.s.b.d.a.OptionalLiveReloadServer       : LiveReload server is running on port 35729
2017-09-22 11:40:59.042  INFO 10744 --- [  restartedMain] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
2017-09-22 11:40:59.054  INFO 10744 --- [  restartedMain] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8888 (http)
2017-09-22 11:40:59.056  INFO 10744 --- [  restartedMain] c.o.inventory.launch.Application         : Started Application in 7.936 seconds (JVM running for 1520.559)

In this log, GET /product/id is mapped but POST /oauth/token or any of the OAuth paths are not mapped and hence it gives a 404 not found error. 在此日志中,GET / product / id已映射,但POST / oauth / token或任何OAuth路径均未映射,因此会出现404 not found错误。 I have uploaded the configurations,let me know if any config is missing for OAuth2 security. 我已经上传了配置,请让我知道OAuth2安全性是否缺少任何配置。

I think you are missing WebMvcConfigurerAdapter implementation, I have implemented the same Ouath2 applications using same technologies like spring boot. 我认为您缺少WebMvcConfigurerAdapter实现,我已经使用诸如Spring Boot的相同技术实现了相同的Ouath2应用程序。 You can verify your config files, GitHub links are here- 您可以验证您的配置文件,GitHub链接在此处-

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM