SpringSecurity+JWT实现前后端分离的使用详解
程序员文章站
2022-07-06 22:49:19
创建一个配置类 securityconfig 继承 websecurityconfigureradapterpackage top.ryzeyang.demo.common.config;import...
创建一个配置类 securityconfig 继承 websecurityconfigureradapter
package top.ryzeyang.demo.common.config; import org.springframework.context.annotation.bean; import org.springframework.security.access.hierarchicalroles.rolehierarchy; import org.springframework.security.access.hierarchicalroles.rolehierarchyimpl; import org.springframework.security.authentication.authenticationmanager; import org.springframework.security.config.annotation.authentication.builders.authenticationmanagerbuilder; import org.springframework.security.config.annotation.method.configuration.enableglobalmethodsecurity; import org.springframework.security.config.annotation.web.builders.httpsecurity; import org.springframework.security.config.annotation.web.builders.websecurity; import org.springframework.security.config.annotation.web.configuration.enablewebsecurity; import org.springframework.security.config.annotation.web.configuration.websecurityconfigureradapter; import org.springframework.security.config.http.sessioncreationpolicy; import org.springframework.security.core.userdetails.user; import org.springframework.security.core.userdetails.userdetails; import org.springframework.security.core.userdetails.userdetailsservice; import org.springframework.security.crypto.factory.passwordencoderfactories; import org.springframework.security.crypto.password.passwordencoder; import org.springframework.security.provisioning.inmemoryuserdetailsmanager; import org.springframework.security.web.authenticationentrypoint; import org.springframework.security.web.access.accessdeniedhandler; import org.springframework.security.web.authentication.authenticationfailurehandler; import org.springframework.security.web.authentication.authenticationsuccesshandler; import org.springframework.security.web.authentication.usernamepasswordauthenticationfilter; import org.springframework.security.web.authentication.logout.logoutsuccesshandler; import top.ryzeyang.demo.common.filter.jwtauthenticationtokenfilter; import top.ryzeyang.demo.utils.jwttokenutil; @enablewebsecurity @enableglobalmethodsecurity(prepostenabled = true) public class securityconfig extends websecurityconfigureradapter { final authenticationfailurehandler authenticationfailurehandler; final authenticationsuccesshandler authenticationsuccesshandler; final authenticationentrypoint authenticationentrypoint; final accessdeniedhandler accessdeniedhandler; final logoutsuccesshandler logoutsuccesshandler; public securityconfig(authenticationfailurehandler authenticationfailurehandler, authenticationsuccesshandler authenticationsuccesshandler, authenticationentrypoint authenticationentrypoint, accessdeniedhandler accessdeniedhandler, logoutsuccesshandler logoutsuccesshandler) { this.authenticationfailurehandler = authenticationfailurehandler; this.authenticationsuccesshandler = authenticationsuccesshandler; this.authenticationentrypoint = authenticationentrypoint; this.accessdeniedhandler = accessdeniedhandler; this.logoutsuccesshandler = logoutsuccesshandler; } @bean public passwordencoder passwordencoder() { return passwordencoderfactories.createdelegatingpasswordencoder(); } @bean("users") public userdetailsservice users() { userdetails user = user.builder() .username("user") .password("{bcrypt}$2a$10$1.nsmxloymgjhxoi8cwwxuu83g0/hitxxrobo4qwzmtdp0tzpbcf.") .roles("user") // roles 和 authorities 不能并存 // .authorities(new string[]{"system:user:query", "system:user:edit", "system:user:delete"}) .build(); userdetails admin = user.builder() .username("admin") .password("{bcrypt}$2a$10$1.nsmxloymgjhxoi8cwwxuu83g0/hitxxrobo4qwzmtdp0tzpbcf.") // .roles("user", "admin") .roles("admin") // .authorities("system:user:create") .build(); return new inmemoryuserdetailsmanager(user, admin); } /** * 角色继承: * 让admin角色拥有user的角色的权限 * @return */ @bean public rolehierarchy rolehierarchy() { rolehierarchyimpl result = new rolehierarchyimpl(); result.sethierarchy("role_admin > role_user"); return result; } @override protected void configure(authenticationmanagerbuilder auth) throws exception { auth.userdetailsservice(users()); } @override public void configure(websecurity web) throws exception { web.ignoring().antmatchers("/js/**", "/css/**", "/images/**"); } @override protected void configure(httpsecurity http) throws exception { // 自定义异常处理 http.exceptionhandling() .authenticationentrypoint(authenticationentrypoint) .accessdeniedhandler(accessdeniedhandler) // 权限 .and() .authorizerequests() // 一个是必须待身份信息但是不校验权限。 .antmatchers("/", "/mock/login").permitall() //只允许匿名访问 .antmatchers("/hello").anonymous() .anyrequest() .authenticated() // 表单登录 // .and() // .formlogin() // .successhandler(authenticationsuccesshandler) // .failurehandler(authenticationfailurehandler) // .loginprocessingurl("/login") // .permitall() // 注销 .and() .logout() .logouturl("/logout") .logoutsuccesshandler(logoutsuccesshandler) .permitall() // 关闭csrf 会在页面中生成一个csrf_token .and() .csrf() .disable() // 基于token,所以不需要session .sessionmanagement() .sessioncreationpolicy(sessioncreationpolicy.stateless) // 添加我们的jwt过滤器 .and() .addfilterbefore(jwtauthenticationtokenfilter(), usernamepasswordauthenticationfilter.class) ; } @bean public jwtauthenticationtokenfilter jwtauthenticationtokenfilter(){ return new jwtauthenticationtokenfilter(); } @bean @override public authenticationmanager authenticationmanagerbean() throws exception { return super.authenticationmanagerbean(); } @bean public jwttokenutil jwttokenutil() { return new jwttokenutil(); } }
创建jwt过滤器 继承 onceperrequestfilter
这里直接用的macro大佬 mall商城里的例子
package top.ryzeyang.demo.common.filter; import lombok.extern.slf4j.slf4j; import org.slf4j.logger; import org.slf4j.loggerfactory; import org.springframework.beans.factory.annotation.autowired; import org.springframework.beans.factory.annotation.qualifier; import org.springframework.beans.factory.annotation.value; import org.springframework.security.authentication.usernamepasswordauthenticationtoken; import org.springframework.security.core.context.securitycontextholder; import org.springframework.security.core.userdetails.userdetails; import org.springframework.security.core.userdetails.userdetailsservice; import org.springframework.security.web.authentication.webauthenticationdetailssource; import org.springframework.stereotype.component; import org.springframework.web.filter.onceperrequestfilter; import top.ryzeyang.demo.utils.jwttokenutil; import javax.servlet.filterchain; import javax.servlet.servletexception; import javax.servlet.http.httpservletrequest; import javax.servlet.http.httpservletresponse; import java.io.ioexception; /** * jwt登录授权过滤器 * * @author macro * @date 2018/4/26 */ @slf4j public class jwtauthenticationtokenfilter extends onceperrequestfilter { @qualifier("users") @autowired private userdetailsservice userdetailsservice; @autowired private jwttokenutil jwttokenutil; @value("${jwt.tokenheader}") private string tokenheader; @value("${jwt.tokenhead}") private string tokenhead; @override protected void dofilterinternal(httpservletrequest request, httpservletresponse response, filterchain chain) throws servletexception, ioexception { string authheader = request.getheader(this.tokenheader); if (authheader != null && authheader.startswith(this.tokenhead)) { string authtoken = authheader.substring(this.tokenhead.length());// the part after "bearer " string username = jwttokenutil.getusernamefromtoken(authtoken); log.info("checking username:{}", username); if (username != null && securitycontextholder.getcontext().getauthentication() == null) { userdetails userdetails = this.userdetailsservice.loaduserbyusername(username); if (jwttokenutil.validatetoken(authtoken, userdetails)) { usernamepasswordauthenticationtoken authentication = new usernamepasswordauthenticationtoken(userdetails, null, userdetails.getauthorities()); authentication.setdetails(new webauthenticationdetailssource().builddetails(request)); log.info("authenticated user:{}", username); securitycontextholder.getcontext().setauthentication(authentication); } } } chain.dofilter(request, response); } }
自定义handler
这里主要介绍两个hanler,一个权限不足,一个验证失败的
权限不足 实现 accessdeniedhandler
package top.ryzeyang.demo.common.handler; import com.fasterxml.jackson.databind.objectmapper; import org.springframework.security.access.accessdeniedexception; import org.springframework.security.web.access.accessdeniedhandler; import org.springframework.stereotype.component; import top.ryzeyang.demo.common.api.commonresult; import top.ryzeyang.demo.common.api.resultenum; import javax.servlet.servletexception; import javax.servlet.http.httpservletrequest; import javax.servlet.http.httpservletresponse; import java.io.ioexception; import java.io.printwriter; @component public class myaccessdeinehandler implements accessdeniedhandler { @override public void handle(httpservletrequest httpservletrequest, httpservletresponse httpservletresponse, accessdeniedexception e) throws ioexception, servletexception { httpservletresponse.setcontenttype("application/json;charset=utf-8"); printwriter writer = httpservletresponse.getwriter(); writer.write(new objectmapper().writevalueasstring(new commonresult<>(resultenum.access_error, e.getmessage()))); writer.flush(); writer.close(); } }
认证失败 实现 authenticationentrypoint
如账号密码错误等验证不通过时
package top.ryzeyang.demo.common.handler; import com.fasterxml.jackson.databind.objectmapper; import org.springframework.security.core.authenticationexception; import org.springframework.security.web.authenticationentrypoint; import org.springframework.stereotype.component; import top.ryzeyang.demo.common.api.commonresult; import top.ryzeyang.demo.common.api.resultenum; import javax.servlet.servletexception; import javax.servlet.http.httpservletrequest; import javax.servlet.http.httpservletresponse; import java.io.ioexception; import java.io.printwriter; @component public class myauthenticationentrypoint implements authenticationentrypoint { @override public void commence(httpservletrequest httpservletrequest, httpservletresponse httpservletresponse, authenticationexception e) throws ioexception, servletexception { httpservletresponse.setcontenttype("application/json;charset=utf-8"); printwriter writer = httpservletresponse.getwriter(); // 认证失败 writer.write(new objectmapper().writevalueasstring(new commonresult<>(resultenum.authentication_error, e.getmessage()))); writer.flush(); writer.close(); } }
jwt工具类
这里直接用的macro大佬 mall商城里的例子
稍微改了一点,因为 jdk11 用的 jjwt 版本不一样 ,语法也有些不同
pom 文件中引入 jjwt
<dependency> <groupid>io.jsonwebtoken</groupid> <artifactid>jjwt-api</artifactid> <version>0.11.2</version> </dependency> <dependency> <groupid>io.jsonwebtoken</groupid> <artifactid>jjwt-impl</artifactid> <version>0.11.2</version> <scope>runtime</scope> </dependency> <dependency> <groupid>io.jsonwebtoken</groupid> <artifactid>jjwt-jackson</artifactid> <!-- or jjwt-gson if gson is preferred --> <version>0.11.2</version> <scope>runtime</scope> </dependency>
jwttokenutil
package top.ryzeyang.demo.utils; import cn.hutool.core.date.dateutil; import cn.hutool.core.util.strutil; import io.jsonwebtoken.claims; import io.jsonwebtoken.jwts; import io.jsonwebtoken.io.decoders; import io.jsonwebtoken.security.keys; import lombok.extern.slf4j.slf4j; import org.springframework.beans.factory.annotation.value; import org.springframework.security.core.userdetails.userdetails; import javax.crypto.secretkey; import java.util.date; import java.util.hashmap; import java.util.map; /** * jwttoken生成的工具类 * jwt token的格式:header.payload.signature * header的格式(算法、token的类型): * {"alg": "hs512","typ": "jwt"} * payload的格式(用户名、创建时间、生成时间): * {"sub":"wang","created":1489079981393,"exp":1489684781} * signature的生成算法: * hmacsha512(base64urlencode(header) + "." +base64urlencode(payload),secret) * * @author macro * @date 2018/4/26 */ @slf4j public class jwttokenutil { private static final string claim_key_username = "sub"; private static final string claim_key_created = "created"; @value("${jwt.secret}") private string secret; @value("${jwt.expiration}") private long expiration; @value("${jwt.tokenhead}") private string tokenhead; private secretkey getsecretkey() { byte[] encodekey = decoders.base64.decode(secret); return keys.hmacshakeyfor(encodekey); } /** * 根据负责生成jwt的token */ private string generatetoken(map<string, object> claims) { secretkey secretkey = getsecretkey(); return jwts.builder() .setclaims(claims) .setexpiration(generateexpirationdate()) .signwith(secretkey) .compact(); } /** * 测试生成的token * @param claims * @return */ public string generatetoken2(map<string, object> claims) { secretkey secretkey = getsecretkey(); return jwts.builder() .setclaims(claims) .setissuer("java4ye") .setexpiration(new date(system.currenttimemillis() + 1 * 1000)) .signwith(secretkey) .compact(); } /** * 从token中获取jwt中的负载 */ private claims getclaimsfromtoken(string token) { secretkey secretkey = getsecretkey(); claims claims = null; try { claims = jwts.parserbuilder() .setsigningkey(secretkey) .build() .parseclaimsjws(token) .getbody(); } catch (exception e) { log.info("jwt格式验证失败:{}", token); } return claims; } /** * 生成token的过期时间 */ private date generateexpirationdate() { return new date(system.currenttimemillis() + expiration * 1000); } /** * 从token中获取登录用户名 */ public string getusernamefromtoken(string token) { string username; try { claims claims = getclaimsfromtoken(token); username = claims.getsubject(); } catch (exception e) { username = null; } return username; } /** * 验证token是否还有效 * * @param token 客户端传入的token * @param userdetails 从数据库中查询出来的用户信息 */ public boolean validatetoken(string token, userdetails userdetails) { string username = getusernamefromtoken(token); return username.equals(userdetails.getusername()) && !istokenexpired(token); } /** * 判断token是否已经失效 */ private boolean istokenexpired(string token) { date expireddate = getexpireddatefromtoken(token); return expireddate.before(new date()); } /** * 从token中获取过期时间 */ private date getexpireddatefromtoken(string token) { claims claims = getclaimsfromtoken(token); return claims.getexpiration(); } /** * 根据用户信息生成token */ public string generatetoken(userdetails userdetails) { map<string, object> claims = new hashmap<>(); claims.put(claim_key_username, userdetails.getusername()); claims.put(claim_key_created, new date()); return generatetoken(claims); } /** * 当原来的token没过期时是可以刷新的 * * @param oldtoken 带tokenhead的token */ public string refreshheadtoken(string oldtoken) { if (strutil.isempty(oldtoken)) { return null; } string token = oldtoken.substring(tokenhead.length()); if (strutil.isempty(token)) { return null; } //token校验不通过 claims claims = getclaimsfromtoken(token); if (claims == null) { return null; } //如果token已经过期,不支持刷新 if (istokenexpired(token)) { return null; } //如果token在30分钟之内刚刷新过,返回原token if (tokenrefreshjustbefore(token, 30 * 60)) { return token; } else { claims.put(claim_key_created, new date()); return generatetoken(claims); } } /** * 判断token在指定时间内是否刚刚刷新过 * * @param token 原token * @param time 指定时间(秒) */ private boolean tokenrefreshjustbefore(string token, int time) { claims claims = getclaimsfromtoken(token); date created = claims.get(claim_key_created, date.class); date refreshdate = new date(); //刷新时间在创建时间的指定时间内 if (refreshdate.after(created) && refreshdate.before(dateutil.offsetsecond(created, time))) { return true; } return false; } }
配置文件 application.yml
这里的 secret 可以用该方法生成
@test void generatekey() { /** * secret 是签名密钥,只生成一次即可,生成方法: * key key = keys.secretkeyfor(signaturealgorithm.hs256); * string secretstring = encoders.base64.encode(key.getencoded()); # 本文使用 base64 编码 * */ key key = keys.secretkeyfor(signaturealgorithm.hs512); string secretstring = encoders.base64.encode(key.getencoded()); system.out.println(secretstring); // blk1x8jln4xh4s+kuc0yufxv+feytgvumycsikbil0yhrddy872mcnzbgzib57jn2v1rtafxixs8tvnpsng//g== }
jwt: tokenheader: authorization secret: blk1x8jln4xh4s+kuc0yufxv+feytgvumycsikbil0yhrddy872mcnzbgzib57jn2v1rtafxixs8tvnpsng//g== expiration: 604800 tokenhead: 'bearer ' server: servlet: context-path: /api
controller
authcontroller
package top.ryzeyang.demo.controller; import org.springframework.beans.factory.annotation.autowired; import org.springframework.beans.factory.annotation.qualifier; import org.springframework.security.authentication.authenticationmanager; import org.springframework.security.authentication.usernamepasswordauthenticationtoken; import org.springframework.security.core.authentication; import org.springframework.security.core.grantedauthority; import org.springframework.security.core.context.securitycontextholder; import org.springframework.security.core.userdetails.userdetails; import org.springframework.security.core.userdetails.userdetailsservice; import org.springframework.web.bind.annotation.*; import top.ryzeyang.demo.common.api.commonresult; import top.ryzeyang.demo.model.dto.userdto; import top.ryzeyang.demo.utils.commonresultutil; import top.ryzeyang.demo.utils.jwttokenutil; import java.util.collection; @restcontroller @responsebody @requestmapping("/mock") public class authcontroller { @autowired private jwttokenutil jwttokenutil; @qualifier("users") @autowired private userdetailsservice userdetailsservice; @autowired authenticationmanager authenticationmanager; @getmapping("/userinfo") public commonresult<collection<? extends grantedauthority>> getuserinfo(){ authentication authentication = securitycontextholder.getcontext().getauthentication(); collection<? extends grantedauthority> authorities = authentication.getauthorities(); return commonresultutil.success(authorities); } /** * 模拟登陆 */ @postmapping("/login") public commonresult<string> login(@requestbody userdto userdto){ string username = userdto.getusername(); string password = userdto.getpassword(); usernamepasswordauthenticationtoken token = new usernamepasswordauthenticationtoken(username, password); authentication authenticate = authenticationmanager.authenticate(token); securitycontextholder.getcontext().setauthentication(authenticate); userdetails userdetails = userdetailsservice.loaduserbyusername(username); string t = jwttokenutil.generatetoken(userdetails); return commonresultutil.success(t); } }
hellocontroller
package top.ryzeyang.demo.controller; import org.springframework.security.access.prepost.preauthorize; import org.springframework.web.bind.annotation.getmapping; import org.springframework.web.bind.annotation.restcontroller; @restcontroller public class hellocontroller { @getmapping("/hello") public string hello() { return "hello"; } @getmapping("/hello/anonymous") public string hello2() { return "anonymous"; } @preauthorize("hasrole('admin')") @getmapping("/hello/admin") public string helloadmin() { return "hello admin"; } @preauthorize("hasrole('user')") @getmapping("/hello/user") public string hellouser() { return "hello user"; } @preauthorize("hasanyauthority('system:user:query')") @getmapping("/hello/user2") public string hellouser2() { return "hello user2"; } }
项目地址在github上
地址:springsecurity-vuetify-permissions-demo
到此这篇关于springsecurity+jwt实现前后端分离的使用详解的文章就介绍到这了,更多相关springsecurity+jwt前后端分离内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!
上一篇: 秀恩爱,死得快呀!