spring cloud oauth2 nginx 单点登录
客户端:user-service、role-service
授权中心:使用nginx实现负载均衡调用
***********************
认证服务器
**********************
配置文件
spring:
application:
name: authorization-service
**********************
config 层
JwtTokenStoreConfig:jwt存储认证信息
@Configuration
public class JwtTokenStoreConfig {
@Bean
public JwtAccessTokenConverter initJwtAccessTokenConverter(){
JwtAccessTokenConverter jwtAccessTokenConverter=new JwtAccessTokenConverter();
jwtAccessTokenConverter.setSigningKey("sign123456");
return jwtAccessTokenConverter;
}
@Bean
public JwtTokenStore initJwtTokenStore(){
return new JwtTokenStore(initJwtAccessTokenConverter());
}
}
OAuth2ServerConfiguration:认证服务器配置
@Configuration
@EnableAuthorizationServer
public class OAuth2ServerConfiguration extends AuthorizationServerConfigurerAdapter {
@Resource
private BCryptPasswordEncoder passwordEncoder;
@Resource
private UserService userService;
@Resource
private JwtTokenStore jwtTokenStore;
@Resource
private JwtAccessTokenConverter jwtAccessTokenConverter;
@Override
public void configure(AuthorizationServerEndpointsConfigurer authorizationServerEndpointsConfigurer) throws Exception {
authorizationServerEndpointsConfigurer
.tokenStore(jwtTokenStore)
.accessTokenConverter(jwtAccessTokenConverter)
.userDetailsService(userService);
}
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory()
.withClient("user").secret(passwordEncoder.encode("123456"))
.authorizedGrantTypes("authorization_code","refresh_token")
.redirectUris("http://192.168.57.21:8080/user-service/login")
.accessTokenValiditySeconds(3000)
.refreshTokenValiditySeconds(3000*10)
.autoApprove(true).scopes("user")
.and()
.withClient("role").secret(passwordEncoder.encode("123456"))
.authorizedGrantTypes("authorization_code","refresh_token")
.redirectUris("http://192.168.57.22:8080/role-service/login")
.accessTokenValiditySeconds(3000)
.refreshTokenValiditySeconds(3000*10)
.autoApprove(true).scopes("role");
}
@Override
public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
security.allowFormAuthenticationForClients()
.tokenKeyAccess("permitAll()") //获取token
.checkTokenAccess("isAuthenticated()"); //验证token
}
}
WebSecurityConfig:安全配置
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Bean
public BCryptPasswordEncoder initPasswordEncoder(){
return new BCryptPasswordEncoder();
}
@Bean
@Override
protected AuthenticationManager authenticationManager() throws Exception {
return super.authenticationManager();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.formLogin().and().authorizeRequests()
.antMatchers("/**").permitAll();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("gtlx")
.password(initPasswordEncoder().encode("123456"))
.authorities("admin");
}
}
***********************
客户端1:user-service
**********************
配置文件
application.yml
spring:
application:
name: user-service
server:
servlet:
context-path: /user-service
security:
oauth2:
client:
client-id: user
client-secret: 123456
user-authorization-uri: http://192.168.57.23:80/oauth/authorize
access-token-uri: http://192.168.57.23:80/oauth/token
resource:
jwt:
key-uri: http://192.168.57.23:80/oauth/token_key
key-value: sign123456
**********************
config 层
WebSecurityConfig
@Configuration
@EnableOAuth2Sso
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.formLogin().and().authorizeRequests()
.antMatchers("/**").hasAuthority("admin");
}
}
**********************
controller 层
UserController
@RestController
public class UserController {
@RequestMapping("/get")
public String get(){
return "hello user";
}
}
***********************
客户端2:role-service
**********************
配置文件
application.yml
spring:
application:
name: role-service
server:
servlet:
context-path: /role-service
security:
oauth2:
client:
client-id: role
client-secret: 123456
user-authorization-uri: http://192.168.57.23:80/oauth/authorize
access-token-uri: http://192.168.57.23:80/oauth/token
resource:
jwt:
key-uri: http://192.168.57.23:80/oauth/token_key
key-value: sign123456
**********************
config 层
WebSecurityConfig
@Configuration
@EnableOAuth2Sso
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.formLogin().and().authorizeRequests()
.antMatchers("/**").hasAuthority("admin");
}
}
**********************
controller 层
RoleController
@RestController
public class RoleController {
@RequestMapping("/get")
public String get(){
return "hello role";
}
}
***********************
使用测试
**********************
nginx 配置文件
nginx.conf
user nginx;
worker_processes 1;
error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;
events {
worker_connections 1024;
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
access_log /var/log/nginx/access.log main;
sendfile on;
#tcp_nopush on;
keepalive_timeout 65;
#gzip on;
include /etc/nginx/conf.d/*.conf;
}
default.conf
server {
listen 80;
server_name localhost;
location / {
root /usr/share/nginx/html;
index index.html index.htm;
proxy_pass http://auth-service;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/html;
}
upstream auth-service {
server 192.168.57.24:8080;
}
**********************
创建容器
docker run -it -d --net fixed3 --ip 192.168.57.21 \
-v /usr/nginx/user-role/user-service.jar:/usr/local/app.jar \
--name user-service common
docker run -it -d --net fixed3 --ip 192.168.57.22 \
-v /usr/nginx/user-role/role-service.jar:/usr/local/app.jar \
--name role-service common
docker run -it -d --net fixed3 --ip 192.168.57.23 \
-v /usr/nginx/user-role/nginx.conf:/etc/nginx/nginx.conf \
-v /usr/nginx/user-role/default.conf:/etc/nginx/conf.d/default.conf --name nginx nginx
docker run -it -d --net fixed3 --ip 192.168.57.24 \
-v /usr/nginx/user-role/auth-service.jar:/usr/local/app.jar \
--name auth-service common
***********************
测试输出
192.168.57.21:8080/user-service/get
输入密码,认证通过后输出:hello-user
192.168.57.22:8080/role-service/get,直接输出:hello role