Spring Boot:在OAUTH2中访问此资源需要完全身份验证

时间:2018-04-30 17:03:45

标签: spring spring-boot oauth-2.0 spring-security-oauth2

我无法将调用重定向到spring security登录页面。虽然内部重定向呼叫将我带到http://localhost:8081/auth/login,但在执行此操作时,我得到以下错误/ login

<oauth>
<error_description>
Full authentication is required to access this resource
</error_description>
<error>unauthorized</error>
</oauth>

我的客户端运行在8082上,服务器端运行在8081上, 当我点击http://localhost:8082/ui/时  它需要我通过重定向

http://localhost:8081/auth/oauth/authorize?client_id=ClientId&redirect_uri=http://localhost:8082/ui/login&response_type=code&state=ydLRdw

但在此重定向后给出错误“因为访问此资源需要完全身份验证 “在http://localhost:8081/auth/login

它应该提供一个登录页面来检查用户凭据,然后允许/禁止该请求。不知道我做错了什么。任何帮助都将受到高度赞赏。

我的客户端配置

@EnableOAuth2Sso
@Configuration
@EnableWebSecurity

public class OauthConfig extends WebSecurityConfigurerAdapter {

     @Autowired
        private OAuth2ClientContextFilter oauth2ClientContextFilter;



    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // TODO Auto-generated method stub
        /*http.antMatcher("/**").
        authorizeRequests().antMatchers("/","/login**").permitAll().anyRequest().authenticated();*/
         /*http    
         .authorizeRequests().anyRequest().authenticated();*/

        http.antMatcher("/**")
        .authorizeRequests()
        .antMatchers("/", "/login**")//.hasRole("USER").anyRequest()


        .permitAll()
        .anyRequest()
        .authenticated()
        .and()
        .httpBasic().and()

       .addFilterAfter(oauth2ClientContextFilter, SecurityContextPersistenceFilter.class);

    }



      public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {

            security.allowFormAuthenticationForClients();
        }

}

客户端的webconfig

@SuppressWarnings("deprecation")
@EnableWebMvc
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {

    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        // TODO Auto-generated method stub
         configurer.enable();
    }

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        // TODO Auto-generated method stub
        super.addViewControllers(registry);
        registry.addViewController("/").setViewName("forward:/index");
        registry.addViewController("/index");
        registry.addViewController("/secure");
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // TODO Auto-generated method stub
        registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
    }

    @Bean
    public  static PropertySourcesPlaceholderConfigurer placeHolderConfigurer()
    {
        return new PropertySourcesPlaceholderConfigurer();
    }

    @Bean
    public RequestContextListener contextlist() 
    {
        return new RequestContextListener();
    }

    @Bean
    public static PropertySourcesPlaceholderConfigurer placeholderConfigurer() {
        return new PropertySourcesPlaceholderConfigurer();
    }

}

客户端控制器

@Controller
public class BasicController {
    @GetMapping
      public String index() {
        return "index";
      }

      @GetMapping("/secure")
      public String secure() {
        return "secure";
      }
}

application.yml

 server:
  port: 8082
  servlet:
    context-path: /ui
  session: 
    cookieName: UISESSION

 security:
   oauth2: 
    client: 
      client-id: ClientId
      clientSecret: secret
      accessTokenUri: http://localhost:8081/auth/oauth/token
      userAuthorizationUri: http://localhost:8081/auth/oauth/authorize
    resource: 
      userInfoUri: http://localhost:8081/auth/rest/hello/principal
      preferTokenInfo: false

application.properties

spring.thymeleaf.cache= false
spring.mvc.view.prefix=/
spring.mvc.view.suffix=.html

spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.security.SecurityAutoConfiguration

server.port= 8082
server.servlet.session.cookie.name=UISESSION

management.endpoints.web.expose=*

我的index.html申请初始主页

<body>

    <h1>Spring Security OAuth Example</h1>

    <a href="secure">Login to OAuth here</a>

</body>

我的服务器端配置

授权服务器

@Configuration
@EnableAuthorizationServer
public class AuthorisationServerConfig extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private AuthenticationManager authenticationManager;





    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        // TODO Auto-generated method stub
        security.allowFormAuthenticationForClients();
        security.tokenKeyAccess("permitAll()")
        .checkTokenAccess("isAuthenticated()");

    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        // TODO Auto-generated method stub
        clients.inMemory().withClient("ClientId")//.authorities("ROLE_ADMIN")
        .secret("{noop}secret")
        .authorizedGrantTypes("authorization_code").scopes("user_info").autoApprove(true);
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        // TODO Auto-generated method stub
        endpoints.authenticationManager(authenticationManager);
    }



}

资源服务器

@EnableResourceServer
@Configuration
@Order(1000)    
public class ResourceServerConfig  extends WebSecurityConfigurerAdapter {

    @Autowired
    private AuthenticationManager authenticationManager; 
    @Autowired

    private  UserDetailsService customUserDetailsService;

    @Autowired
      public ResourceServerConfig(AuthenticationManager authenticationManager, 
              CustomUserDetailsService customUserDetailsService) {
        this.authenticationManager = authenticationManager;
        this.customUserDetailsService = customUserDetailsService;
      }


    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.requestMatchers().antMatchers("/login","/oauth/authorize").and().authorizeRequests()
        .anyRequest().fullyAuthenticated().and().formLogin().permitAll();//.and().csrf().disable();
        http.httpBasic();
        http.csrf().disable();

    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        // TODO Auto-generated method stub

        auth.parentAuthenticationManager(authenticationManager).
        userDetailsService(customUserDetailsService);
        //userDetailsService(customUserDetailsService).passwordEncoder(userPasswordEncoder);
    }   

}

服务

@Service
public class CustomUserDetailsService implements UserDetailsService{

    @Autowired
    private UserRepository userRepository;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // TODO Auto-generated method stub
        Optional<Users> userOptional= userRepository.findByName(username);
        userOptional.orElseThrow(() -> new UsernameNotFoundException("user not found"));
        return userOptional.map(users -> new CustomUserDetails(users)).get();
    }


}

0 个答案:

没有答案