获取授权代码

时间:2017-03-13 12:23:57

标签: java spring spring-security-oauth2

描述

我有授权服务器和客户端服务器。 授权服务器运行良好,我用postman测试它以获取accessToken和授权代码。 但是客户端服务器不起作用。 在authorization_code模式下,客户端登录,然后从授权服务器成功获取授权代码,下一步,浏览器应该重定向到redirect_uri,但它没有,它重定向到客户端的登录页面。

信息

java8,spring-boot-starter-parent-1.4.5.RELEASE,spring-boot-starter-security,spring-security-oauth2

问题地点

org.springframework.security.oauth2.client.token.AccessTokenProviderChain.obtainAccessToken(OAuth2ProtectedResourceDetails,AccessTokenRequest)

   Authentication auth = SecurityContextHolder.getContext().getAuthentication();

    if (auth instanceof AnonymousAuthenticationToken) {
        if (!resource.isClientOnly()) {
            throw new InsufficientAuthenticationException(
                    "Authentication is required to obtain an access token (anonymous not allowed)");
        }
    }

SecurityContextHolder的身份验证是AnonymousAuthenticationToken,我不知道原因。

客户端服务器配置

 @SpringBootApplication 
 @EnableOAuth2Client 
 public class App {
       ............. 
 }

 @Configuration
 public class CustomWebMvcConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {

        registry.addViewController("/").setViewName("index");
        registry.addViewController("/login").setViewName("login");


        super.addViewControllers(registry);
    }

 }


 @Configuration
 public class CustomWebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService userService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

        auth.userDetailsService(userService);

        super.configure(auth);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
            .antMatchers("/resources/**", "/webjars/**", "/img/**").permitAll()
            .antMatchers("/login").permitAll()
            .antMatchers("/getCurrentUserInfo").authenticated()//the resource that need access token
            .anyRequest().permitAll()
        .and()
            .formLogin().loginPage("/login").failureUrl("/login?error")
            .defaultSuccessUrl("/")
         .and()
            .csrf()
            .disable();
    }
  ............. 



        @Autowired
        private OAuth2ClientContext clientContext;


        @RequestMapping("/getCurrentUserInfo")
        @ResponseBody
        public Map<String, String> getCurrentUserInfo(){

            AuthorizationCodeResourceDetails resourceDetails = new AuthorizationCodeResourceDetails();
            resourceDetails.setClientId("authorization_code");
            resourceDetails.setClientSecret("123456");
            resourceDetails.setAccessTokenUri("http://localhost:8080/oauth/token");
            resourceDetails.setUserAuthorizationUri("http://localhost:8080/oauth/authorize");
            resourceDetails.setScope(Arrays.asList("empty"));               OAuth2RestTemplate restTemplate =  new OAuth2RestTemplate(resourceDetails, clientContext);

            Map<String, String> result = restTemplate.getForObject(URI.create("http://localhost:8082/user/getCurrentUserInfo"), HashMap.class);

            logger.debug("------------------------- result: {}",result);

            return result;
        }


    @Service
    public class UserDetailsServiceImpl implements UserDetailsService {

        private static List<String> grantTypes = Arrays.asList("authorization_code", "password", "client_credentials", "implicit");

        @Override
        public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

            if(!grantTypes.contains(username)){
                throw new UsernameNotFoundException(String.format("用户 %s 不存在!", username));
            }

            User user = new User(username, "123456", Arrays.asList());

            return user;
        }

    }

1 个答案:

答案 0 :(得分:0)

我太蠢了,这是一个Cookie(会话)问题。 我的授权服务器和客户端服务器具有相同的域:localhost,但不同的端口。授权服务器为8080,客户端服务器为8081。 Client Server首先登录,有cookie。 授权需要在批准授权之前登录。 授权登录时,将涵盖客户的cookie。 当浏览器重定向到客户端页面时,客户端无法使用授权的cookie找到自己的会话。