关于 oauth2 jwt authentication.getPrincipal 获取的是用户名的问题

本贴最后更新于 1689 天前,其中的信息可能已经天翻地覆

第一种方案重写转换类(DefaultUserAuthenticationConverter)

public Map<String, ?> convertUserAuthentication(Authentication authentication) { Map<String, Object> map = new HashMap<>(1); //继承UserDetails的对象 Object o = authentication.getPrincipal(); UserLogin userInfo = (UserLogin) o; //储存 map.put("userInfo", userInfo); //权限存储 if (authentication.getAuthorities() != null && authentication.getAuthorities().size()>0) { map.put(AUTHORITIES, AuthorityUtils.authorityListToSet(authentication.getAuthorities())); } return map; } public Authentication extractAuthentication(Map<String, ?> map) { Authentication authentication = null; if (map.containsKey("userInfo")) { Object principal = map.get("userInfo"); Collection<? extends GrantedAuthority> authorities = this.getAuthorities(map); authentication = new UsernamePasswordAuthenticationToken(principal, "N/A", authorities); } return authentication; }

第二种方案 DefaultUserAuthenticationConverter 设置 customUserDetailsService

@Bean public JwtAccessTokenConverter jwtAccessTokenConverter(){ JwtAccessTokenConverter converter = new JwtAccessTokenConverter(); //设置用户信息转换器,默认getPrincipal是username DefaultAccessTokenConverter accessTokenConverter = (DefaultAccessTokenConverter)converter.getAccessTokenConverter(); DefaultUserAuthenticationConverter defaultUserAuthenticationConverter = new DefaultUserAuthenticationConverter(); defaultUserAuthenticationConverter.setUserDetailsService(customUserDetailsService); accessTokenConverter.setUserTokenConverter(defaultUserAuthenticationConverter); ClassPathResource resource = new ClassPathResource("publicKey.txt"); String publicKey = null; try { publicKey = IOUtils.toString(resource.getInputStream(), "UTF-8"); } catch (IOException e) { e.printStackTrace(); } converter.setVerifierKey(publicKey); return converter; }

个人总结

//由于oauth2在jwt仅支持用户名和权限,如需扩展处理参考一下 //转换成token的核心代码,在DefaultUserAuthenticationConverter里最终调用 org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter#convertAccessToken //解析token的核心代码,在DefaultUserAuthenticationConverter里最终调用 org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter#extractAuthentication //两者配合可以在jwt里面存放额外的用户信息(头像,卡号这些) //但是我不推荐这么做,使用用户名单独查询用户信息更为合适。
  • Spring

    Spring 是一个开源框架,是于 2003 年兴起的一个轻量级的 Java 开发框架,由 Rod Johnson 在其著作《Expert One-On-One J2EE Development and Design》中阐述的部分理念和原型衍生而来。它是为了解决企业应用开发的复杂性而创建的。框架的主要优势之一就是其分层架构,分层架构允许使用者选择使用哪一个组件,同时为 JavaEE 应用程序开发提供集成的框架。

    945 引用 • 1460 回帖 • 2 关注
  • OAuth

    OAuth 协议为用户资源的授权提供了一个安全的、开放而又简易的标准。与以往的授权方式不同之处是 oAuth 的授权不会使第三方触及到用户的帐号信息(如用户名与密码),即第三方无需使用用户的用户名与密码就可以申请获得该用户资源的授权,因此 oAuth 是安全的。oAuth 是 Open Authorization 的简写。

    36 引用 • 103 回帖 • 26 关注

相关帖子

欢迎来到这里!

我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。

注册 关于
请输入回帖内容 ...