SpringBoot集成SpringSecurity5和OAuth2 — 4、OAuth2的资源服务器

17 篇文章 0 订阅

相关代码:参考码云上的oauth2resource【仅供本人参考使用,不对外开发】

注意:OAuth2的客户端和资源服务器是不同的概念,OAuth2的客户端类似于第三方应用,它对接OAuth2服务器主要是使用OAuth2服务器端提供的客户信息【此处是OAuth2给用户分配的token】来登录客户端自己的系统而非资源服务器,后续用户访问的资源也是客户端自己存的用户资源,所以使用客户端的code来请求token会报错;而资源服务器则需要单独获取code后再获取token,然后才能请求资源服务器上的资源。【资源服务器和认证授权服务器同属一方。】

获取授权码:

http://localhost:8080/oauth/authorize?response_type=code&client_id=client&scope=read&redirect_uri=http://localhost:8090/callback

获取token令牌:

http://localhost:8080/oauth/token?grant_type=authorization_code&code=F4eRew&client_id=client&client_secret=secret&redirect_uri=http://localhost:8090/callback

一、项目环境配置

1.1 、JDK8

1.2、Spring Boot: 2.3.0.RELEASE

1.3、spring-cloud.version:Hoxton.SR5

二、准备工作

2.1 pom.xml

2.1.1 thymeleaf页面模板依赖

<!-- thymeleaf-->
<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

2.1.2 starter-web依赖

<!-- starter-web-->
<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-web</artifactId>
</dependency>

2.1.3 OAuth2依赖

<!--OAuth2-->
<dependency>
   <groupId>org.springframework.cloud</groupId>
   <artifactId>spring-cloud-starter-oauth2</artifactId>
</dependency>

2.1.4 数据库连接依赖

<!-- mybatis-->
<dependency>
   <groupId>org.mybatis.spring.boot</groupId>
   <artifactId>mybatis-spring-boot-starter</artifactId>
   <version>2.1.2</version>
</dependency>

<!-- mysql-->
<dependency>
   <groupId>mysql</groupId>
   <artifactId>mysql-connector-java</artifactId>
   <version>5.1.47</version>
   <scope>runtime</scope>
</dependency>

<!-- alibaba 数据连接池 -->
<dependency>
   <groupId>com.alibaba</groupId>
   <artifactId>druid</artifactId>
   <version>1.1.13</version>
</dependency>

2.1.5 lombok

<!--  lombok-->
<dependency>
   <groupId>org.projectlombok</groupId>
   <artifactId>lombok</artifactId>
   <optional>true</optional>
</dependency>

2.1.6 单元测试依赖

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-test</artifactId>
   <scope>test</scope>
   <exclusions>
      <exclusion>
         <groupId>org.junit.vintage</groupId>
         <artifactId>junit-vintage-engine</artifactId>
      </exclusion>
   </exclusions>
</dependency>

2.1.7 完整的pom.xml文件



<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.3.0.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>

	<groupId>cn.iotspider</groupId>
	<artifactId>oauth2resource</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>oauth2resource</name>

	<description>Demo project for Spring Boot</description>

	<properties>
		<java.version>1.8</java.version>
		<spring-cloud.version>Hoxton.SR5</spring-cloud.version>
	</properties>

	<dependencies>

		<!--  thymeleaf -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-thymeleaf</artifactId>
		</dependency>

		<!--  starter-web -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<!-- oauth2 -->
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-oauth2</artifactId>
		</dependency>

		<!-- mybatis-->
		<dependency>
			<groupId>org.mybatis.spring.boot</groupId>
			<artifactId>mybatis-spring-boot-starter</artifactId>
			<version>2.1.2</version>
		</dependency>

		<!-- mysql-->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.47</version>
			<scope>runtime</scope>
		</dependency>

		<!-- alibaba 数据连接池 -->
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>druid</artifactId>
			<version>1.1.13</version>
		</dependency>

		<!--  lombok-->
		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<optional>true</optional>
		</dependency>

		<!-- 单元测试-->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
			<exclusions>
				<exclusion>
					<groupId>org.junit.vintage</groupId>
					<artifactId>junit-vintage-engine</artifactId>
				</exclusion>
			</exclusions>
		</dependency>

	</dependencies>

	<dependencyManagement>
		<dependencies>
			<dependency>
				<groupId>org.springframework.cloud</groupId>
				<artifactId>spring-cloud-dependencies</artifactId>
				<version>${spring-cloud.version}</version>
				<type>pom</type>
				<scope>import</scope>
			</dependency>
		</dependencies>
	</dependencyManagement>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>

