当前位置: 首页 > 知识库问答 >
问题:

令牌过期时的Spring OAuth2重定向

刘高峯
2023-03-14

我很难在Spring中做这个简单的事情:当访问令牌过期时重定向到登录页面。

    null

根据我的理解,资源服务器应该是处理这种机制的服务器(如果我错了请纠正我)。

我一直在尝试不同的不成功的方法:

  • 在OAuth2AuthenticationProcessingFilter之后添加筛选器并检查令牌有效性和sendRedirect
  • 向我的应用程序添加自定义OAuth2AuthenticationEntryPoint(扩展ResourceServerConfigurerAdapter)
  • 使用自定义处理程序/入口点添加。ExceptionHandling()。
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerOAuthConfig extends AuthorizationServerConfigurerAdapter {
    ....

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints
                .authenticationManager(this.authenticationManager)
                .accessTokenConverter(accessTokenConverter())
                .approvalStore(approvalStore())
                .authorizationCodeServices(authorizationCodeServices())
                .tokenStore(tokenStore());
    }

    /**
      * Configure the /check_token endpoint.
      * This end point will be accessible for the resource servers to verify the token validity
      * @param securityConfigurer
      * @throws Exception
      */
    @Override
    public void configure(AuthorizationServerSecurityConfigurer securityConfigurer) throws Exception {
        securityConfigurer
            .tokenKeyAccess("permitAll()")
            .checkTokenAccess("hasAuthority('ROLE_TRUSTED_CLIENT')");
    }
}

@Configuration
@Order(-20)
public class AuthorizationServerSecurityConfig extends WebSecurityConfigurerAdapter {

    private static final Logger log = LoggerFactory.getLogger(AuthorizationServerSecurityConfig.class);

    @Autowired
    private DataSource oauthDataSource;

    @Autowired
    private AuthenticationFailureHandler eventAuthenticationFailureHandler;

    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    public void globalUserDetails(AuthenticationManagerBuilder auth) throws UserDetailsException {
        try {
            log.debug("Updating AuthenticationManagerBuilder to use userDetailService with a BCryptPasswordEncoder");
            auth.userDetailsService(userDetailsService()).passwordEncoder(new BCryptPasswordEncoder());
        } catch (Exception e) {
            throw new UserDetailsException(e);
        }
    }

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

    @Override
    public UserDetailsService userDetailsService() {
        return this.userDetailsService;
    }

    @Override
    protected void configure(final HttpSecurity http) throws Exception {
        log.debug("Updating HttpSecurity configuration");

        // @formatter:off
        http
            .requestMatchers()
                .antMatchers("/login*", "/login?error=true", "/oauth/authorize", "/oauth/confirm_access")
                .and()
            .authorizeRequests()
                .antMatchers("/login*", "/oauth/authorize", "/oauth/confirm_access").permitAll()
                .anyRequest().authenticated()
                .and()
            .formLogin()
                .loginPage("/login")
                .failureUrl("/login?error=true")
                .failureHandler(eventAuthenticationFailureHandler);
        // @formatter:on
    }
server:
    port: 9999
    contextPath: /uaa

eureka:
    client:
        serviceUrl:
            defaultZone: http://localhost:8761/eureka/

security:
    user:
        password: password

spring:
    datasource_oauth:
        driverClassName: com.mysql.jdbc.Driver
        url: jdbc:mysql://localhost:3306/oauth2_server
        username: abc
        password: 123
    jpa:
        ddl-create: true
    timeleaf:
        cache: false
        prefix: classpath:/templates

logging:
    level:
        org.springframework.security: DEBUG

authentication:
    attempts:
        maximum: 3
@EnableResourceServer
@EnableEurekaClient
@SpringBootApplication
public class Application extends ResourceServerConfigurerAdapter {

    private CustomAuthenticator customFilter = new CustomAuthenticator();

    /**
     * Launching Spring Boot
     * @param args
     */
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args); //NOSONAR
    }

    /**
     * Configuring Token converter
     * @return
     */
    @Bean
    public AccessTokenConverter accessTokenConverter() {
        return new DefaultAccessTokenConverter();
    }

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        resources.authenticationManager(customFilter);
    }

    /**
     * Configuring HTTP Security
     * @param http
     * @throws Exception
     */
    @Override
    public void configure(HttpSecurity http) throws Exception {
        // @formatter:off
        http
            .authorizeRequests().antMatchers("/**").authenticated()
            .and()
                .csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
            .and()
                .addFilterBefore(customFilter, AbstractPreAuthenticatedProcessingFilter.class);

        // @formatter:on
    }

    protected static class CustomAuthenticator extends OAuth2AuthenticationManager implements Filter {

        private static Logger logger = LoggerFactory.getLogger(CustomAuthenticator.class);
        private TokenExtractor tokenExtractor = new BearerTokenExtractor();
        private AuthenticationManager authenticationManager;
        private AuthenticationDetailsSource<HttpServletRequest, ?> authenticationDetailsSource = new OAuth2AuthenticationDetailsSource();
        private boolean inError = false;

        @Override
        public Authentication authenticate(Authentication authentication) throws AuthenticationException {
            try {
                return super.authenticate(authentication);
            }
            catch (Exception e) {
                inError = true;
                return new CustomAuthentication(authentication.getPrincipal(), authentication.getCredentials());
            }
        }

        @Override
        public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
                throws ServletException, IOException {

            logger.debug("Token Error redirecting to Login page");

            if(this.inError) {
                logger.debug("In error");

                RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();

                final HttpServletRequest req = (HttpServletRequest) request;
                final HttpServletResponse res = (HttpServletResponse) response;

                redirectStrategy.sendRedirect(req, res, "http://localhost:8765/login");

                this.inError = false;
                return;
            } else {
                filterChain.doFilter(request, response);
            }
        }

        @Override
        public void destroy() {
        }

        @Override
        public void init(FilterConfig arg0) throws ServletException {
        }

        @SuppressWarnings("serial")
        protected static class CustomAuthentication extends PreAuthenticatedAuthenticationToken {

            public CustomAuthentication(Object principal, Object credentials) {
                super(principal, credentials);
            }

        }

    }
}
server:
    port: 0

