spring security oauth2之refresh token

oAuth2.0认证服务器生成的Access_token是有有效期限制的默认为12个小时,refresh_token默认为三十天。如果Access_token提示过期,可以根据refresh_token获取新的Access_token

下面介绍如何生成refresh_token,并根据refresh_token获取新的Access_token:

authorizedGrantTypes

oauth2官方只有4种授权方式,不过spring security oauth2把refresh token也归为authorizedGrantTypes的一种,因此配置的时候只需要这样就把所有方式都支持了。

如果客户端信息是基于内存存储的则配置方式如下:

@Configuration
@EnableAuthorizationServer //提供/oauth/authorize,/oauth/token,/oauth/check_token,/oauth/confirm_access,/oauth/error
public class OAuth2ServerConfig extends AuthorizationServerConfigurerAdapter {
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
                .withClient("demoApp")
                .secret("demoAppSecret")
                .redirectUris("http://localhost:8081/callback") //新增redirect_uri
                .authorizedGrantTypes("authorization_code", "client_credentials", "refresh_token",
                        "password", "implicit")
                .scopes("all")
                .resourceIds("oauth2-resource")
                .accessTokenValiditySeconds(120)
                .refreshTokenValiditySeconds(60);
    }
}

客户信息如果基于JDBC数据库存储则配置信息如下:

package com.funtl.oauth2.server.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.userdetails.UserDetailsService;
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.ClientDetailsService;
import org.springframework.security.oauth2.provider.client.JdbcClientDetailsService;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JdbcTokenStore;

import com.funtl.oauth2.server.config.service.UserDetailsServiceImpl;

import javax.sql.DataSource;

@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {
  
    @Bean
    @Primary
    @ConfigurationProperties(prefix = "spring.datasource")  
    public DataSource dataSource() {
        // 配置数据源(注意,我使用的是 HikariCP 连接池),以上注解是指定数据源,否则会有冲突
        return DataSourceBuilder.create().build();
    }

   
    
    @Bean
    public TokenStore tokenStore() {
        // 基于 JDBC 实现,令牌保存到数据
        return new JdbcTokenStore(dataSource());
    }

    @Bean  
    public ClientDetailsService jdbcClientDetails() {
        // 基于 JDBC 实现,需要事先在数据库配置客户端信息  
        return new JdbcClientDetailsService(dataSource());
    }

    @Bean
    public UserDetailsService userDetailsService1() {  
    	WebSecurityConfiguration webSecurity = new WebSecurityConfiguration();
        return webSecurity.userDetailsService();
    }
    
    @Override  
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
    	
        // 设置令牌        
        endpoints.tokenStore(tokenStore()).userDetailsService(userDetailsService1());  
        // 最后一个参数为替换之后授权页面的url
        endpoints.pathMapping("/oauth/confirm_access","/custom/confirm_access");
            
    }
    
    @Override  
    public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
        oauthServer
                .tokenKeyAccess("permitAll()")
                .checkTokenAccess("permitAll()")  
                .allowFormAuthenticationForClients();
        
        
    }

    
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        // 读取客户端配置
        clients.withClientDetails(jdbcClientDetails());
    }
    
}

数据库客户端详细信息表oauth_client_details维护如下信息:

 

 第二步:配置userDetailsService

要使用refresh_token的话,需要额外配置userDetailsService

配置如下:

 @Bean
    public UserDetailsService userDetailsService1() {  
    	WebSecurityConfiguration webSecurity = new WebSecurityConfiguration();
        return webSecurity.userDetailsService();
    }
    
    @Override  
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
    	
        // 设置令牌        
        endpoints.tokenStore(tokenStore()).userDetailsService(userDetailsService1());  
        // 最后一个参数为替换之后授权页面的url
        endpoints.pathMapping("/oauth/confirm_access","/custom/confirm_access");
           
    }

否则则会提示如下报错信息:

