帅气dee海绵宝宝
史上最简单的 Spring Cloud 教程
spring-security-4 (4)spring security 认证和授权原理
Spring Security Oauth2 认证(获取token/刷新token)流程(password模式)
spring-oauth-server 数据库表说明
史上最简单的 Spring Cloud 教程
纯洁的微笑
SPRING SECURITY 4官方文档中文翻译与源码解读
Intellij Idea,JDK1.8,Mysql,Redis,Spring Boot 2.1.3,mysql8.0.15,redis2.9
在项目开始阶段网关选用的是springcloud gateway,但是springcloud gateway不能依赖spring-boot-starter-web,它依赖的是spring-boot-starter-webflux,“间接“导致了网关不能继承WebSecurityConfigurerAdapter类,因此无法关闭CSRF(应该是我没有找到正确的方法),不得已把网关从gateway切换到了zuul。
**项目结构:**注册中心,网关,认证中心,业务服务
一,认证中心引入依赖
4.0.0
com.friday
education
0.0.1-SNAPSHOT
education-producer-oauth2
0.0.1-SNAPSHOT
education-producer-oauth2
this project for systerm user oauth2 server
1.8
org.springframework.boot
spring-boot-starter-web
org.mybatis.spring.boot
mybatis-spring-boot-starter
mysql
mysql-connector-java
runtime
com.alibaba
druid
org.springframework.cloud
spring-cloud-starter-oauth2
org.springframework.cloud
spring-cloud-starter-security
org.springframework.cloud
spring-cloud-starter-netflix-eureka-client
org.springframework.boot
spring-boot-starter-data-redis
org.springframework.session
spring-session-data-redis
redis.clients
jedis
org.springframework.boot
spring-boot-actuator-autoconfigure
org.springframework.boot
spring-boot-starter-actuator
com.friday
education-common
0.0.1-SNAPSHOT
org.springframework.boot
spring-boot-maven-plugin
二,认证中心配置
server.port= 1203
spring.application.name=producerOauth2
#---------------------eureka----------------------
eureka.client.service-url.defaultZone=http://127.0.0.1:7001/eureka/
eureka.instance.prefer-ip-address=true
eureka.instance.instance-id=${spring.cloud.client.ip-address}:${server.port}
#-------------------mysql,druid-------------------------
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/producer_user?useUnicode=true&characterEncoding=utf-8&useSSL=false&allowMultiQueries=true&serverTimezone=UTC
spring.datasource.username=root
[email protected]
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.druid.initialSize=5
spring.druid.maxActive=20
spring.druid.maxWait=60000
spring.druid.minIdle=5
spring.druid.timeBetweenEvictionRunsMillis=60000
spring.druid.minEvictableIdleTimeMillis=300000
spring.druid.validationQuery=SELECT 1 from DUAL
spring.druid.testWhileIdle=true
spring.druid.testOnBorrow=false
spring.druid.testOnReturn=false
spring.druid.poolPreparedStatements=false
spring.druid.maxPoolPreparedStatementPerConnectionSize=20
#配置扩展插件,常用的插件有=>stat:监控统计 log4j:日志 wall:防御sql注入
spring.druid.filters=stat,wall,slf4j
#通过connectProperties属性来打开mergeSql功能;慢SQL记录
spring.druid.connectionProperties='druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000'
#-------------------redis----------------------
spring.redis.database=0
spring.redis.host=127.0.0.1
spring.redis.port=6379
spring.redis.password=
spring.redis.jedis.pool.max-active=10000
spring.redis.jedis.pool.max-idle=50
spring.redis.jedis.pool.max-wait=-1
spring.redis.jedis.pool.min-idle=0
spring.redis.timeout=0
#------------------mybatis-------------------------
mybatis.type-aliases-package=com.friday.education.producer.oauth2.entity
mybatis.configuration.map-underscore-to-camel-case=true
mybatis.configuration.jdbc-type-for-null=NULL
mybatis.configuration.lazy-loading-enabled=true
mybatis.configuration.aggressive-lazy-loading=true
mybatis.configuration.cache-enabled=true
mybatis.configuration.call-setters-on-nulls=true
mybatis.mapper-locations=classpath:mybatis/*.xml
#不走认证的url集合
http.authorize.matchers=/**/css/**,/**/js/**,/**/plugin/**,/**/template/**,/**/img/**,/**/fonts/**,/**/cvr100u/**,/css/**,/js/**,/plugin/**,/template/**,/img/**,/fonts/**,/cvr100u/**
http.login.path=/login
三,启动类
package com.friday.education.producer.oauth2;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan("com.friday.education.producer.oauth2.dao")
public class EducationProducerOauth2Application {
public static void main(String[] args) {
SpringApplication.run(EducationProducerOauth2Application.class, args);
}
}
四,OAuth2认证服务器
package com.friday.education.producer.oauth2.config.oauth;
import com.friday.education.producer.oauth2.config.error.MssWebResponseExceptionTranslator;
import com.friday.education.producer.oauth2.service.MyUserDetailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.security.authentication.AuthenticationManager;
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.error.WebResponseExceptionTranslator;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.TokenStore;
import javax.sql.DataSource;
/**
* @ClassName OAuthServerConfig
* @Description TODO Oauth2认证服务器
* @Author Zeus
* @Date 2019/3/27 10:42
* @Version 1.0
**/
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
@Autowired
private AuthenticationManager authenticationManager;
@Autowired
private DataSource dataSource;
@Autowired
private RedisConnectionFactory connectionFactory;
@Autowired
private MyUserDetailService userDetailService;
/**
* @Description 使用TokenStore操作Token
**/
@Bean
public TokenStore tokenStore() {
return new RedisTokenStore(connectionFactory);
}
/**
*用来配置令牌端点(Token Endpoint)的安全约束.
**/
@Override
public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
security.tokenKeyAccess("permitAll()").checkTokenAccess("isAuthenticated()").allowFormAuthenticationForClients();;
}
/**
* 配置客户端详情服务
* 可以把客户端详情信息写死在这里或者是通过数据库来存储调取详情信息
**/
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
/*clients.inMemory() // 使用in-memory存储
.withClient("root") // client_id android
.scopes("read")
.secret("[email protected]") // client_secret android
.authorizedGrantTypes("password", "authorization_code", "refresh_token") // 该client允许的授权类型
.and()
.withClient("webapp") // client_id
.scopes("read")
//.secret("webapp") // client_secret
.authorizedGrantTypes("implicit")// 该client允许的授权类型
.and()
.withClient("browser")
.authorizedGrantTypes("refresh_token", "password")
.scopes("read");*/
// //客户端信息通过Redis去取得验证
// final RedisClientDetailsServiceBuilder builder = new RedisClientDetailsServiceBuilder();
// clients.setBuilder(builder);
//通过JDBC去查询数据库oauth_client_details表验证clientId信息
clients.jdbc(this.dataSource).clients(this.clientDetails());
// clients.withClientDetails(clientDetails());
}
@Bean
public ClientDetailsService clientDetails() {
return new JdbcClientDetailsService(dataSource);
}
@Bean
public WebResponseExceptionTranslator webResponseExceptionTranslator(){
return new MssWebResponseExceptionTranslator();
}
/**
* 用来配置授权(authorization)以及令牌(token)的访问端点和令牌服务(token services)。
**/
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.tokenStore(tokenStore())
.userDetailsService(userDetailService)
.authenticationManager(authenticationManager);
endpoints.tokenServices(defaultTokenServices());
//认证异常翻译
// endpoints.exceptionTranslator(webResponseExceptionTranslator());
}
/**
* 注意,自定义TokenServices的时候,需要设置@Primary,否则报错,
* 自定义的token
* 认证的token是存到redis里的
* @return
*/
@Primary
@Bean
public DefaultTokenServices defaultTokenServices(){
DefaultTokenServices tokenServices = new DefaultTokenServices();
tokenServices.setTokenStore(tokenStore());
tokenServices.setSupportRefreshToken(true);
//tokenServices.setClientDetailsService(clientDetails());
// token有效期自定义设置,默认12小时
tokenServices.setAccessTokenValiditySeconds(60*60*12);
// refresh_token默认30天
tokenServices.setRefreshTokenValiditySeconds(60 * 60 * 24 * 7);
return tokenServices;
}
/* *//**
* 密码匹配
**//*
@Bean
public PasswordEncoder passwordEncoder() {
return new MyBCryptPasswordEncoder();
}
*//**
* @Description //TODO
**//*
@Bean
public AuthorizationCodeServices authorizationCodeServices() {
return new JdbcAuthorizationCodeServices(dataSource);
}
@Bean
public ApprovalStore approvalStore() {
TokenApprovalStore store = new TokenApprovalStore();
store.setTokenStore(tokenStore());
return store;
}*/
}
五,访问权限设置
package com.friday.education.producer.oauth2.config.oauth;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
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 javax.servlet.http.HttpServletResponse;
/**
* @ClassName ResourceServerConfig
* @Description TODO 访问权限配置
* @Author Zeus
* @Date 2019/3/27 14:16
* @Version 1.0
**/
@Configuration
@EnableResourceServer
@Order(3)
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
@Override
public void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.exceptionHandling()
.authenticationEntryPoint((request, response, authException) -> response.sendError(HttpServletResponse.SC_UNAUTHORIZED))
.and()
.requestMatchers().antMatchers("/api/**")
.and()
.authorizeRequests()
.antMatchers("/api/**").authenticated()
.and()
.httpBasic();
}
}
六,security配置
package com.friday.education.producer.oauth2.config.security;
import com.friday.education.producer.oauth2.service.MyUserDetailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
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.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.password.PasswordEncoder;
/**
* 〈security配置〉
* 配置Spring Security
* ResourceServerConfig 是比SecurityConfig 的优先级低的
* @Author Zeus
* @Date 2019/3/27 18:13
* @Version 1.0
**/
@Configuration
@EnableWebSecurity
@Order(2)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private MyUserDetailService userDetailService;
@Bean
public PasswordEncoder passwordEncoder() {
return new MyBCryptPasswordEncoder();
// return new NoEncryptPasswordEncoder();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.requestMatchers().antMatchers("/oauth/**")
.and()
.authorizeRequests()
.antMatchers("/oauth/**").authenticated()
.and()
.csrf().disable();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailService).passwordEncoder(passwordEncoder());
}
/**
* 不定义没有password grant_type,密码模式需要AuthenticationManager支持
*
* @return
* @throws Exception
*/
@Override
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
}
七,重写TokenStore
package com.friday.education.producer.oauth2.config.oauth;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.security.oauth2.common.ExpiringOAuth2RefreshToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2RefreshToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.AuthenticationKeyGenerator;
import org.springframework.security.oauth2.provider.token.DefaultAuthenticationKeyGenerator;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.redis.JdkSerializationStrategy;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStoreSerializationStrategy;
/**
* 重写tokenStore .因为最新版中RedisTokenStore的set已经被弃用了,
* 所以我就只能自定义一个,代码和RedisTokenStore一样,
* 只是把所有conn.set(…)都换成conn..stringCommands().set(…),
*
*
*/
public class RedisTokenStore implements TokenStore {
private static final String ACCESS = "access:";
private static final String AUTH_TO_ACCESS = "auth_to_access:";
private static final String AUTH = "auth:";
private static final String REFRESH_AUTH = "refresh_auth:";
private static final String ACCESS_TO_REFRESH = "access_to_refresh:";
private static final String REFRESH = "refresh:";
private static final String REFRESH_TO_ACCESS = "refresh_to_access:";
private static final String CLIENT_ID_TO_ACCESS = "client_id_to_access:";
private static final String UNAME_TO_ACCESS = "uname_to_access:";
private final RedisConnectionFactory connectionFactory;
private AuthenticationKeyGenerator authenticationKeyGenerator = new DefaultAuthenticationKeyGenerator();
private RedisTokenStoreSerializationStrategy serializationStrategy = new JdkSerializationStrategy();
private String prefix = "";
public RedisTokenStore(RedisConnectionFactory connectionFactory) {
this.connectionFactory = connectionFactory;
}
public void setAuthenticationKeyGenerator(AuthenticationKeyGenerator authenticationKeyGenerator) {
this.authenticationKeyGenerator = authenticationKeyGenerator;
}
public void setSerializationStrategy(RedisTokenStoreSerializationStrategy serializationStrategy) {
this.serializationStrategy = serializationStrategy;
}
public void setPrefix(String prefix) {
this.prefix = prefix;
}
private RedisConnection getConnection() {
return this.connectionFactory.getConnection();
}
private byte[] serialize(Object object) {
return this.serializationStrategy.serialize(object);
}
private byte[] serializeKey(String object) {
return this.serialize(this.prefix + object);
}
private OAuth2AccessToken deserializeAccessToken(byte[] bytes) {
return (OAuth2AccessToken)this.serializationStrategy.deserialize(bytes, OAuth2AccessToken.class);
}
private OAuth2Authentication deserializeAuthentication(byte[] bytes) {
return (OAuth2Authentication)this.serializationStrategy.deserialize(bytes, OAuth2Authentication.class);
}
private OAuth2RefreshToken deserializeRefreshToken(byte[] bytes) {
return (OAuth2RefreshToken)this.serializationStrategy.deserialize(bytes, OAuth2RefreshToken.class);
}
private byte[] serialize(String string) {
return this.serializationStrategy.serialize(string);
}
private String deserializeString(byte[] bytes) {
return this.serializationStrategy.deserializeString(bytes);
}
@Override
public OAuth2AccessToken getAccessToken(OAuth2Authentication authentication) {
String key = this.authenticationKeyGenerator.extractKey(authentication);
byte[] serializedKey = this.serializeKey(AUTH_TO_ACCESS + key);
byte[] bytes = null;
RedisConnection conn = this.getConnection();
try {
bytes = conn.get(serializedKey);
} finally {
conn.close();
}
OAuth2AccessToken accessToken = this.deserializeAccessToken(bytes);
if (accessToken != null) {
OAuth2Authentication storedAuthentication = this.readAuthentication(accessToken.getValue());
if (storedAuthentication == null || !key.equals(this.authenticationKeyGenerator.extractKey(storedAuthentication))) {
this.storeAccessToken(accessToken, authentication);
}
}
return accessToken;
}
@Override
public OAuth2Authentication readAuthentication(OAuth2AccessToken token) {
return this.readAuthentication(token.getValue());
}
@Override
public OAuth2Authentication readAuthentication(String token) {
byte[] bytes = null;
RedisConnection conn = this.getConnection();
try {
bytes = conn.get(this.serializeKey("auth:" + token));
} finally {
conn.close();
}
OAuth2Authentication auth = this.deserializeAuthentication(bytes);
return auth;
}
@Override
public OAuth2Authentication readAuthenticationForRefreshToken(OAuth2RefreshToken token) {
return this.readAuthenticationForRefreshToken(token.getValue());
}
public OAuth2Authentication readAuthenticationForRefreshToken(String token) {
RedisConnection conn = getConnection();
try {
byte[] bytes = conn.get(serializeKey(REFRESH_AUTH + token));
OAuth2Authentication auth = deserializeAuthentication(bytes);
return auth;
} finally {
conn.close();
}
}
@Override
public void storeAccessToken(OAuth2AccessToken token, OAuth2Authentication authentication) {
byte[] serializedAccessToken = serialize(token);
byte[] serializedAuth = serialize(authentication);
byte[] accessKey = serializeKey(ACCESS + token.getValue());
byte[] authKey = serializeKey(AUTH + token.getValue());
byte[] authToAccessKey = serializeKey(AUTH_TO_ACCESS + authenticationKeyGenerator.extractKey(authentication));
byte[] approvalKey = serializeKey(UNAME_TO_ACCESS + getApprovalKey(authentication));
byte[] clientId = serializeKey(CLIENT_ID_TO_ACCESS + authentication.getOAuth2Request().getClientId());
RedisConnection conn = getConnection();
try {
conn.openPipeline();
conn.stringCommands().set(accessKey, serializedAccessToken);
conn.stringCommands().set(authKey, serializedAuth);
conn.stringCommands().set(authToAccessKey, serializedAccessToken);
if (!authentication.isClientOnly()) {
conn.rPush(approvalKey, serializedAccessToken);
}
conn.rPush(clientId, serializedAccessToken);
if (token.getExpiration() != null) {
int seconds = token.getExpiresIn();
conn.expire(accessKey, seconds);
conn.expire(authKey, seconds);
conn.expire(authToAccessKey, seconds);
conn.expire(clientId, seconds);
conn.expire(approvalKey, seconds);
}
OAuth2RefreshToken refreshToken = token.getRefreshToken();
if (refreshToken != null && refreshToken.getValue() != null) {
byte[] refresh = serialize(token.getRefreshToken().getValue());
byte[] auth = serialize(token.getValue());
byte[] refreshToAccessKey = serializeKey(REFRESH_TO_ACCESS + token.getRefreshToken().getValue());
conn.stringCommands().set(refreshToAccessKey, auth);
byte[] accessToRefreshKey = serializeKey(ACCESS_TO_REFRESH + token.getValue());
conn.stringCommands().set(accessToRefreshKey, refresh);
if (refreshToken instanceof ExpiringOAuth2RefreshToken) {
ExpiringOAuth2RefreshToken expiringRefreshToken = (ExpiringOAuth2RefreshToken) refreshToken;
Date expiration = expiringRefreshToken.getExpiration();
if (expiration != null) {
int seconds = Long.valueOf((expiration.getTime() - System.currentTimeMillis()) / 1000L)
.intValue();
conn.expire(refreshToAccessKey, seconds);
conn.expire(accessToRefreshKey, seconds);
}
}
}
conn.closePipeline();
} finally {
conn.close();
}
}
private static String getApprovalKey(OAuth2Authentication authentication) {
String userName = authentication.getUserAuthentication() == null ? "": authentication.getUserAuthentication().getName();
return getApprovalKey(authentication.getOAuth2Request().getClientId(), userName);
}
private static String getApprovalKey(String clientId, String userName) {
return clientId + (userName == null ? "" : ":" + userName);
}
@Override
public void removeAccessToken(OAuth2AccessToken accessToken) {
this.removeAccessToken(accessToken.getValue());
}
@Override
public OAuth2AccessToken readAccessToken(String tokenValue) {
byte[] key = serializeKey(ACCESS + tokenValue);
byte[] bytes = null;
RedisConnection conn = getConnection();
try {
bytes = conn.get(key);
} finally {
conn.close();
}
OAuth2AccessToken accessToken = deserializeAccessToken(bytes);
return accessToken;
}
public void removeAccessToken(String tokenValue) {
byte[] accessKey = serializeKey(ACCESS + tokenValue);
byte[] authKey = serializeKey(AUTH + tokenValue);
byte[] accessToRefreshKey = serializeKey(ACCESS_TO_REFRESH + tokenValue);
RedisConnection conn = getConnection();
try {
conn.openPipeline();
conn.get(accessKey);
conn.get(authKey);
conn.del(accessKey);
conn.del(accessToRefreshKey);
// Don't remove the refresh token - it's up to the caller to do that
conn.del(authKey);
List
八,MyUserDetailService实现UserDetailsService接口
package com.friday.education.producer.oauth2.service;
import com.friday.education.producer.oauth2.dao.UserDao;
import com.friday.education.producer.oauth2.entity.PUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import java.util.HashSet;
import java.util.Set;
/**
* @ClassName MyUserDetailService
* @Description TODO 自定义认证逻辑
* @Author Zeus
* @Date 2019/3/27 17:34
* @Version 1.0
**/
@Service//("userDetailService")
public class MyUserDetailService implements UserDetailsService {
@Autowired
private UserDao userDao;
@Override
public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
PUser user = userDao.findByMemberName(userName);
if (user == null) {
throw new UsernameNotFoundException(userName);
}
Set grantedAuthorities = new HashSet<>();
// 可用性 :true:可用 false:不可用
boolean enabled = true;
// 过期性 :true:没过期 false:过期
boolean accountNonExpired = true;
// 有效性 :true:凭证有效 false:凭证无效
boolean credentialsNonExpired = true;
// 锁定性 :true:未锁定 false:已锁定
boolean accountNonLocked = true;
/*for (Role role : member.getRoles()) {
//角色必须是ROLE_开头,可以在数据库中设置
GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(role.getRoleName());
grantedAuthorities.add(grantedAuthority);
//获取权限
for (Permission permission : role.getPermissions()) {
GrantedAuthority authority = new SimpleGrantedAuthority(permission.getUri());
grantedAuthorities.add(authority);
}
}*/
User us = new User(user.getUserName(), user.getPassword(),
enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, grantedAuthorities);
return us;
}
}
九,dao,entity,controller
package com.friday.education.producer.oauth2.dao;
import com.friday.education.producer.oauth2.entity.PUser;
public interface UserDao {
PUser findByMemberName(String userName);
}
package com.friday.education.producer.oauth2.entity;
import com.friday.education.common.baseentity.BaseEntity;
import lombok.Data;
import java.util.Date;
/**
* @ClassName PUser
* @Description TODO
* @Author Zeus
* @Date 2019/3/21 15:00
* @Version 1.0
**/
@Data
public class PUser extends BaseEntity {
private String userId;
private String loginCode;
private String userName;
private String password;
private String email;
private String mobile;
private String phone;
private int status;
private String createBy;
private Date createDate;
private String updateBy;
private Date updateDate;
private String remarks;
}
package com.friday.education.producer.oauth2.controller;
import com.friday.education.common.basecontroller.BaseController;
import com.friday.education.common.baseentity.Result;
import com.friday.education.common.baseentity.ResultCode;
import com.friday.education.producer.oauth2.service.MyUserDetailService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.oauth2.provider.token.ConsumerTokenServices;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.security.Principal;
/**
* @ClassName LoginController
* @Description TODO 登陆、退出控制器
* @Author Zeus
* @Date 2019/3/21 15:22
* @Version 1.0
**/
@Slf4j
@RestController
@RequestMapping("/api")
public class LoginController extends BaseController {
@Autowired
private MyUserDetailService userDetailService;
@Autowired
private ConsumerTokenServices consumerTokenServices;
@GetMapping("/user")
public Principal user(Principal user) {
//获取当前用户信息
log.debug("user",user);
return user;
}
@DeleteMapping(value = "/exit")
public Result revokeToken(String access_token) {
//注销当前用户
Result result = new Result();
if (consumerTokenServices.revokeToken(access_token)) {
result.setCode(ResultCode.SUCCESS.getCode());
result.setMessage("注销成功");
} else {
result.setCode(ResultCode.FAILED.getCode());
result.setMessage("注销失败");
}
return result;
}
}
一,引入依赖
4.0.0
com.friday
education
0.0.1-SNAPSHOT
education-pnr
0.0.1-SNAPSHOT
education-pnr
this project for publish education resources (pnr)
1.8
org.springframework.boot
spring-boot-starter-web
org.springframework.cloud
spring-cloud-starter-netflix-eureka-client
org.springframework.cloud
spring-cloud-starter-oauth2
org.springframework.cloud
spring-cloud-starter-security
org.mybatis.spring.boot
mybatis-spring-boot-starter
mysql
mysql-connector-java
runtime
com.friday
education-common
0.0.1-SNAPSHOT
org.springframework.boot
spring-boot-maven-plugin
二,配置文件
server.port= 8002
spring.application.name=pnr
#-------------------------eureka-------------------------
eureka.client.service-url.defaultZone=http://127.0.0.1:7001/eureka/
eureka.instance.prefer-ip-address=true
eureka.instance.instance-id=${spring.cloud.client.ip-address}:${server.port}
#-------------------oauth2---------------------
security.oauth2.resource.id=pnr
security.oauth2.client.access-token-uri=http://localhost:1202/producerOauth2/oauth/token
security.oauth2.client.user-authorization-uri=http://localhost:1202/producerOauth2/oauth/authorize
security.oauth2.resource.user-info-uri=http://localhost:1202/producerOauth2/api/user
security.oauth2.resource.prefer-token-info=false
三,启动类
package com.friday.education.pnr;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
@SpringBootApplication(exclude= {DataSourceAutoConfiguration.class})
public class EducationPnrApplication {
public static void main(String[] args) {
SpringApplication.run(EducationPnrApplication.class, args);
}
}
四,继承ResourceServerConfigurerAdapter类
package com.friday.education.pnr.config;
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 javax.servlet.http.HttpServletResponse;
/**
* @ClassName ResourceServerConfig
* @Description TODO
* @Author Zeus
* @Date 2019/3/28 14:48
* @Version 1.0
**/
@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
@Override
public void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.exceptionHandling()
.authenticationEntryPoint((request, response, authException) -> response.sendError(HttpServletResponse.SC_UNAUTHORIZED))
.and()
.requestMatchers().antMatchers("/api/**")
.and()
.authorizeRequests()
.antMatchers("/api/**").authenticated()
.and()
.httpBasic();
}
}
一,引入依赖
4.0.0
com.friday
education
0.0.1-SNAPSHOT
education-eureka
0.0.1-SNAPSHOT
education-eureka
this project for eureka
1.8
Greenwich.SR1
org.springframework.boot
spring-boot-starter-web
org.springframework.cloud
spring-cloud-starter-netflix-eureka-server
org.springframework.cloud
spring-cloud-dependencies
${spring-cloud.version}
pom
import
org.springframework.boot
spring-boot-maven-plugin
二,配置
spring.application.name=education-eureka
server.port=7001
eureka.instance.hostname=127.0.0.1
eureka.client.register-with-eureka=false
eureka.client.fetch-registry=false
eureka.client.service-url.defaultZone=http://127.0.0.1:7001/education-eureka/
#eureka.server.enable-self-preservation = false
一,引入依赖
4.0.0
com.friday
education
0.0.1-SNAPSHOT
education-gateway
0.0.1-SNAPSHOT
education-gateway
this project for gateway server
1.8
Greenwich.SR1
org.springframework.boot
spring-boot-starter-web
org.springframework.cloud
spring-cloud-starter-netflix-zuul
org.springframework.cloud
spring-cloud-starter-netflix-eureka-client
org.springframework.cloud
spring-cloud-starter-netflix-ribbon
org.springframework.cloud
spring-cloud-starter-oauth2
org.springframework.boot
spring-boot-starter-actuator
org.springframework.cloud
spring-cloud-starter-security
org.springframework.cloud
spring-cloud-dependencies
${spring-cloud.version}
pom
import
org.springframework.boot
spring-boot-maven-plugin
二,配置服务
zuul:
server.port=1202
spring.application.name=gateway
#---------------------eureka---------------------
eureka.client.service-url.defaultZone=http://127.0.0.1:7001/eureka/
eureka.instance.prefer-ip-address=true
eureka.instance.instance-id=${spring.cloud.client.ip-address}:${server.port}
#-----------------------zuul----------------------
zuul.routes.producerOauth2-api.path=/producerOauth2/**
zuul.routes.producerOauth2-api.service-id=producerOauth2
zuul.routes.producerOauth2-api.sensitiveHeaders=*
zuul.routes.pnr-api.path=/pnr/**
zuul.routes.pnr-api.service-id=pnr
zuul.routes.pnr-api.sensitiveHeaders=*
zuul.retryable=false
zuul.ignored-services=*
zuul.ribbon.eager-load.enabled=true
zuul.host.connect-timeout-millis=3000
zuul.host.socket-timeout-millis=3000
zuul.add-proxy-headers=true
ribbon.eager-load.enabled=true
logging.level.org.springframework.http.server.reactive=debug
logging.level.org.springframework.web.reactive=debug
logging.level.reactor.ipc.netty=debug
#---------------------OAuth2---------------------
security.oauth2.client.client-id=gateway
security.oauth2.client.access-token-uri=http://localhost:${server.port}/producerOauth2/oauth/token
security.oauth2.client.user-authorization-uri=http://localhost:${server.port}/producerOauth2/oauth/authorize
security.oauth2.resource.user-info-uri=http://localhost:${server.port}/producerOauth2/api/user
#指定access token失效时长
security.oauth2.client.access-token-validity-seconds=30
security.oauth2.resource.prefer-token-info=false
gateway:
server.port=1202
spring.application.name=gateway
#---------------------eureka---------------------
eureka.client.service-url.defaultZone=http://127.0.0.1:7001/eureka/
eureka.instance.prefer-ip-address=true
eureka.instance.instance-id=${spring.cloud.client.ip-address}:${server.port}
#-----------------------gateway----------------------
spring.cloud.gateway.default-filters[0]=PrefixPath=/httpbin
spring.cloud.gateway.default-filters[1]=AddResponseHeader=X-Response-Default-Foo, Default-Bar
#开启服务注册和发现,如果此处设置为true,就不需要配置routes
spring.cloud.gateway.discovery.locator.enabled=true
#将请求路径上的服务名配置为小写
spring.cloud.gateway.discovery.locator.lowerCaseServiceId=true
spring.cloud.gateway.routes[0].id=pnr
#pnr服务的负载均衡地址
spring.cloud.gateway.routes[0].uri=lb://pnr
#以/pnr/开头的请求都会转发到uri为lb://PNR的地址上
spring.cloud.gateway.routes[0].predicates[0]=Path=/pnr/**
#转发之前将/pnr去掉
#spring.cloud.gateway.routes[0].filters[0]=StripPrefix=1
spring.cloud.gateway.routes[1].id=producerOauth2
spring.cloud.gateway.routes[1].uri=lb://PRODUCEROAUTH2
spring.cloud.gateway.routes[1].predicates[0]=Path=/producerOauth2/**
spring.cloud.gateway.routes[1].filters[0]=StripPrefix=1
spring.cloud.gateway.routes[2].id=163
spring.cloud.gateway.routes[2].uri=http://www.163.com/
spring.cloud.gateway.routes[2].predicates[0]=Path=/163/**
spring.cloud.gateway.routes[2].filters[0]=StripPrefix=1
ribbon.eager-load.enabled=true
logging.level.org.springframework.cloud.gateway=trace
logging.level.org.springframework.http.server.reactive=debug
logging.level.org.springframework.web.reactive=debug
logging.level.reactor.ipc.netty=debug
#---------------------OAuth2---------------------
security.oauth2.client.access-token-uri=http://localhost:${server.port}/producerOauth2/oauth/token
security.oauth2.client.user-authorization-uri=http://localhost:${server.port}/producerOauth2/oauth/authorize
security.oauth2.client.client-id=web
security.oauth2.resource.user-info-uri=http://localhost:${server.port}/producerOauth2/api/user
#指定access token失效时长
security.oauth2.client.access-token-validity-seconds=30
security.oauth2.resource.prefer-token-info=false
三,继承WebSecurityConfigurerAdapter类
package com.friday.education.gateway.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
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;
/**
* @ClassName SecurityConfig
* @Description TODO
* @Author Zeus
* @Date 2019/3/28 14:45
* @Version 1.0
**/
@Configuration
@EnableWebSecurity
@Order(99)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
}
}
1,获取认证:
http://192.168.29.6:1202/producerOauth2/oauth/[email protected]
2.获得用户
http://192.168.29.6:1202/producerOauth2/api/user?access_token=c76bdb56-afc1-4a51-b159-223e259df0b2
3,访问业务接口
http://192.168.29.6:1202/pnr/api/current?access_token=c76bdb56-afc1-4a51-b159-223e259df0b2
4.token刷新
http://192.168.29.6:1202/producerOauth2/oauth/token?grant_type=refresh_token&refresh_token=1e555199-c8dd-4504-b484-53d3185df2db
5,注销
http://192.168.29.6:1202/producerOauth2/api/exit?access_token=c76bdb56-afc1-4a51-b159-223e259df0b2
像传统配置方式一样,把不走认证的代码放到了网关中之后,不管怎么配置,调用子服务中需要走认证的接口都报403
代码如下:
@Value("${http.authorize.matchers}")
private String[] httpAuthorizeMatchers;
private String[] getHttpAuthorizeMatchers() {
List matchers = new ArrayList();
matchers.add(uaaServerServicePath);
matchers.add(securityOauth2SsoLoginPath);
if (httpAuthorizeMatchers != null) {
for (String httpAuthorizeMatcher : httpAuthorizeMatchers) {
matchers.add(httpAuthorizeMatcher);
}
}
return matchers.toArray(new String[matchers.size()]);
}
@Override
public void configure(HttpSecurity http) throws Exception {
// 不需要认证的路径
http.authorizeRequests().antMatchers(getHttpAuthorizeMatchers())
.permitAll().anyRequest().authenticated();
// 禁用csrf,csrf校验功能全部放到子系统
http.csrf().disable();
}
按照上面这种方式,代码始终没有调通,不得已,把不走认证的代码放到了子服务中,代码立马就正常了
package com.friday.wf.basicdata.config;
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 javax.servlet.http.HttpServletResponse;
/**
* @ClassName ResourceServerConfig
* @Description TODO
* @Author Zeus
* @Date 2019/3/28 14:48
* @Version 1.0
**/
@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
@Override
public void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.exceptionHandling()
.authenticationEntryPoint((request, response, authException) -> response.sendError(HttpServletResponse.SC_UNAUTHORIZED))
.and()
.requestMatchers().antMatchers("/**/**")
.and()
.authorizeRequests()
.antMatchers("/api/**").permitAll()
.anyRequest().authenticated()
.and()
.httpBasic();
}
}
在这个子服务中有两个controller,user和api,api不需要走认证,user需要,代码如下:
package com.friday.wf.customer.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.security.Principal;
/**
* @ClassName UserController
* @Description TODO
* @Author Zeus
* @Date 2019/3/28 14:50
* @Version 1.0
**/
@RestController
@RequestMapping("/api")
public class ApiController {
@GetMapping("hello")
// @PreAuthorize("hasAnyAuthority('hello')")
public String hello(){
return "hello";
}
@GetMapping("current")
public Principal user(Principal principal) {
return principal;
}
@GetMapping("query")
// @PreAuthorize("hasAnyAuthority('query')")
public String query() {
return "具有query权限";
}
}
package com.friday.wf.customer.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.security.Principal;
/**
* @ClassName UserController
* @Description TODO
* @Author Zeus
* @Date 2019/3/28 14:50
* @Version 1.0
**/
@RestController
@RequestMapping("/user")
public class UserController {
@GetMapping("hello")
// @PreAuthorize("hasAnyAuthority('hello')")
public String hello(){
return "hello";
}
@GetMapping("current")
public Principal user(Principal principal) {
return principal;
}
@GetMapping("query")
// @PreAuthorize("hasAnyAuthority('query')")
public String query() {
return "具有query权限";
}
}
调用接口如下:
备注:由于时间紧急,目前只贴了代码,后续会慢慢把每一块的解释说明补全,代码会上传到git上。
项目git地址