- 使用 Spring Initializr 创建 Spring Boot 应用程序
- 在Spring Boot中配置Cassandra
- 在 Spring Boot 上配置 Tomcat 连接池
- 将Camel消息路由到嵌入WildFly的Artemis上
DROP TABLE IF EXISTS `oauth_client_details`;
CREATE TABLE `oauth_client_details` (
`client_id` varchar(48) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
`resource_ids` varchar(256) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`client_secret` varchar(256) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`scope` varchar(256) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`authorized_grant_types` varchar(256) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`web_server_redirect_uri` varchar(256) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`authorities` varchar(256) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`access_token_validity` int(11) NULL DEFAULT NULL,
`refresh_token_validity` int(11) NULL DEFAULT NULL,
`additional_information` varchar(4096) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`autoapprove` varchar(256) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
PRIMARY KEY (`client_id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of oauth_client_details
-- ----------------------------
INSERT INTO `oauth_client_details` VALUES ('yl', 'res1', '$2a$10$O8G0X/sUPAA76MV7U3BwY.3Uo8/QMBcqK678Rwkoz.fowbce.CLtO', 'all', 'authorization_code,refresh_token,implicit,password,client_credentials', 'http://localhost:8082/01.html,http://localhost:8082/02.html', NULL, 7200, 7200, NULL, 'true');
SET FOREIGN_KEY_CHECKS = 1;
1.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.2.5.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.yl</groupId>
<artifactId>auth-server</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>auth-server</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>11</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.10</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-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-security</artifactId>
<version>2.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-oauth2</artifactId>
<version>2.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
2.application.properties
spring.datasource.url=jdbc:mysql://localhost:3306/demo?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.driver-class-name = com.mysql.cj.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=root
spring.main.allow-bean-definition-overriding=true
# redis的配置
spring.redis.host=192.168.244.138
spring.redis.port=6379
spring.redis.password=root123
spring.redis.database=0
3.token的配置
package com.yl.authserver.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.InMemoryTokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;
@Configuration
public class AccessTokenConfig {
// 服务端不需要保存jwt的字符串
@Bean
TokenStore tokenStore() {
return new JwtTokenStore(jwtAccessTokenConverter());
}
@Bean
JwtAccessTokenConverter jwtAccessTokenConverter() {
JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
converter.setSigningKey("tom");
return converter;
}
}
4.security的配置
package com.yl.authserver.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.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Bean
PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("admin")
.password(passwordEncoder().encode("123"))
.roles("admin")
.and()
.withUser("root")
.password(passwordEncoder().encode("123"))
.roles("root");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable().formLogin();
}
}
5.自定义token数据返回的配置
package com.yl.authserver.config;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.stereotype.Component;
import java.util.Map;
@Component
public class AdditionalInformation implements TokenEnhancer {
@Override
public OAuth2AccessToken enhance(OAuth2AccessToken oAuth2AccessToken, OAuth2Authentication oAuth2Authentication) {
Map<String, Object> map = oAuth2AccessToken.getAdditionalInformation();
map.put("msg","hello oauth2");
map.put("网站","www.baidu.com");
map.put("微信","66");
((DefaultOAuth2AccessToken)oAuth2AccessToken).setAdditionalInformation(map);
return oAuth2AccessToken;
}
}
6.授权服务器的配置
package com.yl.authserver.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.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.ClientDetailsService;
import org.springframework.security.oauth2.provider.client.JdbcClientDetailsService;
import org.springframework.security.oauth2.provider.code.AuthorizationCodeServices;
import org.springframework.security.oauth2.provider.code.InMemoryAuthorizationCodeServices;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.TokenEnhancerChain;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import javax.sql.DataSource;
import java.util.Arrays;
//配置授权服务器
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
@Autowired
TokenStore tokenStore;
// 客户端信息
// @Autowired
// ClientDetailsService clientDetailsService;
@Autowired
PasswordEncoder passwordEncoder;
@Autowired
JwtAccessTokenConverter jwtAccessTokenConverter;
@Autowired
AdditionalInformation additionalInformation;
@Autowired
AuthenticationManager authenticationManager;
@Autowired
DataSource dataSource;
@Bean
ClientDetailsService clientDetailsService() {
return new JdbcClientDetailsService(dataSource);
}
//配置Token服务
AuthorizationServerTokenServices authorizationServerTokenServices() {
DefaultTokenServices tokenServices = new DefaultTokenServices();
tokenServices.setClientDetailsService(clientDetailsService());
tokenServices.setSupportRefreshToken(true);
tokenServices.setAccessTokenValiditySeconds(60 * 60 * 2); //token有限期设置为2小时
tokenServices.setRefreshTokenValiditySeconds(60 * 60 * 24 * 7);
tokenServices.setTokenStore(tokenStore);
TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
tokenEnhancerChain.setTokenEnhancers(Arrays.asList(jwtAccessTokenConverter,additionalInformation));
tokenServices.setTokenEnhancer(tokenEnhancerChain);
return tokenServices;
}
//配置token
@Override
public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
security.checkTokenAccess("permitAll()")// /oauth/check_token 带时候会调用这个请求来校验token
.checkTokenAccess("isAuthenticated()")
.allowFormAuthenticationForClients();
}
//配置客户端的信息(客户端信息存于内存)
// @Override
// public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
// clients.inMemory()
// .withClient("yl") //客户端名
// .secret(passwordEncoder.encode("123")) //客户端密码
// .scopes("all")
// .resourceIds("res1") //资源id
// .authorizedGrantTypes("authorization_code","refresh_token","implicit","password","client_credentials")
// // authorization_code授权码模式,password密码模式,implicit简化模式,client_credentials客户端模式,可以设置同时支持多种模式
// .autoApprove(true) //自动授权
.redirectUris("http://localhost:8082/index.html"); //授权码模式界面
.redirectUris("http://localhost:8082/01.html");//简化模式界面
// .redirectUris("http://localhost:8082/02.html");//密码模式界面
// }
//配置客户端的信息(客户端信息存于数据库)
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.withClientDetails(clientDetailsService());
}
//配置端点信息(主要获取授权码,要先拿到授权码,然后再根据授权码去获取token)
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.authorizationCodeServices(authorizationCodeServices())
.authenticationManager(authenticationManager)
.tokenServices(authorizationServerTokenServices());
}
@Bean
AuthorizationCodeServices authorizationCodeServices() {
return new InMemoryAuthorizationCodeServices();
}
}
1.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.2.5.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.yl</groupId>
<artifactId>user-server</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>user-server</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>11</java.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-security</artifactId>
<version>2.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-oauth2</artifactId>
<version>2.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
2.application.properties
server.port=8081
3.contoller
package com.yl.userserver.controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@CrossOrigin(value = "*")
public class HelloController {
@GetMapping("/hello")
public String hello() {
return "hello";
}
@GetMapping("/admin")
public String admin() {
return "hello admin";
}
}
4.token的配置
package com.yl.userserver.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;
@Configuration
public class AccessTokenConfig {
// 服务端不需要保存jwt的字符串
@Bean
TokenStore tokenStore() {
return new JwtTokenStore(jwtAccessTokenConverter());
}
@Bean
JwtAccessTokenConverter jwtAccessTokenConverter() {
JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
converter.setSigningKey("tom");
return converter;
}
}
5.资源服务器的配置
package com.yl.userserver.config;
import org.springframework.beans.factory.annotation.Autowired;
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;
import org.springframework.security.oauth2.provider.token.TokenStore;
//配置资源服务器
@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
@Autowired
TokenStore tokenStore;
@Override
public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
resources.resourceId("res1")
.tokenStore(tokenStore)
.stateless(true);
}
@Override
public void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/admin/**")
.hasRole("admin")
.anyRequest().authenticated()
.and().cors();
}
}
1.启动redis
2.启动授权服务器和资源服务器
3.获取token
4.携带token访问资源服务器的hello接口
1. JWT 简介 JSON Web Token(JWT) 是一个开放标准(RFC 7519),它定义了一种紧凑的、自包含的方式,用于作为 JSON 对象在各方之间安全地传输信息。该信息可以被验证和信
关于JWT(json web token)的一些问题: 可以在手机上使用吗? 在我看来,它适用于移动设备,但它是否是一个很好的身份验证解决方案?如果不是,还有哪些其他解决方案可用于移动应用程序和服务器
我无法清楚地掌握 JWT 是如何工作的,尤其是。签名部分。 一旦客户端提交正确的用户名和密码,身份验证服务器就会创建一个 JWT token ,其中包含 header 、有效负载/声明和签名。 问题
我正在通过 jwt.io(在调试器部分)解码 JWT token 以查看标题、有效负载。令人惊讶的是,它还验证了,我可以看到它(jwt.io 调试器)也能够检索公钥。 所以我的问题是:JWT toke
我尝试使用 validate-jwt 策略限制使用 JWT token 对 REST API 的访问。以前从来没有这样做过。 这是我的入站策略(取自简单 token 验证here):
我们有一个微服务架构,使用 JWT 在服务之间进行身份验证。我希望轻松地从 JWT 中获取更多字段。目前实际上只有权限由 Spring Security 直接公开。 我们的边缘服务/API 网关创建以
我正在尝试在 .NET 中生成 JWT token 。起初,我尝试使用“System.IdentityModel.Tokens.Jwt”,但它在 token 验证期间引起了问题,所以我切换到“jose
我已经阅读了很多关于 stackOverflow 和 jwt 文档的问题。据我了解,现在我应该如何计算 token : header = { "alg": "HS256", "typ": "J
我想知道我可以设置的 JWT token 到期的最大值是多少。 谢谢! 最佳答案 没有关于过期时间的规定。它主要取决于使用 token 的上下文。 RFC7519 section 4 : The se
我在子域上托管了单独的身份验证应用程序和多个 spa 应用程序,我想将生成的 JWT token (当用户从身份验证应用程序登录时生成)从身份验证应用程序共享到子域下托管的其他应用程序。我怎样才能
据我所知,验证 JWT 签名是一个直接的过程。但是当我使用一些在线工具为我执行此操作时,它不匹配。如何在不使用 JWT 库的情况下手动验证 JWT 签名?我需要一种快速方法(使用可用的在线工具)来演示
我的 JSON 网络 token (JWT): eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6InU0T2ZORlBId0VCb3NIanRyYXVPYlY4
我是 JWT 的新手。我对 JWT 进行了一些研究,并了解到它的框架是“header.claims.signature”。 考虑一个简单的场景,如下所示: 客户通过身份验证 客户可能具有(一个或多个)
我需要知道的最大长度 JSON Web Token (JWT) 在规范中没有相关信息。难道,长度没有限制? 最佳答案 我也一直在努力寻找这个。 我想说 - 尝试确保它低于 7kb。 虽然 JWT 在规
我看到 JWT token 由 A-Z、a-Z、0-9 和特殊字符 - 和 _ 组成。我想知道 JWT token 中允许的字符列表? 最佳答案 来自JWT introduction :“输出是三个用
我正在使用 Jhipster 创建一个应用程序。为此,我想使用 Keycloak 身份验证服务器。但是,一旦我登录,就会收到以下消息:Statut : Internal Server Error (内
我正在使用 Jhipster 创建一个应用程序。为此,我想使用 Keycloak 身份验证服务器。但是,一旦我登录,就会收到以下消息:Statut : Internal Server Error (内
我在我的网站上使用 MEAN 堆栈,用户可以在其中将带有玩家信息的事件(2-4/事件)添加到购物车。有时他们会购买多个事件。我希望此信息不会受到用户操纵(如果他们使用控制台,则在结帐前更改信息),并且
一个 JSON Web token (JWT) 被分成三个 Base-64 编码的部分,这些部分由句点 (“.”) 连接起来。前两部分对 JSON 对象进行编码,第一部分是详细说明签名和散列算法的 h
我正在使用 django rest 框架 JWT 库 http://getblimp.github.io/django-rest-framework-jwt/ JWT token 过期有两个设置 JW
我是一名优秀的程序员,十分优秀!