当前位置: 移动技术网 > IT编程>开发语言>Java > 详解SpringCloud服务认证(JWT)

详解SpringCloud服务认证(JWT)

2019年07月19日  | 移动技术网IT编程  | 我要评论

欧陆经典女鞋,祸害新千年,绿鬣蜥怎么养

 - jwt

jwt(json web token), 是为了在网络应用环境间传递声明而执行的一种基于json的开放标准((rfc 7519).该token被设计为紧凑且安全的,特别适用于分布式站点的单点登录(sso)场景。jwt的声明一般被用来在身份提供者和服务提供者间传递被认证的用户身份信息,以便于从资源服务器获取资源,也可以增加一些额外的其它业务逻辑所必须的声明信息,该token也可直接被用于认证,也可被加密。

- jwt与其它的区别

通常情况下,把api直接暴露出去是风险很大的,不说别的,直接被机器攻击就喝一壶的。那么一般来说,对api要划分出一定的权限级别,然后做一个用户的鉴权,依据鉴权结果给予用户开放对应的api。目前,比较主流的方案有几种:

oauth

oauth(开放授权)是一个开放的授权标准,允许用户让第三方应用访问该用户在某一服务上存储的私密的资源(如照片,视频),而无需将用户名和密码提供给第三方应用。

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

cookie/session auth

cookie认证机制就是为一次请求认证在服务端创建一个session对象,同时在客户端的浏览器端创建了一个cookie对象;通过客户端带上来cookie对象来与服务器端的session对象匹配来实现状态管理的。默认的,当我们关闭浏览器的时候,cookie会被删除。但可以通过修改cookie 的expire time使cookie在一定时间内有效,基于session方式认证势必会对服务器造成一定的压力(内存存储),不易于扩展(需要处理分布式session),跨站请求伪造的攻击(csrf)

- jwt的优点

1.相比于session,它无需保存在服务器,不占用服务器内存开销。

2.无状态、可拓展性强:比如有3台机器(a、b、c)组成服务器集群,若session存在机器a上,session只能保存在其中一台服务器,此时你便不能访问机器b、c,因为b、c上没有存放该session,而使用token就能够验证用户请求合法性,并且我再加几台机器也没事,所以可拓展性好就是这个意思。

3.前后端分离,支持跨域访问。

- jwt的组成

{ "iss": "jwt builder", 
 "iat": 1416797419, 
 "exp": 1448333419, 
 "aud": "www.battcn.com", 
 "sub": "1837307557@qq.com", 
 "givenname": "levin", 
 "surname": "levin", 
 "email": "1837307557@qq.com", 
 "role": [ "admin", "member" ] 
}
  1.  iss: 该jwt的签发者,是否使用是可选的;
  2. sub: 该jwt所面向的用户,是否使用是可选的;
  3. aud: 接收该jwt的一方,是否使用是可选的;
  4. exp(expires): 什么时候过期,这里是一个unix时间戳,是否使用是可选的;
  5. iat(issued at): 在什么时候签发的(unix时间),是否使用是可选的;
  6. nbf (not before):如果当前时间在nbf里的时间之前,则token不被接受;一般都会留一些余地,比如几分钟;,是否使用是可选的;

一个jwt实际上就是一个字符串,它由三部分组成,头部、载荷、签名(上图依次排序)

jwt token生成器:

- 认证

- 登陆认证

  1. 客户端发送 post 请求到服务器,提交登录处理的controller层
  2. 调用认证服务进行用户名密码认证,如果认证通过,返回完整的用户信息及对应权限信息
  3. 利用 jjwt 对用户、权限信息、秘钥构建token
  4. 返回构建好的token

- 请求认证

  1. 客户端向服务器请求,服务端读取请求头信息(request.header)获取token
  2. 如果找到token信息,则根据配置文件中的签名加密秘钥,调用jjwt lib对token信息进行解密和解码;
  3. 完成解码并验证签名通过后,对token中的exp、nbf、aud等信息进行验证;
  4. 全部通过后,根据获取的用户的角色权限信息,进行对请求的资源的权限逻辑判断;
  5. 如果权限逻辑判断通过则通过response对象返回;否则则返回http 401;

无效token

有效token

- jwt的缺点

有优点就会有缺点,是否适用应该考虑清楚,而不是技术跟风

  1. token过大容易占用更多的空间
  2. token中不应该存储敏感信息
  3. jwt不是 session ,勿将token当session
  4. 无法作废已颁布的令牌,因为所有的认证信息都在jwt中,由于在服务端没有状态,即使你知道了某个jwt被盗取了,你也没有办法将其作废。在jwt过期之前(你绝对应该设置过期时间),你无能为力。
  5. 类似缓存,由于无法作废已颁布的令牌,在其过期前,你只能忍受”过期”的数据(自己放出去的token,含着泪也要用到底)。

- 代码(片段)

tokenproperties 与 application.yml资源的key映射,方便使用

@configuration
@configurationproperties(prefix = "battcn.security.token")
public class tokenproperties {
 /**
 * {@link com.battcn.security.model.token.token} token的过期时间
 */
 private integer expirationtime;

 /**
 * 发行人
 */
 private string issuer;

 /**
 * 使用的签名key {@link com.battcn.security.model.token.token}.
 */
 private string signingkey;

 /**
 * {@link com.battcn.security.model.token.token} 刷新过期时间
 */
 private integer refreshexptime;

 // get set ...
}

token生成的类

@component
public class tokenfactory {

 private final tokenproperties properties;

 @autowired
 public tokenfactory(tokenproperties properties) {
 this.properties = properties;
 }

 /**
 * 利用jjwt 生成 token
 * @param context
 * @return
 */
 public accesstoken createaccesstoken(usercontext context) {
 optional.ofnullable(context.getusername()).orelsethrow(()-> new illegalargumentexception("cannot create token without username"));
 optional.ofnullable(context.getauthorities()).orelsethrow(()-> new illegalargumentexception("user doesn't have any privileges"));
 claims claims = jwts.claims().setsubject(context.getusername());
 claims.put("scopes", context.getauthorities().stream().map(object::tostring).collect(tolist()));
 localdatetime currenttime = localdatetime.now();
 string token = jwts.builder()
  .setclaims(claims)
  .setissuer(properties.getissuer())
  .setissuedat(date.from(currenttime.atzone(zoneid.systemdefault()).toinstant()))
  .setexpiration(date.from(currenttime
  .plusminutes(properties.getexpirationtime())
  .atzone(zoneid.systemdefault()).toinstant()))
  .signwith(signaturealgorithm.hs512, properties.getsigningkey())
 .compact();
 return new accesstoken(token, claims);
 }

 /**
 * 生成 刷新 refreshtoken
 * @param usercontext
 * @return
 */
 public token createrefreshtoken(usercontext usercontext) {
 if (stringutils.isblank(usercontext.getusername())) {
  throw new illegalargumentexception("cannot create token without username");
 }
 localdatetime currenttime = localdatetime.now();
 claims claims = jwts.claims().setsubject(usercontext.getusername());
 claims.put("scopes", arrays.aslist(scopes.refresh_token.authority()));
 string token = jwts.builder()
  .setclaims(claims)
  .setissuer(properties.getissuer())
  .setid(uuid.randomuuid().tostring())
  .setissuedat(date.from(currenttime.atzone(zoneid.systemdefault()).toinstant()))
  .setexpiration(date.from(currenttime
  .plusminutes(properties.getrefreshexptime())
  .atzone(zoneid.systemdefault()).toinstant()))
  .signwith(signaturealgorithm.hs512, properties.getsigningkey())
 .compact();

 return new accesstoken(token, claims);
 }
}

配置文件,含token过期时间,秘钥,可自行扩展

battcn:
 security:
 token:
 expiration-time: 10 # 分钟 1440
 refresh-exp-time: 30 # 分钟 2880
 issuer: http://blog.battcn.com
 signing-key: battcn

websecurityconfig 是 spring security 关键配置,在securrty中基本上可以通过定义过滤器去实现我们想要的功能.

@configuration
@enablewebsecurity
public class websecurityconfig extends websecurityconfigureradapter {

 public static final string token_header_param = "x-authorization";
 public static final string form_based_login_entry_point = "/api/auth/login";
 public static final string token_based_auth_entry_point = "/api/**";
 public static final string manage_token_based_auth_entry_point = "/manage/**";
 public static final string token_refresh_entry_point = "/api/auth/token";

 @autowired private restauthenticationentrypoint authenticationentrypoint;
 @autowired private authenticationsuccesshandler successhandler;
 @autowired private authenticationfailurehandler failurehandler;
 @autowired private loginauthenticationprovider loginauthenticationprovider;
 @autowired private tokenauthenticationprovider tokenauthenticationprovider;

 @autowired private tokenextractor tokenextractor;

 @autowired private authenticationmanager authenticationmanager;

 protected loginprocessingfilter buildloginprocessingfilter() throws exception {
 loginprocessingfilter filter = new loginprocessingfilter(form_based_login_entry_point, successhandler, failurehandler);
 filter.setauthenticationmanager(this.authenticationmanager);
 return filter;
 }

 protected tokenauthenticationprocessingfilter buildtokenauthenticationprocessingfilter() throws exception {
 list<string> list = lists.newarraylist(token_based_auth_entry_point,manage_token_based_auth_entry_point);
 skippathrequestmatcher matcher = new skippathrequestmatcher(list);
 tokenauthenticationprocessingfilter filter = new tokenauthenticationprocessingfilter(failurehandler, tokenextractor, matcher);
 filter.setauthenticationmanager(this.authenticationmanager);
 return filter;
 }

 @bean
 @override
 public authenticationmanager authenticationmanagerbean() throws exception {
 return super.authenticationmanagerbean();
 }

 @override
 protected void configure(authenticationmanagerbuilder auth) {
 auth.authenticationprovider(loginauthenticationprovider);
 auth.authenticationprovider(tokenauthenticationprovider);
 }

 @override
 protected void configure(httpsecurity http) throws exception {
 http
 .csrf().disable() // 因为使用的是jwt,因此这里可以关闭csrf了
 .exceptionhandling()
 .authenticationentrypoint(this.authenticationentrypoint)
 .and()
  .sessionmanagement()
  .sessioncreationpolicy(sessioncreationpolicy.stateless)
 .and()
  .authorizerequests()
  .antmatchers(form_based_login_entry_point).permitall() // login end-point
  .antmatchers(token_refresh_entry_point).permitall() // token refresh end-point
 .and()
  .authorizerequests()
  .antmatchers(token_based_auth_entry_point).authenticated() // protected api end-points
  .antmatchers(manage_token_based_auth_entry_point).hasanyrole(roleenum.admin.name())
 .and()
  .addfilterbefore(buildloginprocessingfilter(), usernamepasswordauthenticationfilter.class)
  .addfilterbefore(buildtokenauthenticationprocessingfilter(), usernamepasswordauthenticationfilter.class);
 }
}

- 说点什么

由于jwt代码做了简单封装,包含内容较多,所以文章里只贴主要片段,需要完整代码可以直接从下面git获取

本章代码(battcn-jwt-service):

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网