Spring Cloud集成OAuth2

Spring Cloud集成OAuth2

什么是OAuth2

OAuth2 是一个授权框架,或称授权标准,它可以使第三方应用程序或客户端获得对HTTP服务上(例如 Google,GitHub )用户帐户信息的有限访问权限。OAuth 2 通过将用户身份验证委派给托管用户帐户的服务以及授权客户端访问用户帐户进行工作

具体介绍请参考大牛文章:阮一峰的《理解OAuth 2.0》

OAuth2能做什么

OAuth2 允许用户提供一个令牌,而不是用户名和密码来访问他们存放在特定服务提供者的数据。每一个令牌授权一个特定的网站(例如,视频编辑网站)在特定的时段(例如,接下来的2小时内)内访问特定的资源(例如仅仅是某一相册中的视频)。这样,OAuth允许用户授权第三方网站访问他们存储在另外的服务提供者上的信息,而不需要分享他们的访问许可或他们数据的所有内容

举个栗子:比如我们常用的微信公众号,当我们第一次打开公众号中网页的时候会弹出是否允许授权,当我们点击授权的时候,公众号网站就能获取到我们的头像和昵称等信息。这个过程就是通过OAuth2 来实现的

怎么去使用OAuth2

OAuth2是一套协议,我们可以根据协议来自己编写程序来实现OAuth2的功能,当然我们也可以通过一些框架来实现。由于我们的技术栈是Spring Cloud,那我们就开看看Spring Cloud怎么集成OAuth2。

Spring Cloud集成OAuth2

引入POM依赖

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-oauth2</artifactId>
        </dependency>

编写登录服务

因为授权是用户的授权,所以必须有用户登录才能授权,这里我们使用spring security来实现登录功能

建表语句

CREATE TABLE `ts_users` (
  `user_id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '用户ID',
  `user_name` varchar(50) NOT NULL COMMENT '用户名',
  `user_pwd` varchar(100) NOT NULL COMMENT '用户密码',
  PRIMARY KEY (`user_id`) USING BTREE,
  UNIQUE KEY `idx_user_name` (`user_name`) USING BTREE,
  KEY `idx_user_id` (`user_id`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 ROW_FORMAT=DYNAMIC COMMENT='用户信息表';

Security配置:SecurityConfig

package com.walle.gatewayserver.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
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.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * @author zhangjiapeng
 * @Package com.walle.gatewayserver.config
 * @Description: ${todo}
 * @date 2019/1/10 16:05
 */
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    // 用户验证服务
    @Autowired
    @Qualifier("userDetailServiceImpl")
    private UserDetailsService userDetailsService;

    // 加密方式 security2.0以后 密码无法明文保存,必须要经过加密
    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
    }

    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/hello");
    }


    // 配置拦截规则
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .anyRequest().authenticated()
                .and().formLogin()
                .and().csrf().disable()
                .httpBasic();
    }
}

登录实现:UserDetailServiceImpl

package com.walle.gatewayserver.service.impl;

import com.walle.common.entity.UserInfo;
import com.walle.gatewayserver.dao.UserInfoDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
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.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author zhangjiapeng
 * @Package com.walle.gatewayserver.service.impl
 * @Description: ${todo}
 * @date 2019/1/10 15:54
 */
@Service
public class UserDetailServiceImpl implements UserDetailsService {


    @Autowired
    private UserInfoDao userInfoDao;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        // 根据用户名查找用户
        UserInfo userInfo = userInfoDao.getByUserName(username);
        if(userInfo == null){
            throw  new  UsernameNotFoundException("用户不存在");
        }
        // 权限
        GrantedAuthority authority = new SimpleGrantedAuthority("admin");
        List<GrantedAuthority> authorities = new ArrayList<>(1);
        authorities.add(authority);

        UserDetails userDetails = new User(userInfo.getUsername(),passwordEncoder.encode(userInfo.getPassword()),authorities);
        // 返回用户信息,注意加密
        return userDetails;
    }
}

暴露接口,这里有两个接口,一个开放给web,一个开放给android

@RestController
@Slf4j
public class UserInfoController {

    @GetMapping("/user/web")
    public String web(){
        return  "hello web";
    }

    @GetMapping("/user/android")
    public String android(){
        return  "hello android";
    }
}

启动服务:访问http://localhost:9001/user/web,然后会看到登录界面

1547452036997.png

输入账号密码后看到

1547452089041.png

访问http://localhost:9001/user/android

1547452126286.png

这时候我们的登录用户可以访问到所有的资源,但是我们想让web登录的用户只能看到web,android的用户只能看到android。我们通过OAuth2来实现这个功能

编写授权服务

package com.walle.gatewayserver.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.userdetails.UserDetailsService;
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.client.InMemoryClientDetailsService;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.store.InMemoryTokenStore;

import java.util.concurrent.TimeUnit;

/**
 * @author zhangjiapeng
 * @Package com.walle.gatewayserver.config
 * @Description: ${todo}
 * @date 2019/1/10 16:39
 */

@Configuration
@EnableAuthorizationServer
public class AuthorizationConfig extends AuthorizationServerConfigurerAdapter {

    @Autowired
    @Qualifier("userDetailServiceImpl")
    private UserDetailsService userDetailsService;

    @Autowired
    private PasswordEncoder passwordEncoder;


    @Autowired
    private AuthenticationManager authenticationManager;

    @Bean
    public InMemoryTokenStore tokenStore(){
        return new InMemoryTokenStore();
    }


    @Bean
    public InMemoryClientDetailsService clientDetails() {
        return new InMemoryClientDetailsService();
    }

    // 配置token
    @Bean
    @Primary
    public DefaultTokenServices tokenService(){
        DefaultTokenServices tokenServices = new DefaultTokenServices();
        tokenServices.setTokenStore(tokenStore());
        tokenServices.setSupportRefreshToken(true);
        tokenServices.setClientDetailsService(clientDetails());
        tokenServices.setAccessTokenValiditySeconds((int) TimeUnit.DAYS.toSeconds(30));
        return tokenServices;
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.tokenStore(tokenStore())
                .userDetailsService(userDetailsService)
                .authenticationManager(authenticationManager)
                .tokenServices(tokenService());
    }

    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        security.allowFormAuthenticationForClients()
                .tokenKeyAccess("permitAll()")
                .checkTokenAccess("isAuthenticated()");
    }

    // 设置客户端信息
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
                .withClient("web")
                .scopes("web")
                .secret(passwordEncoder.encode("web"))
                .authorizedGrantTypes("authorization_code", "refresh_token")
                .redirectUris("http://www.baidu.com")
                .and().withClient("android")
                .scopes("android")
                .secret(passwordEncoder.encode("android"))
                .authorizedGrantTypes("authorization_code", "refresh_token")
                .redirectUris("http://www.baidu.com");
    }
}

这里是通过内存模式配置了两个客户端

客户端:web 密码: web scopes: web

客户端:android 密码: web scopes: android

配置资源服务

package com.walle.gatewayserver.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
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.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;

/**
 * @author zhangjiapeng
 * @Package com.walle.gatewayserver.config
 * @Description: ${todo}
 * @date 2019/1/10 16:29
 */
@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {


    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
                .and()
                    .requestMatchers().antMatchers("/user/**")
                .and()
                    .authorizeRequests()
                        .antMatchers("/user/web").access("#oauth2.hasScope('web')")
                                       .antMatchers("/user/android").access("#oauth2.hasScope('android')")
                        .anyRequest().permitAll();

    }
}

这里我们可以看到,我们通过配置资源服务拦截所有的/user/**的请求,然后请求/user/android必须有scope=android

这时候在登录访问下http://localhost:9001/user/android

1547452947310.png

这时候我们看到报错页面,需要验证才能访问。

获取授权

访问http://localhost:9001/oauth/authorize?client_id=android&response_type=code&redirect_uri=http://www.baidu.com

然后跳转到一个授权页面

1547453423313.png

是不是跟微信很像,这里说是否授权web,我们选择Approve ,然后页面跳转到了

https://www.baidu.com/?code=XOCtGr

我们拿到了一个code,然后我们通过code去获取access_token

POST访问http://localhost:9001/oauth/token?clientId=android&grant_type=authorization_code&code=A9bCN5&redirect_uri=http://www.baidu.com

1547453517990.png

这样我们就获得了access_token

这时候我们访问http://localhost:9001/user/android?access_token=59cf521c-026f-4df1-974e-3e4bfc42e432

看到


1547453588529.png

OK,android可以访问了,我们试试web能不能访问呢,访问http://localhost:9001/user/web?access_token=59cf521c-026f-4df1-974e-3e4bfc42e432

1547453650333.png

提示我们不合适的scope,这样我们就实现了不同客户端访问不同资源的权限控制

完!

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,015评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,262评论 1 292
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,727评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,986评论 0 205
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,363评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,610评论 1 219
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,871评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,582评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,297评论 1 242
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,551评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,053评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,385评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,035评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,079评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,841评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,648评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,550评论 2 270

推荐阅读更多精彩内容