• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

SpringBoot整合Oauth2开放平台接口授权案例

武飞扬头像
夏木炎
帮助1

  1.  
    <!-- SpringBoot整合Web组件 -->
  2.  
    <dependency>
  3.  
    <groupId>org.springframework.boot</groupId>
  4.  
    <artifactId>spring-boot-starter-web</artifactId>
  5.  
    </dependency>
  6.  
    <dependency>
  7.  
    <groupId>org.projectlombok</groupId>
  8.  
    <artifactId>lombok</artifactId>
  9.  
    </dependency>
  10.  
     
  11.  
    <!-- springboot整合freemarker -->
  12.  
    <dependency>
  13.  
    <groupId>org.springframework.boot</groupId>
  14.  
    <artifactId>spring-boot-starter-freemarker</artifactId>
  15.  
    </dependency>
  16.  
     
  17.  
    <!-->spring-boot 整合security -->
  18.  
    <dependency>
  19.  
    <groupId>org.springframework.boot</groupId>
  20.  
    <artifactId>spring-boot-starter-security</artifactId>
  21.  
    </dependency>
  22.  
    <!-- spring-cloud-starter-oauth2 -->
  23.  
    <dependency>
  24.  
    <groupId>org.springframework.cloud</groupId>
  25.  
    <artifactId>spring-cloud-starter-oauth2</artifactId>
  26.  
    </dependency>
学新通

二、授权中心案例代码

Oauth2相关配置:

  1.  
    /**
  2.  
    * @author Mr.Zheng
  3.  
    * @Program: parent
  4.  
    * @Description: 配置授权中心信息
  5.  
    * @date 2020-05-03 13:21
  6.  
    */
  7.  
    @Configuration
  8.  
    @EnableAuthorizationServer
  9.  
    public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
  10.  
    /**
  11.  
    * accessToken有效期 两小时
  12.  
    */
  13.  
    private int accessTokenValiditySeconds = 7200;
  14.  
     
  15.  
    /**
  16.  
    * refreshToken有效期 两小时
  17.  
    */
  18.  
    private int refreshTokenValiditySeconds = 7200;
  19.  
     
  20.  
    /**
  21.  
    * 添加商户信息
  22.  
    *
  23.  
    * @param clients 商户
  24.  
    * @throws Exception 异常
  25.  
    */
  26.  
    @Override
  27.  
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
  28.  
    clients.inMemory()
  29.  
    //商户id
  30.  
    .withClient("client_1")
  31.  
    //商户secret
  32.  
    .secret(passwordEncoder().encode("123456"))
  33.  
    //回调地址
  34.  
    .redirectUris("https://www.百度.com/")
  35.  
    /* OAuth2为我们提供了四种授权方式:
  36.  
    * 1、授权码模式(authorization code)用在客户端与服务端应用之间授权
  37.  
    * 2、简化模式(implicit)用在移动app或者web app(这些app是在用户的设备上的,如在手机上调起微信来进行认证授权)
  38.  
    * 3、密码模式(resource owner password credentials)应用直接都是受信任的(都是由一家公司开发的)
  39.  
    * 4、客户端模式(client credentials)用在应用API访问
  40.  
    */
  41.  
    .authorizedGrantTypes("password", "client_credentials", "refresh_token", "authorization_code")
  42.  
    //授权范围
  43.  
    .scopes("all")
  44.  
    //accessToken有效期
  45.  
    .accessTokenValiditySeconds(accessTokenValiditySeconds)
  46.  
    //refreshToken有效期
  47.  
    .refreshTokenValiditySeconds(refreshTokenValiditySeconds);
  48.  
    }
  49.  
     
  50.  
    /**
  51.  
    * 设置token类型
  52.  
    * @param endpoints
  53.  
    */
  54.  
    @Override
  55.  
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
  56.  
    endpoints.authenticationManager(authenticationManager())
  57.  
    .allowedTokenEndpointRequestMethods(HttpMethod.GET,HttpMethod.POST);
  58.  
    endpoints.authenticationManager(authenticationManager());
  59.  
    endpoints.userDetailsService(userDetailsService());
  60.  
    }
  61.  
     
  62.  
    @Override
  63.  
    public void configure(AuthorizationServerSecurityConfigurer oauthServer) {
  64.  
    // 允许表单认证
  65.  
    oauthServer.allowFormAuthenticationForClients();
  66.  
    // 允许check_token访问
  67.  
    oauthServer.checkTokenAccess("permitAll()");
  68.  
    }
  69.  
     
  70.  
    @Bean
  71.  
    AuthenticationManager authenticationManager() {
  72.  
    AuthenticationManager authenticationManager = new AuthenticationManager() {
  73.  
    @Override
  74.  
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
  75.  
    return daoAuhthenticationProvider().authenticate(authentication);
  76.  
    }
  77.  
     
  78.  
    };
  79.  
    return authenticationManager;
  80.  
    }
  81.  
     
  82.  
    @Bean
  83.  
    public AuthenticationProvider daoAuhthenticationProvider() {
  84.  
    DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider();
  85.  
    daoAuthenticationProvider.setUserDetailsService(userDetailsService());
  86.  
    daoAuthenticationProvider.setHideUserNotFoundExceptions(false);
  87.  
    daoAuthenticationProvider.setPasswordEncoder(passwordEncoder());
  88.  
    return daoAuthenticationProvider;
  89.  
    }
  90.  
     
  91.  
    /**
  92.  
    * 设置添加用户信息,正常应该从数据库中读取
  93.  
    *
  94.  
    * @return UserDetailsService
  95.  
    */
  96.  
    @Bean
  97.  
    UserDetailsService userDetailsService() {
  98.  
    InMemoryUserDetailsManager userDetailsService = new InMemoryUserDetailsManager();
  99.  
    userDetailsService.createUser(User.withUsername("user_1").password(passwordEncoder().encode("123456"))
  100.  
    .authorities("ROLE_USER").build());
  101.  
    userDetailsService.createUser(User.withUsername("user_2").password(passwordEncoder().encode("1234567"))
  102.  
    .authorities("ROLE_USER").build());
  103.  
    return userDetailsService;
  104.  
    }
  105.  
     
  106.  
    /**
  107.  
    * 设置加密方式
  108.  
    *
  109.  
    * @return PasswordEncoder
  110.  
    */
  111.  
    @Bean
  112.  
    PasswordEncoder passwordEncoder() {
  113.  
    return new BCryptPasswordEncoder();
  114.  
    }
  115.  
    }