2.2 application.propeties


spring.application.name=oauth2-resource
server.port=8090

mybatis.mapper-locations=classpath:mapper/*/*.xml
#将扫描到的mapper.xml显示在控制台
mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl

spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/oauth2jdbc?useUnicode=true&characterEncoding=utf8&useSSL=false&useTimezone=true&serverTimezone=GMT%2B8
spring.datasource.username=root
spring.datasource.password=root

spring.thymeleaf.prefix = classpath:/templates/
#spring.thymeleaf.suffix = .html
spring.thymeleaf.encoding = UTF-8
spring.thymeleaf.servlet.content-type=text/html
spring.thymeleaf.cache = false


#资源客户端配置
security.oauth2.client.client-id=client
security.oauth2.client.client-secret=secret
security.oauth2.resource.id=resource
#校验token的路径
security.oauth2.resource.token-info-uri=http://localhost:8080/oauth/check_token

三、代码:

3.1 ResourceServerConfig加入@EnableResourceServer注解


package cn.iotspider.oauth2resource.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;

@Configuration
@EnableResourceServer
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true, jsr250Enabled = true)
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {


    /**
     * 配置资源服务器
     *
     * @param http
     * @throws Exception
     */
    @Override
    public void configure(HttpSecurity http) throws Exception {
        // 验证所有请求
        http.authorizeRequests()
                .anyRequest()
                .authenticated();

    }

}

3.2 ResourceController

package cn.iotspider.oauth2resource.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


@RestController
public class ResourceController {

    @RequestMapping("resource")
    public String resource() {
        return "ResourceServer Module";
    }

}

本项目只是为了用于练习搭建OAuth2的资源服务器,所以就没有加入对数据库的操作。至此,OAuth2的资源服务器就搭建完成了。

四、测试

4.1 在浏览器端输入:http://localhost:8090/resource

上图说明在访问时没有被授权,所以没有权限请求资源,需要在请求中加入OAuth2认证服务器生成的token才行。

4.2使用PostMan测试:

按下图设置,然后再请求资源就能请求成功了

完结!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
非常感谢您的提问,以下是一个简单的 Spring Boot 集成 Spring Security OAuth2 的代码示例: @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private UserDetailsService userDetailsService; @Autowired private DataSource dataSource; @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/login**", "/error**").permitAll() .anyRequest().authenticated() .and() .formLogin() .loginPage("/login") .defaultSuccessUrl("/home") .permitAll() .and() .logout() .permitAll(); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth .jdbcAuthentication() .dataSource(dataSource) .usersByUsernameQuery("SELECT username, password, enabled FROM users WHERE username = ?") .authoritiesByUsernameQuery("SELECT username, authority FROM authorities WHERE username = ?"); } @Bean public TokenStore tokenStore() { return new JdbcTokenStore(dataSource); } @Bean public ClientDetailsService clientDetailsService() { JdbcClientDetailsService clientDetailsService = new JdbcClientDetailsService(dataSource); clientDetailsService.setPasswordEncoder(passwordEncoder()); return clientDetailsService; } @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } @Override @Bean public AuthenticationManager authenticationManagerBean() throws Exception { return super.authenticationManagerBean(); } @Override protected void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception { endpoints .tokenStore(tokenStore()) .authenticationManager(authenticationManagerBean()) .userDetailsService(userDetailsService); } @Override public void configure(ClientDetailsServiceConfigurer clients) throws Exception { clients .withClient("client") .secret(passwordEncoder().encode("secret")) .authorizedGrantTypes("password", "refresh_token") .scopes("read", "write") .accessTokenValiditySeconds(3600) .refreshTokenValiditySeconds(86400); } } 请注意,这只是一个简单的示例,您需要根据您的实际需求进行修改和扩展。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值