HTTP/1.1 500
X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: 0
X-Frame-Options: DENY
X-Application-Context: application
Cache-Control: no-store
Pragma: no-cache
Content-Type: application/json;charset=UTF-8
Transfer-Encoding: chunked
Date: Wed, 06 Dec 2017 13:35:33 GMT
Connection: close

{"error":"server_error","error_description":"UserDetailsService is required."}

具体的接口调用请参照如下博客:

Spring Security oAuth2.0之refresh_token

最近准备了一个公众号每天都会推送一些开发中经常遇到的问题解决方法,希望多久关注一下,谢谢支持:

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 4
    评论
嗨!关于Spring Boot整合Spring SecurityOAuth2.0实现token认证,你可以按照以下步骤进行操作: 1. 添加依赖:在你的Spring Boot项目的pom.xml文件中,添加Spring SecurityOAuth2.0相关的依赖。 ```xml <dependencies> <!-- Spring Security --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <!-- Spring Security OAuth2 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-oauth2-client</artifactId> </dependency> </dependencies> ``` 2. 配置Spring Security:创建一个继承自WebSecurityConfigurerAdapter的配置类,并重写configure方法来配置Spring Security的行为。 ```java @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/oauth2/**", "/login/**", "/logout/**") .permitAll() .anyRequest() .authenticated() .and() .oauth2Login() .loginPage("/login") .and() .logout() .logoutSuccessUrl("/") .invalidateHttpSession(true) .clearAuthentication(true) .deleteCookies("JSESSIONID"); } } ``` 在上述配置中,我们允许访问一些特定的URL(如/oauth2/**,/login/**和/logout/**),并保护所有其他URL。我们还设置了自定义的登录页面和注销成功后的跳转页面。 3. 配置OAuth2.0:创建一个继承自AuthorizationServerConfigurerAdapter的配置类,并重写configure方法来配置OAuth2.0的行为。 ```java @Configuration @EnableAuthorizationServer public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter { @Autowired private AuthenticationManager authenticationManager; @Override public void configure(ClientDetailsServiceConfigurer clients) throws Exception { clients .inMemory() .withClient("client_id") .secret("client_secret") .authorizedGrantTypes("authorization_code", "password", "refresh_token") .scopes("read", "write") .accessTokenValiditySeconds(3600) .refreshTokenValiditySeconds(86400); } @Override public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception { endpoints .authenticationManager(authenticationManager); } } ``` 在上述配置中,我们使用内存存储客户端信息(client_id和client_secret),并配置了授权类型(如authorization_code、password和refresh_token)。我们还设置了访问令牌和刷新令牌的有效期。 4. 创建登录页面:创建一个HTML登录页面,用于用户进行身份验证并获取访问令牌。 ```html <!DOCTYPE html> <html> <head> <title>Login</title> </head> <body> <h2>Login</h2> <form th:action="@{/login}" method="post"> <div> <label for="username">Username:</label> <input type="text" id="username" name="username" /> </div> <div> <label for="password">Password:</label> <input type="password" id="password" name="password" /> </div> <div> <button type="submit">Login</button> </div> </form> </body> </html> ``` 5. 处理登录请求:创建一个控制器来处理登录请求,并在登录成功后重定向到受保护的资源。 ```java @Controller public class LoginController { @GetMapping("/login") public String showLoginForm() { return "login"; } @PostMapping("/login") public String loginSuccess() { return "redirect:/protected-resource"; } } ``` 在上述控制器中,我们使用@GetMapping注解来处理GET请求,@PostMapping注解来处理POST请求。登录成功后,我们将用户重定向到受保护的资源。 这样,你就完成了Spring Boot整合Spring SecurityOAuth2.0实现token认证的配置。你可以根据自己的需求进行进一步的定制和扩展。希望对你有所帮助!如果你有任何疑问,请随时问我。
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

李晓LOVE向阳

你的鼓励是我持续的不断动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值