学新通

Security相关配置:

  1.  
    /**
  2.  
    * @author Mr.Zheng
  3.  
    * @Program: parent
  4.  
    * @Description: 添加Security权限配置
  5.  
    * @date 2020-05-03 13:59
  6.  
    */
  7.  
    @Component
  8.  
    public class SecurityConfig extends WebSecurityConfigurerAdapter {
  9.  
     
  10.  
    /**
  11.  
    * 授权中心管理器
  12.  
    * @return AuthenticationManager
  13.  
    * @throws Exception 异常
  14.  
    */
  15.  
    @Bean
  16.  
    @Override
  17.  
    public AuthenticationManager authenticationManagerBean() throws Exception {
  18.  
    return super.authenticationManagerBean();
  19.  
    }
  20.  
     
  21.  
    @Bean
  22.  
    public PasswordEncoder passwordEncoder() {
  23.  
    return new BCryptPasswordEncoder();
  24.  
    }
  25.  
     
  26.  
    /**
  27.  
    * 拦截所有请求,使用httpBasic方式登陆
  28.  
    * @param http 请求
  29.  
    * @throws Exception 异常
  30.  
    */
  31.  
    @Override
  32.  
    protected void configure(HttpSecurity http) throws Exception {
  33.  
    http.authorizeRequests().antMatchers("/**").fullyAuthenticated().and().httpBasic();
  34.  
    }
  35.  
     
  36.  
    }
学新通

测试授权码模式:

访问http://localhost:8080/oauth/authorize?response_type=code&client_id=client_1&redirect_uri=https://www.百度.com/

学新通

学新通

使用该授权码获取accessToken:

访问http://localhost:8080/oauth/token?grant_type=authorization_code&client_id=client_1&client_secret=123456&code=EwaTib&redirect_uri=https://www.百度.com/&scope=all

学新通

测试密码模式获取accessToken:

学新通

三、受保护应用端案例代码

全局配置:

  1.  
    server:
  2.  
    port: 8081
  3.  
     
  4.  
    logging:
  5.  
    level:
  6.  
    org.springframework.security: DEBUG
  7.  
     
  8.  
    security:
  9.  
    oauth2:
  10.  
    resource:
  11.  
    ####从认证授权中心上验证token
  12.  
    tokenInfoUri: http://localhost:8080/oauth/check_token
  13.  
    preferTokenInfo: true
  14.  
    client:
  15.  
    accessTokenUri: http://localhost:8080/oauth/token
  16.  
    userAuthorizationUri: http://localhost:8080/oauth/authorize
  17.  
    ###appid
  18.  
    clientId: client_1
  19.  
    ###appSecret
  20.  
    clientSecret: 123456
