неверный токен доступа не определен после добавления настроек sso - PullRequest
0 голосов
/ 13 декабря 2018

Я использую auth2 sso и весеннюю загрузку.При попытке получить токен доступа появляется сообщение об ошибке. Пожалуйста, объясните, почему это происходит и как решить эту проблему: с помощью sso auto перенаправляет вызов авторизации и получает эту ошибку, прежде чем добавить конфигурацию безопасности, она работает нормально и получить токен доступа.Для этого я использую пользовательский провайдер аутентификации.

2018-12-13 11:02:49.583 DEBUG 19440 --- [nio-8081-exec-7] p.a.OAuth2AuthenticationProcessingFilter : Authentication request failed: error="invalid_token", error_description="Invalid access token: undefined"
2018-12-13 11:02:49.587 DEBUG 19440 --- [nio-8081-exec-7] s.s.o.p.e.DefaultOAuth2ExceptionRenderer : Written [error="invalid_token", error_description="Invalid access token: undefined"] as "application/json;charset=UTF-8" using [org.springframework.http.converter.json.MappingJackson2HttpMessageConverter@65ffb33b]

Мой код похож на ниже.

Сервер авторизации:

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.authenticationManager(authenticationManager)
        .tokenEnhancer(CustomTokenEnhancer())
        .tokenStore(tokenStore());

    }    

    @Bean
    public TokenEnhancer CustomTokenEnhancer() {
        return new TokenEnhancer() {
            @Override
            public OAuth2AccessToken enhance(OAuth2AccessToken oAuth2AccessToken, OAuth2Authentication authentication) {
                DefaultOAuth2AccessToken newToken = new DefaultOAuth2AccessToken(oAuth2AccessToken);
                final Map<String, Object> additionalInfo = new HashMap<>();
                final String sessionId=(String) authentication.getUserAuthentication().getDetails();
                additionalInfo.put("id", authentication.getPrincipal());
                additionalInfo.put("authorities", authentication.getAuthorities());
                additionalInfo.put("sessionId", sessionId);
                SecurityContextHolder.getContext().setAuthentication(authentication);

                newToken.setAdditionalInformation(additionalInfo);
                return newToken;
            }


        };
    }


@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    @Autowired
    @Qualifier("authenticationManagerBean")
    private AuthenticationManager authenticationManager;

    @Value("${accessTokenValidity}")
    private Integer accessTokenValidity;




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

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
         System.out.println("accessTokenValidity: "+accessTokenValidity);
        clients
                .inMemory()
                .withClient("client")
                .secret("secret")
                .authorizedGrantTypes("authorization_code","password")
                .scopes("user_info")
                .autoApprove(true)
                .accessTokenValiditySeconds(accessTokenValidity)
                .resourceIds("oauth2-server");
;
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.authenticationManager(authenticationManager)
        .tokenEnhancer(CustomTokenEnhancer())
        .tokenStore(tokenStore());

    }


    @Bean
    public TokenEnhancer CustomTokenEnhancer() {
        return new TokenEnhancer() {
            @Override
            public OAuth2AccessToken enhance(OAuth2AccessToken oAuth2AccessToken, OAuth2Authentication authentication) {
                DefaultOAuth2AccessToken newToken = new DefaultOAuth2AccessToken(oAuth2AccessToken);
                final Map<String, Object> additionalInfo = new HashMap<>();
                final String sessionId=(String) authentication.getUserAuthentication().getDetails();
                additionalInfo.put("id", authentication.getPrincipal());
                additionalInfo.put("authorities", authentication.getAuthorities());
                additionalInfo.put("sessionId", sessionId);
                SecurityContextHolder.getContext().setAuthentication(authentication);

                newToken.setAdditionalInformation(additionalInfo);
                return newToken;
            }


        };
    }

    @Bean
    public InMemoryTokenStore tokenStore() throws Exception {
        return new InMemoryTokenStore();
    } 

}

Сервер ресурсов:

protected void configure(HttpSecurity http) throws Exception {

         http.authorizeRequests()
         .antMatchers( "**/oauth/**").permitAll()
             .and()
         .authorizeRequests()
         .anyRequest().authenticated()
         .and()
         .formLogin()
         .loginPage("/login")
         .permitAll()
         .and().logout().logoutRequestMatcher(new AntPathRequestMatcher("/oauth/rest/mcash/logout"))
         .permitAll().invalidateHttpSession(true).logoutSuccessUrl("/")
         .and()
         .exceptionHandling().accessDeniedHandler(accessDeniedHandler);

(accessDeniedHandler);
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) {

        auth.authenticationProvider(daoAuthenticationProvider());       


    }
@Override
    protected void configure(AuthenticationManagerBuilder auth) {

        auth.authenticationProvider(daoAuthenticationProvider());       

  }





   @Bean
   public AuthenticationProvider daoAuthenticationProvider()  {

        return new CustomAuthonticationProvider();
   }

Конфигурация безопасности в службе API:

@EnableOAuth2Sso
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter  {


    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()                
      .authorizeRequests()
      .antMatchers("**/authentication/**")
      .permitAll()
      .anyRequest().authenticated();

    }

пользовательский поставщик аутентификации:

public class CustomAuthonticationProvider implements AuthenticationProvider  {


    /* (non-Javadoc)
     * @see org.springframework.security.authentication.AuthenticationProvider#authenticate(org.springframework.security.core.Authentication)
     */
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {

            //custom validations

         UsernamePasswordAuthenticationToken authenticationToken=new UsernamePasswordAuthenticationToken(authentication.getPrincipal(), password, translate(user.getRoles()));
         if(null!=details) {
             authenticationToken.setDetails(details);

         }

         SecurityContextHolder.getContext().setAuthentication(authentication);

         return authenticationToken;
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...