Spring Boot + OAuth2 + JWT:无法在Cookie中存储刷新令牌

时间:2019-03-18 16:57:33

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

我已经在我的Spring Boot应用程序上使用OAuth2和JWT实现了安全身份验证,效果很好。现在,我尝试将生成的刷新令牌存储在服务器上的Cookie中,并使用带有@ControllerAdivce的带注释的类将其从JSON响应中删除。

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

中定义
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"
}

非常感谢!

0 个答案:

没有答案