学新通

资源拦截配置:

  1.  
    /**
  2.  
    * @author Mr.Zheng
  3.  
    * @Program: parent
  4.  
    * @Description: 资源拦截配置
  5.  
    * @date 2020-05-03 15:43
  6.  
    */
  7.  
    @Configuration
  8.  
    @EnableResourceServer
  9.  
    public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
  10.  
    @Override
  11.  
    public void configure(HttpSecurity http) throws Exception {
  12.  
    // 对 api/order 请求进行拦截
  13.  
    http.authorizeRequests().antMatchers("/api/test/**").authenticated();
  14.  
    }
  15.  
     
  16.  
    }
学新通

资源服务请求测试类:

  1.  
    /**
  2.  
    * @author Mr.Zheng
  3.  
    * @Program: parent
  4.  
    * @Description:
  5.  
    * @date 2020-05-03 15:44
  6.  
    */
  7.  
    @RestController
  8.  
    @RequestMapping("/api/test")
  9.  
    public class TestController {
  10.  
     
  11.  
    @RequestMapping("/add")
  12.  
    public String addOrder() {
  13.  
    return "add success!";
  14.  
    }
  15.  
     
学新通

 启动类开启Oauth2

  1.  
    /**
  2.  
    * @author Mr.Zheng
  3.  
    * @Program: parent
  4.  
    * @Description:
  5.  
    * @date 2020-05-03 15:42
  6.  
    */
  7.  
    @SpringBootApplication
  8.  
    @EnableOAuth2Sso
  9.  
    public class TestOauth2Server {
  10.  
    public static void main(String[] args) {
  11.  
    SpringApplication.run(TestOauth2Server.class,args);
  12.  
    }
  13.  
    }

四、授权中心和受保护应用端联合测试

1)、没授权时:

学新通

2)、授权时:

先获取token

学新通

再用token访问资源

学新通

五、修改授权中心改成动态数据库查询的方式

下载官方数据库脚本:spring-security-oauth/schema.sql at main · spring-attic/spring-security-oauth · GitHub

学新通

