Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/design-patterns/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java spring-security-oauth2客户端需要在获得授权代码后再次进行身份验证(重新登录) 描述_Java_Spring_Spring Security Oauth2 - Fatal编程技术网

Java spring-security-oauth2客户端需要在获得授权代码后再次进行身份验证(重新登录) 描述

Java spring-security-oauth2客户端需要在获得授权代码后再次进行身份验证(重新登录) 描述,java,spring,spring-security-oauth2,Java,Spring,Spring Security Oauth2,我有一个授权服务器和客户端服务器。 授权服务器运行良好,我使用postman对其进行了测试,以获取accessToken和授权代码。 但是客户端服务器不工作。 在授权代码模式下,客户端登录,然后成功地从授权服务器获取授权代码,下一步,浏览器应该重定向到重定向uri,但没有,它重定向到客户端的登录页面 信息 java8,spring-boot-starter-parent-1.4.5.RELEASE,spring-boot-starter-security,spring-security-oaut

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

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

问题定位 org.springframework.security.oauth2.client.token.AccessTokenProviderChain.ActainAccessToken(OAuth2ProtectedResourceDetails,AccessTokenRequest)

SecurityContextHolder的身份验证是匿名身份验证令牌,我不知道为什么

客户端服务器配置
@springboot应用程序
@EnableOAuth2Client
公共类应用程序{
............. 
}
@配置
公共类CustomWebMvcConfig扩展了WebMVCConfigureAdapter{
@凌驾
public void addViewController(ViewControllerRegistry注册表){
registry.addViewController(“/”).setViewName(“索引”);
registry.addViewController(“/login”).setViewName(“login”);
super.addViewController(注册表);
}
}
@配置
公共类CustomWebSecurityConfig扩展了WebSecurityConfigureAdapter{
@自动连线
私有用户详细信息服务用户服务;
@凌驾
受保护的无效配置(AuthenticationManagerBuilder auth)引发异常{
auth.userDetailsService(userService);
super.configure(auth);
}
@凌驾
受保护的无效配置(HttpSecurity http)引发异常{
http
.授权请求()
.antMatchers(“/resources/**”,“/webjars/**”,“/img/**”).permitAll()
.antMatchers(“/login”).permitAll()
.antMatchers(“/getCurrentUserInfo”).authenticated()//需要访问令牌的资源
.anyRequest().permitAll()
.及()
.formLogin().login页面(“/login”).failureUrl(“/login?error”)
.defaultSuccessUrl(“/”)
.及()
.csrf()
.disable();
}
............. 
@自动连线
私有OAuth2ClientContext客户端上下文;
@请求映射(“/getCurrentUserInfo”)
@应答器
公共地图getCurrentUserInfo(){
AuthorizationCodeResourceDetails resourceDetails=新的AuthorizationCodeResourceDetails();
resourceDetails.setClientId(“授权代码”);
resourceDetails.setClientSecret(“123456”);
resourceDetails.setAccessTokenUri(“http://localhost:8080/oauth/token");
resourceDetails.setUserAuthorizationUri(“http://localhost:8080/oauth/authorize");
setScope(Arrays.asList(“空”);OAuth2RestTemplate restTemplate=新的OAuth2RestTemplate(resourceDetails,clientContext);
映射结果=restTemplate.getForObject(URI.create(“http://localhost:8082/user/getCurrentUserInfo),HashMap.class);
debug(“----------------------------result:{}”,result);
返回结果;
}
@服务
公共类UserDetailsServiceImpl实现UserDetailsService{
私有静态列表grantTypes=Arrays.asList(“授权码”、“密码”、“客户端凭据”、“隐式”);
@凌驾
public UserDetails loadUserByUsername(字符串用户名)引发UsernameNotFoundException{
如果(!grantTypes.contains(用户名)){
抛出新的UsernameNotFoundException(String.format(“用户 %s不存在!", 用户名);
}
User=新用户(用户名“123456”,Arrays.asList());
返回用户;
}
}

我太笨了,这是一个Cookie(会话)问题。 我的授权服务器和客户端服务器有相同的域:localhost,但端口不同。授权服务器是8080,客户端服务器是8081。 客户机服务器先登录,有cookie。 授权需要先登录,然后才能批准授权。 当授权登录时,客户端的cookie被覆盖。 当浏览器重定向到客户端页面时,客户端找不到自己使用授权cookie的会话

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

    }