Spring Cloud整合SpringSecurity实现简单权限认证访问

本文介绍如何利用SpringCloud OAuth2搭建微服务鉴权系统,包括配置资源服务器、认证服务器及网关等组件,实现服务间的鉴权与调用。

一、需要准备的工程

cslcp-eureka

cslcp-gateway

cslcp-security

cslcp-1(服务1)

cslcp-2(服务2)

cslcp-s(中台)

1. 前端发送请求后端进行数据验证(token)整套流程
在这里插入图片描述
2.前台调用多个服务原理
在这里插入图片描述
3.前台调用单个服务原理
在这里插入图片描述

二、cslcp-1工程

工程目录结构

主要添加了 ResourceServerConfig类修改了yml配置新增了pom依赖!之前的工程代码可以参考: SpringCloud微服务–使用使用restTemplate实现服务间调用传参中的服务工程

在这里插入图片描述
主类

package com.zhisen.cslcp1;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
@SpringBootApplication
@EnableDiscoveryClient
public class Cslcp1Application {
	public static void main(String[] args) {
		SpringApplication.run(Cslcp1Application.class, args);
	}
}

APPConfig配置类

package com.zhisen.cslcp1.config;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
@Configuration
public class AppConfig {
	@Bean
	@LoadBalanced
	public RestTemplate restTemplate(){
		return new RestTemplate();
	}
}

ResourceServiceConfig资源服务器配置类

package com.zhisen.cslcp1.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.RemoteTokenServices;
@Configuration
@EnableResourceServer
// 本服务是一个资源服务器
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

	@Value("${security.oauth2.client.client-id}")
	private String clientId;

	@Value("${security.oauth2.client.client-secret}")
	private String secret;

	@Value("${security.oauth2.authorization.check-token-access}")
	private String checkTokenEndpointUrl;

	// 自己这台服务的授权模式
	@Override
	public void configure(HttpSecurity http) throws Exception {
		http.csrf().disable();
		http.authorizeRequests().antMatchers("/test/**").authenticated().antMatchers("/account/**")
				.hasAuthority("admin");
	}
	// 连接远程服务
	@Bean
	public RemoteTokenServices tokenService() {
		RemoteTokenServices tokenService = new RemoteTokenServices();
		tokenService.setClientId(clientId);
		tokenService.setClientSecret(secret);
		tokenService.setCheckTokenEndpointUrl(checkTokenEndpointUrl);
		return tokenService;
	}
	@Override
	public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
		resources.tokenServices(tokenService());
	}
}

接口类根据自己的业务决定

yml

server:
  port: 10002

spring:
  application:
    name: cslcp
  rabbitmq:
    host: 172.16.122.112
    port: 11223
    username: yaohegui
    password: 123456
    
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://172.16.122.112:3306/orders?serverTimezone=GMT%2B8&allowMultiQueries=true&characterEncoding=UTF-8
    username: root
    password: root
  #mvc:
    #static-path-pattern: "/static/**"

#mybatis:
  #mapper-locations: com/zhisen/cslcp/dao/*Mapper.xml
  #type-aliases-package: com.zhisen.cslcp.dao.entity
logging:
  level:
    com.zhisen.cslcp.dao: debug

eureka:
  instance:
    hostname: 172.16.122.38
    prefer-ip: false  #强制使用host指定的ip
    lease-renewal-interval-in-seconds: 4
    lease-expiration-duration-in-seconds: 12
  client:
    hostname: 172.16.122.38
    fetch-registry: true
    registry-fetch-interval-seconds: 8
    serviceUrl:
      defaultZone: http://172.16.122.38:10001/eureka/

security:
  oauth2:
    client:
      client-id: user-client
      client-secret: user-secret-8888
      user-authorization-uri: http://localhost:18889/oauth/authorize
      access-token-uri: http://localhost:18889/oauth/token
    resource:
      id: user-client
      user-info-uri: user-info
    authorization:
      check-token-access: http://localhost:18889/oauth/check_token

在这里插入图片描述
在这里插入图片描述
pom
引入权限依赖

<!-- 权限依赖 -->
<dependency>
	<groupId>org.springframework.cloud</groupId>
	<artifactId>spring-cloud-starter-oauth2</artifactId>
	<version>2.2.5.RELEASE</version>
</dependency>

全:

<?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.5.1</version>
		<relativePath /> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.zhisen</groupId>
	<artifactId>cslcp-1</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>cslcp-1</name>
	<description>Demo project for Spring Boot</description>
	<properties>
		<java.version>1.8</java.version>
		<spring-cloud.version>2020.0.3</spring-cloud.version>
	</properties>
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
		</dependency>
		<dependency>
			<groupId
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

么贺贵

你的鼓励将是我创作的最大动力

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

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

打赏作者

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

抵扣说明:

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

余额充值