新增数据库依赖:

  1.  
    <!-- mysql -->
  2.  
    <dependency>
  3.  
    <groupId>mysql</groupId>
  4.  
    <artifactId>mysql-connector-java</artifactId>
  5.  
    </dependency>
  6.  
     
  7.  
    <dependency>
  8.  
    <groupId>org.springframework.boot</groupId>
  9.  
    <artifactId>spring-boot-starter-jdbc</artifactId>
  10.  
    </dependency>
  1.  
    spring:
  2.  
    datasource:
  3.  
    hikari:
  4.  
    connection-test-query: SELECT 1
  5.  
    minimum-idle: 1
  6.  
    maximum-pool-size: 5
  7.  
    pool-name: dbcp1
  8.  
    driver-class-name: com.mysql.jdbc.Driver
  9.  
    url: jdbc:mysql://localhost:3306/zhq_test_oauth?autoReconnect=true&useSSL=false
  10.  
    username: root
  11.  
    password: root

 修改Oauth2配置:

  1.  
    /**
  2.  
    * @author Mr.Zheng
  3.  
    * @Program: parent
  4.  
    * @Description: 配置授权中心信息
  5.  
    * @date 2020-05-03 13:21
  6.  
    */
  7.  
    @Configuration
  8.  
    @EnableAuthorizationServer
  9.  
    public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
  10.  
     
  11.  
     
  12.  
    @Autowired
  13.  
    @Qualifier("dataSource")
  14.  
    private DataSource dataSource;
  15.  
     
  16.  
     
  17.  
    /**
  18.  
    * accessToken有效期 两小时
  19.  
    */
  20.  
    private int accessTokenValiditySeconds = 7200;
  21.  
     
  22.  
    /**
  23.  
    * refreshToken有效期 两小时
  24.  
    */
  25.  
    private int refreshTokenValiditySeconds = 7200;
  26.  
     
  27.  
    @Bean
  28.  
    public TokenStore tokenStore() {
  29.  
    // return new InMemoryTokenStore(); //使用内存中的 token store
  30.  
    return new JdbcTokenStore(dataSource); /// 使用Jdbctoken store
  31.  
    }
  32.  
     
  33.  
     
  34.  
    /**
  35.  
    * 添加商户信息
  36.  
    *
  37.  
    * @param clients 商户
  38.  
    * @throws Exception 异常
  39.  
    */
  40.  
    @Override
  41.  
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
  42.  
    clients.jdbc(dataSource)
  43.  
    //测试首次运行可以指定测试数据,如果数据库中没有则不报错,如果有或者第二次运行会报错,因为数据库已经存在了,需要注释掉
  44.  
    .withClient("client_1")
  45.  
    //商户secret
  46.  
    .secret(passwordEncoder().encode("123456"))
  47.  
    //回调地址
  48.  
    .redirectUris("https://www.百度.com/")
  49.  
    /* OAuth2为我们提供了四种授权方式:
  50.  
    * 1、授权码模式(authorization code)用在客户端与服务端应用之间授权
  51.  
    * 2、简化模式(implicit)用在移动app或者web app(这些app是在用户的设备上的,如在手机上调起微信来进行认证授权)
  52.  
    * 3、密码模式(resource owner password credentials)应用直接都是受信任的(都是由一家公司开发的)
  53.  
    * 4、客户端模式(client credentials)用在应用API访问
  54.  
    */
  55.  
    .authorizedGrantTypes("password", "client_credentials", "refresh_token", "authorization_code")
  56.  
    //授权范围
  57.  
    .scopes("all")
  58.  
    //accessToken有效期
  59.  
    .accessTokenValiditySeconds(accessTokenValiditySeconds)
  60.  
    //refreshToken有效期
  61.  
    .refreshTokenValiditySeconds(refreshTokenValiditySeconds);
  62.  
    }
  63.  
     
  64.  
    /**
  65.  
    * 设置token类型
  66.  
    * @param endpoints
  67.  
    */
  68.  
    @Override
  69.  
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
  70.  
    endpoints.authenticationManager(authenticationManager())
  71.  
    .allowedTokenEndpointRequestMethods(HttpMethod.GET,HttpMethod.POST);
  72.  
    endpoints.authenticationManager(authenticationManager());
  73.  
    endpoints.userDetailsService(userDetailsService());
  74.  
    }
  75.  
     
  76.  
    @Override
  77.  
    public void configure(AuthorizationServerSecurityConfigurer oauthServer) {
  78.  
    // 允许表单认证
  79.  
    oauthServer.allowFormAuthenticationForClients();
  80.  
    // 允许check_token访问
  81.  
    oauthServer.checkTokenAccess("permitAll()");
  82.  
    }
  83.  
     
  84.  
    @Bean
  85.  
    AuthenticationManager authenticationManager() {
  86.  
    AuthenticationManager authenticationManager = new AuthenticationManager() {
  87.  
    @Override
  88.  
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
  89.  
    return daoAuhthenticationProvider().authenticate(authentication);
  90.  
    }
  91.  
     
  92.  
    };
  93.  
    return authenticationManager;
  94.  
    }
  95.  
     
  96.  
    @Bean
  97.  
    public AuthenticationProvider daoAuhthenticationProvider() {
  98.  
    DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider();
  99.  
    daoAuthenticationProvider.setUserDetailsService(userDetailsService());
  100.  
    daoAuthenticationProvider.setHideUserNotFoundExceptions(false);
  101.  
    daoAuthenticationProvider.setPasswordEncoder(passwordEncoder());
  102.  
    return daoAuthenticationProvider;
  103.  
    }
  104.  
     
  105.  
    /**
  106.  
    * 设置添加用户信息,正常应该从数据库中读取
  107.  
    *
  108.  
    * @return UserDetailsService
  109.  
    */
  110.  
    @Bean
  111.  
    UserDetailsService userDetailsService() {
  112.  
    InMemoryUserDetailsManager userDetailsService = new InMemoryUserDetailsManager();
  113.  
    userDetailsService.createUser(User.withUsername("user_1").password(passwordEncoder().encode("123456"))
  114.  
    .authorities("ROLE_USER").build());
  115.  
    userDetailsService.createUser(User.withUsername("user_2").password(passwordEncoder().encode("1234567"))
  116.  
    .authorities("ROLE_USER").build());
  117.  
    return userDetailsService;
  118.  
    }
  119.  
     
  120.  
    /**
  121.  
    * 设置加密方式
  122.  
    *
  123.  
    * @return PasswordEncoder
  124.  
    */
  125.  
    @Bean
  126.  
    PasswordEncoder passwordEncoder() {
  127.  
    return new BCryptPasswordEncoder();
  128.  
    }
  129.  
    }
学新通

测试运行:

学新通

检查数据库发现测试商户已经导入到数据库了

学新通

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhgbhage
系列文章
更多 icon
同类精品
更多 icon
继续加载