Commit 7b8121e1 authored by gzt's avatar gzt

构建客户端模式

parent 9eb4ba8a
HELP.md
target/
!.mvn/wrapper/maven-wrapper.jar
!**/src/main/**
!**/src/test/**
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
build/
### VS Code ###
.vscode/
......@@ -23,22 +23,27 @@
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.0</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- oauth -->
<dependency>
<groupId>org.springframework.security.oauth</groupId>
<artifactId>spring-security-oauth2</artifactId>
<version>2.2.1.RELEASE</version>
</dependency>
<!-- security -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-security</artifactId>
<version>2.1.3.RELEASE</version>
</dependency>
</dependencies>
<build>
......
......@@ -2,7 +2,10 @@ package com.yingxin.server.client;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
@EnableAuthorizationServer
@SpringBootApplication
public class ClientApplication {
......
package com.yingxin.server.client.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
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.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.InMemoryTokenStore;
/**
* description//TODO
* 授权服务器配置
* @author gaozhentao
* @version 1.0
* @date 2019/8/20
*/
@Configuration
public class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {
@Autowired
private AuthenticationManager authenticationManager;
@Autowired
UserDetailsService userDetailsService;
// 使用最基本的InMemoryTokenStore生成token
@Bean
public TokenStore memoryTokenStore() {
return new InMemoryTokenStore();
}
/**
* 配置客户端详情服务
* 客户端详细信息在这里进行初始化,你能够把客户端详情信息写死在这里或者是通过数据库来存储调取详情信息
* @param clients
* @throws Exception
*/
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory()
.withClient("client1")//用于标识用户ID
.authorizedGrantTypes("authorization_code","client_credentials","refresh_token")//授权方式
.scopes("test")//授权范围
.secret(PasswordEncoderFactories.createDelegatingPasswordEncoder().encode("123456"));//客户端安全码,secret密码配置从 Spring Security 5.0开始必须以 {bcrypt}+加密后的密码 这种格式填写;
}
/**
* 用来配置令牌端点(Token Endpoint)的安全约束.
* @param security
* @throws Exception
*/
@Override
public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
/* 配置token获取合验证时的策略 */
// security.tokenKeyAccess("permitAll()").checkTokenAccess("isAuthenticated()");
security.tokenKeyAccess("permitAll()").checkTokenAccess("isAuthenticated()").allowFormAuthenticationForClients();
}
/**
* 用来配置授权(authorization)以及令牌(token)的访问端点和令牌服务(token services)
* @param endpoints
* @throws Exception
*/
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
// 配置tokenStore,需要配置userDetailsService,否则refresh_token会报错
endpoints.authenticationManager(authenticationManager).tokenStore(memoryTokenStore()).userDetailsService(userDetailsService);
}
}
package com.yingxin.server.client.config;
import org.springframework.context.annotation.Bean;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
/**
* description//TODO
*
* @author gaozhentao
* @version 1.0
* @date 2019/8/20
*/
@EnableWebSecurity //开启权限验证
public class SecurityConfig extends WebSecurityConfigurerAdapter {
/**
* 配置这个bean会在做AuthorizationServerConfigurer配置的时候使用
* @return
* @throws Exception
*/
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
/**
* 配置用户
* 使用内存中的用户,实际项目中,一般使用的是数据库保存用户,具体的实现类可以使用JdbcDaoImpl或者JdbcUserDetailsManager
* @return
*/
@Bean
@Override
protected UserDetailsService userDetailsService() {
InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
manager.createUser(User.withUsername("admin").password(PasswordEncoderFactories.createDelegatingPasswordEncoder().encode("admin")).authorities("USER").build());
return manager;
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService());
}
}
package com.yingxin.server.client.dao;
/**
* description//TODO
*
* @author gaozhentao
* @version 1.0
* @date 2019/8/22
*/
public class UserDao {
}
package com.yingxin.server.client.entities;
/**
* description//TODO
*
* @author gaozhentao
* @version 1.0
* @date 2019/8/22
*/
public class User {
}
<?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 http://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.1.7.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.yingxin</groupId>
<artifactId>springcloudauthserver</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>SpringCloudAuthServer</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
<spring-cloud.version>Greenwich.SR2</spring-cloud.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-oauth2</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- <dependency>-->
<!-- <groupId>org.springframework.boot</groupId>-->
<!-- <artifactId>spring-boot-starter-data-redis</artifactId>-->
<!-- </dependency>-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</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>
......@@ -15,7 +15,10 @@
<description>resources project for Spring Boot</description>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<spring-cloud.version>Finchley.SR2</spring-cloud.version>
</properties>
<dependencies>
......@@ -29,8 +32,29 @@
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-oauth2</artifactId>
</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>
......
package com.yingxin.server.resources;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@EnableResourceServer
@RestController
@SpringBootApplication
public class ResourcesApplication {
private static final Logger log = LoggerFactory.getLogger(ResourcesApplication.class);
public static void main(String[] args) {
SpringApplication.run(ResourcesApplication.class, args);
}
@GetMapping("/user")
public Authentication getUser(Authentication authentication) {
log.info("resource: user {}", authentication);
return authentication;
}
}
auth-server-url: http://localhost:8080 # 授权服务地址
server:
port: 8088
security:
oauth2:
client:
client-id: client1
client-secret: 123456
scope: test
access-token-uri: ${auth-server-url}/oauth/token
user-authorization-uri: ${auth-server-url}/oauth/authorize
resource:
token-info-uri: ${auth-server-url}/oauth/check_token #检查令牌
package com.yingxin.springcloudauthserver;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
@EnableDiscoveryClient
@SpringBootApplication
public class SpringCloudAuthServerApplication {
public static void main(String[] args) {
SpringApplication.run(SpringCloudAuthServerApplication.class, args);
}
}
package com.yingxin.springcloudauthserver.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
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.token.store.InMemoryTokenStore;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;
// 定义授权服务器
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
// private final AuthenticationManager authenticationManager;
// private final RedisConnectionFactory redisConnectionFactory;
// public AuthorizationServerConfig(AuthenticationManager authenticationManager, RedisConnectionFactory redisConnectionFactory) {
// this.authenticationManager = authenticationManager;
// this.redisConnectionFactory = redisConnectionFactory;
// }
@Bean
public PasswordEncoder passwordEncoder() {
return PasswordEncoderFactories.createDelegatingPasswordEncoder();
}
// 定义令牌端点上的安全性约束
@Override
public void configure(AuthorizationServerSecurityConfigurer security) {
security.allowFormAuthenticationForClients()
.tokenKeyAccess("isAuthenticated()")
// .checkTokenAccess("permitAll()");
.checkTokenAccess("permitAll()");
}
// 定义客户端详细信息服务的配置器。可以初始化客户端详细信息,也可以只引用现有store
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
// 2.0版本以后默认取消了明文密码保存
String finalSecret = "{bcrypt}" + new BCryptPasswordEncoder().encode("123456");
/*
client模式,没有用户的概念,直接与认证服务器交互,用配置中的客户端信息去申请accessToken,
客户端有自己的client_id,client_secret对应于用户的username,password,而客户端也拥有自己的
authorities,当采取client模式认证时,对应的权限也就是客户端自己的authorities。
password模式,自己本身有一套用户体系,在认证时需要带上自己的用户名和密码,
以及客户端的client_id,client_secret。此时,accessToken所包含的权限是用户本身的权限,
而不是客户端的权限。
*/
clients.inMemory().withClient("client_1")// clientId:(必须)客户端id
.authorizedGrantTypes("client_credentials", "refresh_token")
.secret(finalSecret);
// .resourceIds("order") // resorceIds:这个客户端可以访问的资源id 不设置则授权所有资源
// .authorizedGrantTypes("client_credentials", "refresh_token") // 授权给客户端使用的权限类型 默认值为空
// .scopes("server") // 客户端的作用域。如果scope未定义或者为空(默认值),则客户端作用域不受限制
// .authorities("oauth2") // 授权给客户端的权限
// .secret(finalSecret); // (对于可信任的客户端是必须的)客户端的私密信息
}
// 定义授权和令牌端点以及令牌服务
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
endpoints
// .tokenStore(new RedisTokenStore(redisConnectionFactory))
.tokenStore(new InMemoryTokenStore())
// .authenticationManager(authenticationManager)
.allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST); // 默认只开放post请求
}
}
//package com.yingxin.springcloudauthserver.config;
//
//import org.springframework.context.annotation.Bean;
//import org.springframework.context.annotation.Configuration;
//import org.springframework.security.authentication.AuthenticationManager;
//import org.springframework.security.config.annotation.web.builders.HttpSecurity;
//import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
//import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
//import org.springframework.security.core.userdetails.User;
//import org.springframework.security.core.userdetails.UserDetailsService;
//import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
//import org.springframework.security.provisioning.InMemoryUserDetailsManager;
//
//@Configuration
//@EnableWebSecurity
//public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
//
// @Bean
// @Override
// public AuthenticationManager authenticationManagerBean() throws Exception {
// return super.authenticationManagerBean();
// }
//
// @Bean
// @Override
// public UserDetailsService userDetailsServiceBean() {
// BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
// String finalPassword = "{bcrypt}"+bCryptPasswordEncoder.encode("password1");
//
// InMemoryUserDetailsManager userDetailsManager = new InMemoryUserDetailsManager();
// userDetailsManager.createUser(User.withUsername("user1").password(finalPassword).authorities("USER").build());
// return userDetailsManager;
// }
//
//
// @Override
// protected void configure(HttpSecurity http) throws Exception {
// http.authorizeRequests()
//// .antMatchers("/oauth/token").authenticated()
// .anyRequest().permitAll();
// }
//}
eureka.client.service-url.defaultZone=http://localhost:8761/eureka/
spring.application.name=spring-cloud-oauth-auth-server
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment