spring security oauth2 jwt 示例

公司项目是基于dubbo和zookeeper在门户项目端提供接口统一鉴权的,一直没有接触过spring security。出于好奇一直想了解下spring security怎么使用以及oauth2和jwt的鉴权过程,这次学习过程中将spring security搭上oauth2和jwt做一个示例程序。

OAuth 2.0

OAuth 2.0是一套关于授权的开放标准,主要针对第三方应用认证授权场景,详细信息可参考RFC 6749
OAuth 2.0定义了四个角色:

  • resource owner:资源所有者,即用户本身
  • resource server:资源服务器,服务提供商存放用户应用资源的服务器
  • client:客户端,即第三方应用
  • authorization server:授权服务器,服务提供商专门处理认证授权的服务器

打个比方,我打开简书发现没有账号但又懒得注册,点击使用QQ账号登录,那么这里的就是resource owner简书clientQQ保存账号信息比如头像的服务器就是resource serverQQ用来处理登录授权的服务器就是authorization server,如果以上操作按照OAuth 2.0的标准,它的流程大致如下:

OAuth 2.0授权流程

其中关键就是授权码token的获取,对于token的获取OAuth 2.0定义了四种方式:

  • Authorization Code:授权码模式,例如微信上给第三方小程序授权
  • Implicit:简化模式,授权码模式的简化版本,嫌授权码模式麻烦时用
  • Resource Owner Password Credentials:资源所有者密码凭证模式,一般高信任的内部应用间使用
  • Client Credentials:客户端凭证模式,一般用于开放API调用

JWT

即JSON Web Token的缩写,json格式的token,包含三部分:

  • Header:头部,包含类型和签名算法名称
  • Payload:载荷,主要内容,包含需要传递的信息
  • Signature:签名,对头部和载荷哈希后的内容

使用JWT主要是服务器端不需要存储token,资源服务器也不需要访问授权服务器验证token,每次访问只需对应资源服务器验证token有效性,减少服务器开销。

Spring security

Spring security框架基于OAuth 2.0做了相关实现,我们只需要做相应的配置就能实现一个基于OAuth 2.0和JWT的授权服务。

引入相关依赖

这里是使用gradle做依赖管理

dependencies {
    compile group: 'org.springframework.boot', name: 'spring-boot-starter-web', version: '2.1.3.RELEASE'
    compile group: 'org.springframework.boot', name: 'spring-boot-starter-jdbc', version: '2.1.3.RELEASE'
    compile group: 'org.springframework.boot', name: 'spring-boot-starter-data-jpa', version: '2.1.3.RELEASE'
    compile group: 'org.springframework.cloud', name: 'spring-cloud-starter-security', version: '2.1.1.RELEASE'
    compile group: 'org.springframework.cloud', name: 'spring-cloud-starter-oauth2', version: '2.1.1.RELEASE'
    compile group: 'org.apache.commons', name: 'commons-lang3', version: '3.8.1'
    compile group: 'com.google.code.gson', name: 'gson', version: '2.8.5'
    compile group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version: '2.9.8'

    runtime group: 'com.alibaba', name: 'druid', version: '1.1.13'
    runtime group: 'mysql', name: 'mysql-connector-java', version: '5.1.47'
}

配置spring security

@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService authUserDetailsService;

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

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

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable().authorizeRequests().antMatchers("/oauth/**").permitAll();
    }

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

配置授权服务器

@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private TokenStore jwtTokenStore;

    @Autowired
    private JwtAccessTokenConverter jwtAccessTokenConverter;

    @Autowired
    @Qualifier("jwtTokenEnhancer")
    private TokenEnhancer jwtTokenEnhancer;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        //允许表单认证
        security.allowFormAuthenticationForClients();
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory().withClient("client_admin")
                .resourceIds("resource")
                .authorizedGrantTypes("password", "client_credentials", "refresh_token")
                .scopes("read")
                .authorities("admin")
                .secret(passwordEncoder.encode("123456"))
                .accessTokenValiditySeconds(3 * 60 * 60)
                .refreshTokenValiditySeconds(6 * 60 * 60);
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        TokenEnhancerChain enhancerChain = new TokenEnhancerChain();
        List<TokenEnhancer> enhancerList = new ArrayList<>();
        enhancerList.add(jwtTokenEnhancer);
        enhancerList.add(jwtAccessTokenConverter);
        enhancerChain.setTokenEnhancers(enhancerList);

        endpoints.authenticationManager(authenticationManager)
                .tokenStore(jwtTokenStore)
                .accessTokenConverter(jwtAccessTokenConverter)
                .tokenEnhancer(enhancerChain)
                .exceptionTranslator(loggingExceptionTranslator());
    }

    @Bean
    public WebResponseExceptionTranslator loggingExceptionTranslator() {
        return new DefaultWebResponseExceptionTranslator() {
            private Log log = LogFactory.getLog(getClass());

            @Override
            public ResponseEntity<OAuth2Exception> translate(Exception e) throws Exception {
                //异常堆栈信息输出
                log.error("异常堆栈信息", e);
                return super.translate(e);
            }
        };
    }
}

配置资源服务器

@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

    @Autowired
    private ResourceServerTokenServices resourceJwtTokenServices;

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) {
        //resource资源只允许基于令牌的身份验证
        resources.resourceId("resource").stateless(true);
        resources.tokenServices(resourceJwtTokenServices);
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
                // 由于我们希望在用户界面中访问受保护的资源,因此我们需要允许创建会话
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
                .and()
                .requestMatchers().anyRequest()
                .and()
                //启用匿名登录,不可访问受保护资源
                .anonymous()
                .and()
                .authorizeRequests()
                //配置protected访问控制,必须认证过后才可以访问
                .antMatchers("/protected/**").authenticated();
    }
}

JWT配置

@Configuration
public class JwtTokenConfig {

    private static KeyPair KEY_PAIR;

    //此处只有在授权服务器和资源服务器在一起的时候才能这样搞,实际使用RSA还是需要用JDK和openssl去生成证书
    static {
        try {
            KEY_PAIR = KeyPairGenerator.getInstance("RSA").generateKeyPair();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
    }


    @Autowired
    private SystemAccountDao systemAccountDao;

    @Bean
    public TokenStore jwtTokenStore() {
        return new JwtTokenStore(jwtAccessTokenConverter());
    }

    @Bean
    public JwtAccessTokenConverter jwtAccessTokenConverter() {
        JwtAccessTokenConverter accessTokenConverter = new JwtAccessTokenConverter();
        accessTokenConverter.setKeyPair(KEY_PAIR);
        return accessTokenConverter;
    }

    @Bean
    public ResourceServerTokenServices resourceJwtTokenServices() {
        final DefaultTokenServices defaultTokenServices = new DefaultTokenServices();
        // 使用自定义的Token转换器
        defaultTokenServices.setTokenEnhancer(jwtAccessTokenConverter());
        // 使用自定义的tokenStore
        defaultTokenServices.setTokenStore(jwtTokenStore());
        return defaultTokenServices;
    }

    /**
     * token信息扩展
     */
    @Bean
    public TokenEnhancer jwtTokenEnhancer() {
        return new TokenEnhancer() {
            @Override
            public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
                Authentication userAuthentication = authentication.getUserAuthentication();
                if (userAuthentication != null) {
                    String userName = userAuthentication.getName();
                    List<SystemAccount> list = systemAccountDao.findByAccount(userName);
                    if (list != null && !list.isEmpty()) {
                        SystemAccount account = list.get(0);
                        Map<String, Object> additionalInformation = new HashMap<>();
                        Map<String, String> map = new HashMap<>();
                        map.put("account", account.getAccount());
                        map.put("createTime", account.getCreateTime().toString());
                        map.put("state", String.valueOf(account.getState()));
                        additionalInformation.put("user", GsonUtil.toJson(map));
                        ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInformation);
                    }
                }
                return accessToken;
            }
        };
    }
}

配置UserService

@Component
public class AuthUserDetailsService implements UserDetailsService {

    @Autowired
    private SystemAccountDao systemAccountDao;

    @Autowired
    private SystemAccountRoleDao systemAccountRoleDao;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        List<SystemAccount> list = systemAccountDao.findByAccount(username);
        if (list != null && !list.isEmpty()) {
            SystemAccount account = list.get(0);
            List<SystemAccountRole> roleList = systemAccountRoleDao.findByAccountId(account.getId());
            Collection<SimpleGrantedAuthority> authorities = new HashSet<>();
            if (roleList != null && !roleList.isEmpty()) {
                for (SystemAccountRole accountRole : roleList) {
                    authorities.add(new SimpleGrantedAuthority(String.valueOf(accountRole.getRoleId())));
                }
            }
            return new User(username, account.getPassword(),
                    account.getState() == 1, true, true, true,
                    authorities);
        }
        return null;
    }
}

password模式访问示例

password模式访问

客户端模式访问示例

客户端模式访问

携带token访问受保护资源

携带token访问受保护资源

项目地址

示例项目代码可到我的Github上下载:https://github.com/DexterQY/authentication

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

推荐阅读更多精彩内容