欧陆经典女鞋,祸害新千年,绿鬣蜥怎么养
jwt(json web token), 是为了在网络应用环境间传递声明而执行的一种基于json的开放标准((rfc 7519).该token被设计为紧凑且安全的,特别适用于分布式站点的单点登录(sso)场景。jwt的声明一般被用来在身份提供者和服务提供者间传递被认证的用户身份信息,以便于从资源服务器获取资源,也可以增加一些额外的其它业务逻辑所必须的声明信息,该token也可直接被用于认证,也可被加密。
通常情况下,把api直接暴露出去是风险很大的,不说别的,直接被机器攻击就喝一壶的。那么一般来说,对api要划分出一定的权限级别,然后做一个用户的鉴权,依据鉴权结果给予用户开放对应的api。目前,比较主流的方案有几种:
oauth(开放授权)是一个开放的授权标准,允许用户让第三方应用访问该用户在某一服务上存储的私密的资源(如照片,视频),而无需将用户名和密码提供给第三方应用。
oauth 允许用户提供一个令牌,而不是用户名和密码来访问他们存放在特定服务提供者的数据。每一个令牌授权一个特定的第三方系统(例如,视频编辑网站)在特定的时段(例如,接下来的2小时内)内访问特定的资源(例如仅仅是某一相册中的视频)。这样,oauth让用户可以授权第三方网站访问他们存储在另外服务提供者的某些特定信息,而非所有内容
cookie认证机制就是为一次请求认证在服务端创建一个session对象,同时在客户端的浏览器端创建了一个cookie对象;通过客户端带上来cookie对象来与服务器端的session对象匹配来实现状态管理的。默认的,当我们关闭浏览器的时候,cookie会被删除。但可以通过修改cookie 的expire time使cookie在一定时间内有效,基于session方式认证势必会对服务器造成一定的压力(内存存储),不易于扩展(需要处理分布式session),跨站请求伪造的攻击(csrf)
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" ] }
一个jwt实际上就是一个字符串,它由三部分组成,头部、载荷、签名(上图依次排序)
jwt token生成器:
- 登陆认证
- 请求认证
无效token
有效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):
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。
如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复
浅析我对 String、StringBuilder、StringBuffer 的理解
使用IDEA搭建SSM框架的详细教程(spring + springMVC +MyBatis)
Springboot整合freemarker 404问题解决方案
引入mybatis-plus报 Invalid bound statement错误问题的解决方法
网友评论