eureka:
    client:
        serviceUrl:
            defaultZone: http://localhost:8761/eureka/

security:
    oauth2:
        resource:
            userInfoUri: http://localhost:9999/uaa/user

logging:
    level:
        org.springframework.security: DEBUG
@SpringBootApplication
@EnableEurekaClient
@EnableZuulProxy
@EnableOAuth2Sso
public class EdgeServerApplication extends WebSecurityConfigurerAdapter {

    /**
     * Configuring Spring security
     * @return
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // @formatter:off
        http.logout()
            .and()
                .authorizeRequests().antMatchers("/**").authenticated()
            .and()
                .csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse());
        // @formatter:on
    }

    /**
     * Launching Spring Boot
     * @param args
     */
    public static void main(String[] args) {
        SpringApplication.run(EdgeServerApplication.class, args); //NOSONAR
    }
}

其application.yml配置

server:
    port: 8765

eureka:
    client:
        serviceUrl:
            defaultZone: http://localhost:8761/eureka/

security:
    user:
        password: none
    oauth2:
        client:
            accessTokenUri: http://localhost:9999/uaa/oauth/token
            userAuthorizationUri: http://localhost:9999/uaa/oauth/authorize
            clientId: spa
            clientSecret: spasecret
        resource:
            userInfoUri: http://localhost:9999/uaa/user

zuul:
    debug:
        request: true
    routes:
        authorization-server:
            path: /uaa/**
            stripPrefix: false
        fast-funds-service:
            path: /**

logging:
    level:
        org.springframework.security: DEBUG

谢谢你的帮助

共有1个答案

饶明亮
2023-03-14

尝试将刷新令牌的有效性设置为0或1秒。

@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
    clients.inMemory()
           .withClient("javadeveloperzone")
           .secret("secret")
           .accessTokenValiditySeconds(2000)        // expire time for access token
           .refreshTokenValiditySeconds(-1)         // expire time for refresh token
           .scopes("read", "write")                         // scope related to resource server
           .authorizedGrantTypes("password", "refresh_token");      // grant type

https://javadeveloperzone.com/spring-security/spring-security-oauth2-success-or-failed-event-listener/#22_securityoauth2configuration

 类似资料:
  • 我用ReactJS做单页网页登录。问题是如何以及在哪里保存令牌过期时间。我需要保存在sessionStore中,但当浏览器关闭时,所有的数据都将被删除。本地商店?但数据将永远。或者我可以在localStore中保存并在每个事件中添加函数,该函数检查localStore的过期时间,当事件触发成功时再次更新localStore?但代码看起来很可怕...性能问题呢?这大概可以接受吗?

  • 我对android Gcm令牌过期策略很好奇。当我希望向Gcm服务注册的设备能够接收Gcm推送消息时,我将向API注册它。 然后我会得到一个Gcm令牌“a”。如果我从未在play store上升级我的应用程序版本代码。谷歌会用“B”刷新它并自动终止“A”吗? 如果是,它什么时候做。我看过一些文章说,一旦“A”被“B”刷新,那么当服务器试图向“A”发送消息时,服务器将获得新的注册标识“B”。我现在想

  • 我已经阅读了跑道文档。我特别考虑了以下关于使用的声明: 此请求返回与上述相同的数据,您可以继续反复执行此操作,以保持应用程序的身份验证,而无需要求用户重新身份验证。 这是否意味着将无限期有效或过期: < li >签发后X天;或者 < li >最后一次使用它获取新的< code>access_token后的X天 编辑:请参阅此跑道线程,该线程提出相同的问题,但似乎没有给出任何关于Oauth2.0协议

  • 当然,如果我们对每个请求进行一次到DB的往返,那么我们就可以验证帐户是有效的还是无效的。我的问题是,什么是最好的方法来照顾这种情况的长寿命代币。 提前道谢。

  • 我正在使用NodeJS访问Azure ServiceBus,它工作了好几天。突然,我开始收到错误 订阅删除错误:错误:401-ExpiredToken:。跟踪ID:xxxxxx-xxxxxxx,时间戳:2015年4月8日12:32:54 PM 我正在使用连接字符串连接到ServiceBus 只有一个共享访问策略“RootManageSharedAccessKey”具有“管理、发送、监听”的权限 这

  • google oauth2刷新令牌何时过期? 我所说的过期是指过期是因为经过了某个时间跨度(不是因为用户已撤销访问权限或用户已请求新的刷新令牌) 我做了一些研究,没有一个引用官方的谷歌文档(我也找不到一个有效的谷歌文档) 其他一些问题表示,由于时间,它从未过期: 谷歌刷新令牌过期了吗? https://community.fitbit.com/t5/web-api-development/inva