Springboot+SpringSecurity+JWT实现用户登录和权限认证示例
如今,互联网项目对于安全的要求越来越严格,这就是对后端开发提出了更多的要求,目前比较成熟的几种大家比较熟悉的模式,像rbac 基于角色权限的验证,shiro框架专门用于处理权限方面的,另一个比较流行的后端框架是spring-security,该框架提供了一整套比较成熟,也很完整的机制用于处理各类场景下的可以基于权限,资源路径,以及授权方面的解决方案,部分模块支持定制化,而且在和oauth2.0进行了很好的无缝连接,在移动互联网的授权认证方面有很强的优势,具体的使用大家可以结合自己的业务场景进行选取和使用
下面来说说关于单点登录中目前比较流行的一种使用方式,就是springsecurity+jwt实现无状态下用户登录;
jwt
在之前的篇章中大致提到过,使用jwt在分布式项目中进行用户信息的认证很方便,各个模块只需要知道配置的秘钥,就可以解密token中用户的基本信息,完成认证,很方便,关于使用jwt的基本内容可以查阅相关资料,或者参考我之前的一篇;
整理一下思路
1、搭建springboot工程
2、导入springsecurity跟jwt的依赖
3、用户的实体类,dao层,service层(真正开发时再写,这里就直接调用dao层操作数据库)
4、实现userdetailsservice接口
5、实现userdetails接口
6、验证用户登录信息的拦截器
7、验证用户权限的拦截器
8、springsecurity配置
9、认证的controller以及测试的controller
项目结构
pom文件
<dependencies> <dependency> <groupid>org.springframework.boot</groupid> <artifactid>spring-boot-starter-web</artifactid> </dependency> <dependency> <groupid>org.springframework.boot</groupid> <artifactid>spring-boot-starter-test</artifactid> <scope>test</scope> </dependency> <dependency> <groupid>org.springframework.boot</groupid> <artifactid>spring-boot-starter</artifactid> </dependency> <dependency> <groupid>org.springframework.boot</groupid> <artifactid>spring-boot-starter-security</artifactid> </dependency> <!-- https://mvnrepository.com/artifact/org.springframework.security.oauth/spring-security-oauth2 --> <dependency> <groupid>org.springframework.security.oauth</groupid> <artifactid>spring-security-oauth2</artifactid> <version>2.3.5.release</version> </dependency> <!-- https://mvnrepository.com/artifact/org.springframework.security/spring-security-jwt --> <dependency> <groupid>org.springframework.security</groupid> <artifactid>spring-security-jwt</artifactid> <version>1.0.10.release</version> </dependency> <!-- https://mvnrepository.com/artifact/org.springframework.security.oauth.boot/spring-security-oauth2-autoconfigure --> <dependency> <groupid>org.springframework.security.oauth.boot</groupid> <artifactid>spring-security-oauth2-autoconfigure</artifactid> <version>2.1.4.release</version> </dependency> <dependency> <groupid>io.jsonwebtoken</groupid> <artifactid>jjwt</artifactid> <version>0.9.1</version> </dependency> <dependency> <groupid>org.springframework.boot</groupid> <artifactid>spring-boot-starter-data-jpa</artifactid> </dependency> <dependency> <groupid>mysql</groupid> <artifactid>mysql-connector-java</artifactid> </dependency> <!-- mybatis依赖 --> <dependency> <groupid>org.mybatis.spring.boot</groupid> <artifactid>mybatis-spring-boot-starter</artifactid> <version>1.3.0</version> </dependency> <dependency> <groupid>org.springframework.boot</groupid> <artifactid>spring-boot-starter-jdbc</artifactid> </dependency> <!-- redis依赖 --> <dependency> <groupid>org.springframework.boot</groupid> <artifactid>spring-boot-starter-data-redis</artifactid> </dependency> </dependencies>
application.properties
server.port=8091 #数据库连接 spring.datasource.url=jdbc:mysql://localhost:3306/test?useunicode=true spring.datasource.driver-class-name=com.mysql.jdbc.driver spring.datasource.username=root spring.datasource.password=root #mybatis配置 mybatis.type-aliases-package=com.congge.entity mybatis.mapper-locations=classpath:mybatis/*.xml #redis配置 spring.session.store-type=redis spring.redis.database=0 spring,redis.host=127.0.0.1 spring.redis.port=6379 spring.redis.pool.min-idle=10000 spring.redis.timeout=30000
为模拟用户登录,这里提前创建了一个测试使用的表,user
实体类user
public class user { private integer id; private string username; private string password; private string role; public integer getid() { return id; } public void setid(integer id) { this.id = id; } public string getusername() { return username; } public void setusername(string username) { this.username = username; } public string getpassword() { return password; } public void setpassword(string password) { this.password = password; } public string getrole() { return role; } public void setrole(string role) { this.role = role; } @override public string tostring() { return "user{" + "id=" + id + ", username='" + username + '\'' + ", password='" + password + '\'' + ", role='" + role + '\'' + '}'; } }
jwt工具类,用于管理token相关的操作,可以单测使用
public class testjwtutils { public static final string token_header = "authorization"; public static final string token_prefix = "bearer "; public static final string subject = "congge"; public static final long expirition = 1000 * 24 * 60 * 60 * 7; public static final string appsecret_key = "congge_secret"; private static final string role_claims = "rol"; public static string generatejsonwebtoken(users user) { if (user.getid() == null || user.getusername() == null || user.getfaceimage() == null) { return null; } map<string,object> map = new hashmap<>(); map.put(role_claims, "rol"); string token = jwts .builder() .setsubject(subject) .setclaims(map) .claim("id", user.getid()) .claim("name", user.getusername()) .claim("img", user.getfaceimage()) .setissuedat(new date()) .setexpiration(new date(system.currenttimemillis() + expirition)) .signwith(signaturealgorithm.hs256, appsecret_key).compact(); return token; } /** * 生成token * @param username * @param role * @return */ public static string createtoken(string username,string role) { map<string,object> map = new hashmap<>(); map.put(role_claims, role); string token = jwts .builder() .setsubject(username) .setclaims(map) .claim("username",username) .setissuedat(new date()) .setexpiration(new date(system.currenttimemillis() + expirition)) .signwith(signaturealgorithm.hs256, appsecret_key).compact(); return token; } public static claims checkjwt(string token) { try { final claims claims = jwts.parser().setsigningkey(appsecret_key).parseclaimsjws(token).getbody(); return claims; } catch (exception e) { e.printstacktrace(); return null; } } /** * 获取用户名 * @param token * @return */ public static string getusername(string token){ claims claims = jwts.parser().setsigningkey(appsecret_key).parseclaimsjws(token).getbody(); return claims.get("username").tostring(); } /** * 获取用户角色 * @param token * @return */ public static string getuserrole(string token){ claims claims = jwts.parser().setsigningkey(appsecret_key).parseclaimsjws(token).getbody(); return claims.get("rol").tostring(); } /** * 是否过期 * @param token * @return */ public static boolean isexpiration(string token){ claims claims = jwts.parser().setsigningkey(appsecret_key).parseclaimsjws(token).getbody(); return claims.getexpiration().before(new date()); } public static void main(string[] args) { string name = "acong"; string role = "rol"; string token = createtoken(name,role); system.out.println(token); claims claims = checkjwt(token); system.out.println(claims.get("username")); system.out.println(getusername(token)); system.out.println(getuserrole(token)); system.out.println(isexpiration(token)); } /** * eyjhbgcioijiuzi1nij9. * eyjzdwiioijjb25nz2uilcjpzci6ijexmdexiiwibmftzsi6im51b3dlaxnpa2kilcjpbwcioij3d3cudw9rby5jb20vms5wbmcilcjpyxqioje1ntq5oti1nzksimv4cci6mtu1ntu5nzm3ox0. * 6dj9en-ubctimrldzeevjq3e1nxjgowryuyim4_-tee * * @param args */ /*public static void main(string[] args) { users user = new users(); user.setid("11011"); user.setusername("nuoweisiki"); user.setfaceimage("www.uoko.com/1.png"); string token = generatejsonwebtoken(user); system.out.println(token); claims claims = checkjwt(token); if (claims != null) { string id = claims.get("id").tostring(); string name = claims.get("name").tostring(); string img = claims.get("img").tostring(); string rol = claims.get("rol").tostring(); system.out.println("id:" + id); system.out.println("name:" + name); system.out.println("img:" + img); system.out.println("rol:" + rol); } }*/ }
操作数据库的类
,这里主要是提供用户注册的一个save用户的方法,
@service public class userservice { @autowired private userdao userdao; public void save(user user) { user.setid(1); userdao.save(user); } }
jwtuser
该类封装登录用户相关信息,例如用户名,密码,权限集合等,需要实现userdetails 接口,
public class jwtuser implements userdetails { private integer id; private string username; private string password; private collection<? extends grantedauthority> authorities; public jwtuser() { } // 写一个能直接使用user创建jwtuser的构造器 public jwtuser(user user) { id = user.getid(); username = user.getusername(); password = user.getpassword(); authorities = collections.singleton(new simplegrantedauthority(user.getrole())); } public collection<? extends grantedauthority> getauthorities() { return authorities; } public string getpassword() { return password; } public string getusername() { return username; } public boolean isaccountnonexpired() { return true; } public boolean isaccountnonlocked() { return true; } public boolean iscredentialsnonexpired() { return true; } public boolean isenabled() { return true; } @override public string tostring() { return "jwtuser{" + "id=" + id + ", username='" + username + '\'' + ", password='" + password + '\'' + ", authorities=" + authorities + '}'; } }
配置拦截器
jwtauthenticationfilter
jwtauthenticationfilter继承于usernamepasswordauthenticationfilter
该拦截器用于获取用户登录的信息,只需创建一个token并调用authenticationmanager.authenticate()让spring-security去进行验证就可以了,不用自己查数据库再对比密码了,这一步交给spring去操作。 这个操作有点像是shiro的subject.login(new usernamepasswordtoken()),验证的事情交给框架。
/** * 验证用户名密码正确后,生成一个token,并将token返回给客户端 * 该类继承自usernamepasswordauthenticationfilter,重写了其中的2个方法 , * attemptauthentication:接收并解析用户凭证。 * successfulauthentication:用户成功登录后,这个方法会被调用,我们在这个方法里生成token并返回。 */ public class jwtauthenticationfilter extends usernamepasswordauthenticationfilter { private authenticationmanager authenticationmanager; public jwtauthenticationfilter(authenticationmanager authenticationmanager) { this.authenticationmanager = authenticationmanager; super.setfilterprocessesurl("/auth/login"); } @override public authentication attemptauthentication(httpservletrequest request, httpservletresponse response) throws authenticationexception { // 从输入流中获取到登录的信息 try { loginuser loginuser = new objectmapper().readvalue(request.getinputstream(), loginuser.class); return authenticationmanager.authenticate( new usernamepasswordauthenticationtoken(loginuser.getusername(), loginuser.getpassword()) ); } catch (ioexception e) { e.printstacktrace(); return null; } } // 成功验证后调用的方法 // 如果验证成功,就生成token并返回 @override protected void successfulauthentication(httpservletrequest request, httpservletresponse response, filterchain chain, authentication authresult) throws ioexception, servletexception { jwtuser jwtuser = (jwtuser) authresult.getprincipal(); system.out.println("jwtuser:" + jwtuser.tostring()); string role = ""; collection<? extends grantedauthority> authorities = jwtuser.getauthorities(); for (grantedauthority authority : authorities){ role = authority.getauthority(); } string token = testjwtutils.createtoken(jwtuser.getusername(), role); //string token = jwttokenutils.createtoken(jwtuser.getusername(), false); // 返回创建成功的token // 但是这里创建的token只是单纯的token // 按照jwt的规定,最后请求的时候应该是 `bearer token` response.setcharacterencoding("utf-8"); response.setcontenttype("application/json; charset=utf-8"); string tokenstr = jwttokenutils.token_prefix + token; response.setheader("token",tokenstr); } @override protected void unsuccessfulauthentication(httpservletrequest request, httpservletresponse response, authenticationexception failed) throws ioexception, servletexception { response.getwriter().write("authentication failed, reason: " + failed.getmessage()); } }
jwtauthorizationfilter
验证成功当然就是进行鉴权了,每一次需要权限的请求都需要检查该用户是否有该权限去操作该资源,当然这也是框架帮我们做的,那么我们需要做什么呢?很简单,只要告诉spring-security该用户是否已登录,是什么角色,拥有什么权限就可以了。
jwtauthenticationfilter继承于basicauthenticationfilter,至于为什么要继承这个我也不太清楚了,这个我也是网上看到的其中一种实现,实在springsecurity苦手,不过我觉得不继承这个也没事呢(实现以下filter接口或者继承其他filter实现子类也可以吧)只要确保过滤器的顺序,jwtauthorizationfilter在jwtauthenticationfilter后面就没问题了。
/** * 验证成功当然就是进行鉴权了 * 登录成功之后走此类进行鉴权操作 */ public class jwtauthorizationfilter extends basicauthenticationfilter { public jwtauthorizationfilter(authenticationmanager authenticationmanager) { super(authenticationmanager); } @override protected void dofilterinternal(httpservletrequest request, httpservletresponse response, filterchain chain) throws ioexception, servletexception { string tokenheader = request.getheader(testjwtutils.token_header); // 如果请求头中没有authorization信息则直接放行了 if (tokenheader == null || !tokenheader.startswith(testjwtutils.token_prefix)) { chain.dofilter(request, response); return; } // 如果请求头中有token,则进行解析,并且设置认证信息 securitycontextholder.getcontext().setauthentication(getauthentication(tokenheader)); super.dofilterinternal(request, response, chain); } // 这里从token中获取用户信息并新建一个token private usernamepasswordauthenticationtoken getauthentication(string tokenheader) { string token = tokenheader.replace(testjwtutils.token_prefix, ""); string username = testjwtutils.getusername(token); string role = testjwtutils.getuserrole(token); if (username != null){ return new usernamepasswordauthenticationtoken(username, null, collections.singleton(new simplegrantedauthority(role)) ); } return null; } }
配置springsecurity
到这里基本操作都写好啦,现在就需要我们将这些辛苦写好的“组件”组合到一起发挥作用了,那就需要配置了。需要开启一下注解@enablewebsecurity然后再继承一下websecurityconfigureradapter就可以啦,
@enablewebsecurity @enableglobalmethodsecurity(prepostenabled = true) public class securityconfig extends websecurityconfigureradapter { @autowired @qualifier("userdetailsserviceimpl") private userdetailsservice userdetailsservice; @bean public bcryptpasswordencoder bcryptpasswordencoder(){ return new bcryptpasswordencoder(); } @override protected void configure(authenticationmanagerbuilder auth) throws exception { auth.userdetailsservice(userdetailsservice).passwordencoder(bcryptpasswordencoder()); } @override protected void configure(httpsecurity http) throws exception { http.cors().and().csrf().disable() .authorizerequests() // 测试用资源,需要验证了的用户才能访问 .antmatchers("/tasks/**") .authenticated() .antmatchers(httpmethod.delete, "/tasks/**") .hasrole("admin") // 其他都放行了 .anyrequest().permitall() .and() .addfilter(new jwtauthenticationfilter(authenticationmanager())) .addfilter(new jwtauthorizationfilter(authenticationmanager())) // 不需要session .sessionmanagement() .sessioncreationpolicy(sessioncreationpolicy.stateless) .and() .exceptionhandling() .authenticationentrypoint(new jwtauthenticationentrypoint()); } @bean corsconfigurationsource corsconfigurationsource() { final urlbasedcorsconfigurationsource source = new urlbasedcorsconfigurationsource(); source.registercorsconfiguration("/**", new corsconfiguration().applypermitdefaultvalues()); return source; } }
authcontroller
测试类,模拟用户注册,
@restcontroller @requestmapping("/auth") public class authcontroller { @autowired private userservice userservice; @autowired private bcryptpasswordencoder bcryptpasswordencoder; @postmapping("/register") public string registeruser(@requestbody map<string,string> registeruser){ user user = new user(); user.setusername(registeruser.get("username")); user.setpassword(bcryptpasswordencoder.encode(registeruser.get("password"))); user.setrole("role_user"); userservice.save(user); return "success"; } }
注册是有了,那登录在哪呢?我们看一下usernamepasswordauthenticationfilter的源代码
public usernamepasswordauthenticationfilter() { super(new antpathrequestmatcher("/login", "post")); }
可以看出来默认是/login,所以登录直接使用这个路径就可以啦~当然也可以自定义
只需要在jwtauthenticationfilter的构造方法中加入下面那一句话就可以啦
public jwtauthenticationfilter(authenticationmanager authenticationmanager) { this.authenticationmanager = authenticationmanager; super.setfilterprocessesurl("/auth/login"); }
所以现在认证的路径统一了一下也是挺好的~看起来相当舒服了
注册:/auth/register
登录:/auth/login
taskcontroller
提供一个外部访问的api资源接口,即用户要访问该类下面的接口必须要先通过认证,后面的测试中也可以看出来,直接贴代码,
@requestmapping("/tasks") public class taskcontroller { @getmapping("/gettasks") @responsebody public string listtasks(){ return "任务列表"; } @postmapping @preauthorize("hasrole('admin')") public string newtasks(){ return "创建了一个新的任务"; } }
下面我们来测试一下,为了模拟效果比较直观点,我们使用postman进行测试,
1、首先,我们调用注册的方法注册一个用户,
注册成功之后,我们看到数据库已经有了一个用户,
2、使用该用户进行登录,我们希望的是登录成功之后,后台生成一个token并返回给前端,这样后面的接口调用中直接带上这个token即可,
可以看到登录成功,后台反返回了token,下面我们使用这个token请求其他的接口,测试一下gettasks这个接口,注意需要在postman的请求header里面带上token信息,这里是全部的token,即包含bearer 的整个字符串,
这时候,成功请求到了接口的数据,大家可以测试一下将过期时间调整的短一点,然后再去请求看看会有什么样的效果,这里就不做演示了。
本篇到这里基本就结束了,关于springsecurity其实内容还是很多的,里面的用法也比较复杂,大家抽空可以做深入的研究,篇幅原因不做过多介绍了。最后感谢观看。
附上源码地址:
到此这篇关于springboot+springsecurity+jwt实现用户登录和权限认证示例的文章就介绍到这了,更多相关springboot springsecurity jwt内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!
推荐阅读
-
Springboot+SpringSecurity+JWT实现用户登录和权限认证示例
-
springMVC+request.session实现用户登录和访问权限控制
-
shiro学习三(spring boot整合shiro读取数据库数据实现用户登录,权限认证)
-
Springboot+Spring Security实现前后端分离登录认证及权限控制的示例代码
-
ASP.NET MVC+EF框架+EasyUI实现权限管理系列(12)-实现用户异步登录和T4模板
-
springboot+shiro实现用户登录认证和权限管理(二)
-
php中Zend_Auth和Zend_Acl进行登录认证及根据用户角色进行权限控制 (1/4)_PHP教程
-
Springboot+SpringSecurity+JWT实现用户登录和权限认证示例
-
ASP.NET MVC+EF框架+EasyUI实现权限管理系列(12)-实现用户异步登录和T4模板
-
springMVC+request.session实现用户登录和访问权限控制