Spring Boot Oauth2 oauth / token未在初始化时映射

时间:2017-09-22 12:06:56

标签: spring-boot oauth-2.0

我将OAuth2安全性应用于我的Spring Boot应用程序。 我的问题是,当我运行application / oauth / token路径时,在应用程序初始化时没有映射。

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

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

@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";
    }

应用程序控制台日志:

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: 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)

在此日志中,映射了GET / product / id,但未映射POST / oauth / token或任何OAuth路径,因此它提供404未找到错误。 我已上传配置,如果OAuth2安全性缺少任何配置,请告诉我。

1 个答案:

答案 0 :(得分:0)

我认为您缺少WebMvcConfigurerAdapter实现,我使用相同的技术(如spring boot)实现了相同的Ouath2应用程序。您可以验证您的配置文件,GitHub链接在这里 -