Spring Boot + OAuth2 + JWT: проблема с сохранением токена обновления в Cookie - PullRequest
0 голосов
/ 18 марта 2019

Я реализовал аутентификацию безопасности с использованием OAuth2 и JWT в моем приложении Spring Boot, которое хорошо работает. Теперь я пытаюсь сохранить сгенерированный токен обновления в Cookie на сервере и удалить его из ответа JSON, используя аннотированный класс с @ControllerAdivce.

Когда я запускаю свое приложение на http://localhost:8080/oauth/token,, мой класс @ControllerAdvice не вызывался. Что не так или что я забыл сделать?

Следуйте за моим кодом:

Класс WebSecurityConfig

package com.escolpi.aplicativo.api.config.security;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;

@Configuration
@EnableWebSecurity
@EnableResourceServer
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Bean
    public BCryptPasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

}

Класс ResourceServerConfig

package com.escolpi.aplicativo.api.config.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;

@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

    // @Autowired
    // private CredencialUsuarioService credencialUsuarioService;

    @Autowired
    private BCryptPasswordEncoder encoder;

    @Autowired
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().withUser("admin").password(encoder.encode("admin")).roles("ADMIN"); //
//      auth.userDetailsService(credencialUsuarioService).passwordEncoder(passwordEncoder());
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers(HttpMethod.GET, "/home").permitAll()
                .anyRequest().authenticated()
            .and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .and().csrf().disable();
    }

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        resources.stateless(true);
    }

}

Класс AuthorizationServerConfig

package com.escolpi.aplicativo.api.config.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
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;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;

@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    private static final String OAUTH2_CLIENT_ID = "escolpi-client";
    private static final String OAUTH2_CLIENT_SECRET = "secret";
    private static final int OAUTH2_ACCESS_TOKEN_VALIDITY = 1800; // 30 minutos
    private static final int OAUTH2_REFRESH_TOKEN_VALIDITY = (3600 * 24); // 24 horas
    private static final boolean OAUTH2_REUSE_REFRESH_TOKEN = false;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private BCryptPasswordEncoder encoder;

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory().withClient(OAUTH2_CLIENT_ID)
            .secret(encoder.encode(OAUTH2_CLIENT_SECRET))
            .scopes("read", "write")
            .authorizedGrantTypes("password", "refresh_token")
            .accessTokenValiditySeconds(OAUTH2_ACCESS_TOKEN_VALIDITY)
            .refreshTokenValiditySeconds(OAUTH2_REFRESH_TOKEN_VALIDITY);
    }

    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        security.allowFormAuthenticationForClients();
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.tokenStore(tokenStore()).accessTokenConverter(accessTokenConverter())
            .reuseRefreshTokens(OAUTH2_REUSE_REFRESH_TOKEN)
            .authenticationManager(authenticationManager);
    }

    @Bean
    public JwtAccessTokenConverter accessTokenConverter() {
        JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
        converter.setSigningKey("escolpi");

        return converter;
    }

    @Bean
    public TokenStore tokenStore() {
        return new JwtTokenStore(accessTokenConverter());
    }

}

Класс RefreshTokenPostProcessor (не вызываемый класс)

package com.escolpi.aplicativo.security.token;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.http.server.ServletServerHttpResponse;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import com.escolpi.aplicativo.api.util.Dominios;

@ControllerAdvice
public class RefreshTokenPostProcessor implements ResponseBodyAdvice<OAuth2AccessToken> {

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        System.out.println(returnType.getMethod().getName());
        return returnType.getMethod().getName().equals("postAccessToken");
    }

    @Override
    public OAuth2AccessToken beforeBodyWrite(OAuth2AccessToken body, MethodParameter returnType,
            MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType,
            ServerHttpRequest request, ServerHttpResponse response) {
        DefaultOAuth2AccessToken token = (DefaultOAuth2AccessToken) body;
        String refreshToken = body.getRefreshToken().getValue();
        HttpServletRequest req = ((ServletServerHttpRequest) request).getServletRequest();
        HttpServletResponse resp = ((ServletServerHttpResponse) response).getServletResponse();

        adicionarRefreshTokenNoCookie(refreshToken, req, resp);
        removerRefreshTokenDoBody(token);

        return token;
    }

    /**
     * Addiciona um Refresh Token em um Cookie seguro.
     * @param refreshToken: String
     * @param request: HttpServletRequest
     * @param response: HttpServletResponse
     */
    private void adicionarRefreshTokenNoCookie(String refreshToken, HttpServletRequest request, HttpServletResponse response) {
        Cookie refreshTokenCookie = new Cookie(Dominios.NOME_REQUEST_TOKEN, refreshToken);
        refreshTokenCookie.setHttpOnly(true);
        // TODO: Segurança do Cookie para true em Produção
        refreshTokenCookie.setSecure(false);
        refreshTokenCookie.setPath(request.getContextPath() + Dominios.OAUTH2_TOKEN_PATH);
        refreshTokenCookie.setMaxAge(2592000); // 30 dias
        response.addCookie(refreshTokenCookie);
    }

    /**
     * Remove um Refresh Token.
     * @param body: DefaultOAuth2AccessToken
     */
    private void removerRefreshTokenDoBody(DefaultOAuth2AccessToken body) {
        body.setRefreshToken(null);
    }

}

Константы были определены в Dominios class

package com.escolpi.aplicativo.api.util;
public class Dominios {
    // ommited code
    public static final String NOME_REQUEST_TOKEN = "refreshToken";
    public static final String OAUTH2_TOKEN_PATH = "/oauth/token";
}

Ответ при доступе http://localhost:8080/oauth/token:

{
    "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1NTI5MjQ2NDYsInVzZXJfbmFtZSI6ImFkbWluIiwiYXV0aG9yaXRpZXMiOlsiUk9MRV9BRE1JTiJdLCJqdGkiOiIxZTUzZmUyOS03N2FmLTQ2NGUtOTgwNy0yNThjYjMyMjgyZTkiLCJjbGllbnRfaWQiOiJlc2NvbHBpLWNsaWVudCIsInNjb3BlIjpbInJlYWQiLCJ3cml0ZSJdfQ.ZTpdfStVb__DRi7eyF95ivSYJlax7-OF5JrVQjZpq4I",
    "token_type": "bearer",
    "refresh_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX25hbWUiOiJhZG1pbiIsInNjb3BlIjpbInJlYWQiLCJ3cml0ZSJdLCJhdGkiOiIxZTUzZmUyOS03N2FmLTQ2NGUtOTgwNy0yNThjYjMyMjgyZTkiLCJleHAiOjE1NTMwMDkyNDYsImF1dGhvcml0aWVzIjpbIlJPTEVfQURNSU4iXSwianRpIjoiMTRjZWNmZmUtZDIzMi00ZmM3LTk1NTEtZWRjNjVmMGQxNmNhIiwiY2xpZW50X2lkIjoiZXNjb2xwaS1jbGllbnQifQ.z5kuBm87Dp9mxCH2n_AsUu8DJrTvyRkICdkctr7btkU",
    "expires_in": 1799,
    "scope": "read write",
    "jti": "1e53fe29-77af-464e-9807-258cb32282e9"
}

Большое спасибо!

...