springboot整合shiro与自定义过滤器的全过程
程序员文章站
2022-01-01 12:22:32
目录filter自定义过滤器 增加了 对验证码的校验shiro中的权限控制总结filter自定义过滤器 增加了 对验证码的校验package com.youxiong.filter;import co...
filter自定义过滤器 增加了 对验证码的校验
package com.youxiong.filter; import com.youxiong.shiro.usernamepasswordkaptchatoken; import org.apache.shiro.authc.authenticationtoken; import org.apache.shiro.subject.subject; import org.apache.shiro.web.filter.authc.formauthenticationfilter; import javax.servlet.servletrequest; import javax.servlet.servletresponse; import javax.servlet.http.httpservletrequest; import javax.servlet.http.httpsession; public class formvalid extends formauthenticationfilter { private string kaptcha = "kaptcha_session_key"; public formvalid() { super(); } //用户未登录 /* @override protected boolean onaccessdenied(servletrequest request, servletresponse response) throws exception { httpservletrequest httpservletrequest = (httpservletrequest) request; httpsession session = httpservletrequest.getsession(); string kaptchacode = (string) session.getattribute(kaptcha); string code = httpservletrequest.getparameter("code"); if(code!=null&&kaptchacode!=null&&!kaptchacode.equals(code)){ httpservletrequest.setattribute("shirologinfailure","codeerror"); return true; } return super.onaccessdenied(request, response); } */ //用户提交表单时候 创建的token @override protected authenticationtoken createtoken( servletrequest request, servletresponse response) { httpservletrequest httpservletrequest = (httpservletrequest) request; string code = (string) httpservletrequest.getparameter("kaptcha"); string host = gethost(request); string username = getusername(request); string password = getpassword(request); boolean rememberme = isrememberme(request); system.out.println("create token--------------code------>one "+code); return new usernamepasswordkaptchatoken(username,password.tochararray(),rememberme,host,code); } }
自定义usernamepassword是为了接收前台发送过来的数据
package com.youxiong.shiro; import org.apache.shiro.authc.authenticationtoken; import org.apache.shiro.authc.usernamepasswordtoken; import java.io.serializable; public class usernamepasswordkaptchatoken extends usernamepasswordtoken { private static final long serialversionuid = 1l; private string kaptcha; public usernamepasswordkaptchatoken(){ super(); } public usernamepasswordkaptchatoken(string username, char[] password, boolean rememberme, string host, string kaptcha) { super(username, password, rememberme, host); this.kaptcha = kaptcha; } public string getkaptcha() { return kaptcha; } public void setkaptcha(string kaptcha) { this.kaptcha = kaptcha; } }
shiro配置
package com.youxiong.config; import com.google.code.kaptcha.servlet.kaptchaservlet; import com.youxiong.dao.userreposisty; import com.youxiong.domain.permission; import com.youxiong.domain.role; import com.youxiong.domain.userinfo; import com.youxiong.filter.formvalid; import com.youxiong.redis.jediscachemanager; import com.youxiong.redis.redissessiondao; import com.youxiong.redis.redissessionlistener; import com.youxiong.redis.redisesessionfactory; import com.youxiong.shiro.myshirorealm; import org.apache.shiro.authc.credential.hashedcredentialsmatcher; import org.apache.shiro.mgt.securitymanager; import org.apache.shiro.session.sessionlistener; import org.apache.shiro.session.mgt.sessionfactory; import org.apache.shiro.session.mgt.sessionmanager; import org.apache.shiro.session.mgt.eis.enterprisecachesessiondao; import org.apache.shiro.session.mgt.eis.sessiondao; import org.apache.shiro.spring.security.interceptor.authorizationattributesourceadvisor; import org.apache.shiro.spring.web.shirofilterfactorybean; import org.apache.shiro.web.mgt.defaultwebsecuritymanager; import org.apache.shiro.web.servlet.simplecookie; import org.apache.shiro.web.session.mgt.defaultwebsessionmanager; import org.springframework.beans.factory.annotation.autowired; import org.springframework.boot.web.servlet.servletregistrationbean; import org.springframework.context.annotation.bean; import org.springframework.context.annotation.configuration; import org.springframework.web.servlet.handler.simplemappingexceptionresolver; import javax.servlet.filter; import java.util.*; @configuration public class shiroconfig { @autowired private userreposisty userreposisty; @bean public shirofilterfactorybean createshirofilter(securitymanager securitymanager) { system.out.println("--------shirofilterfactorybean-------"); shirofilterfactorybean shirofilterfactorybean = new shirofilterfactorybean(); shirofilterfactorybean.setsecuritymanager(securitymanager); map<string, filter> filtermap = new hashmap<>(); //map里面key值要为authc才能使用自定义的过滤器 filtermap.put("authc", formvalid()); // can go to login shirofilterfactorybean.setloginurl("/login.html"); //dologin success go to page shirofilterfactorybean.setsuccessurl("/success.html"); //do not unauthorized page shirofilterfactorybean.setunauthorizedurl("/403.html"); map<string, string> map = new linkedhashmap<string, string>(); //验证码的路径 不要跟下面需要认证的写在一个路径里 会被拦截的 map.put("/servlet/**", "anon"); //需要把要授权的url 全部装到filterchain中去过滤 userinfo userinfo = userreposisty.findbyuid(1); for (role role : userinfo.getroles()) { for (permission permission : role.getpermissions()) { if (permission.geturl() != "") { string permissions = "perms[" + permission.getpermission() + "]"; map.put(permission.geturl(), permissions); } } } map.put("/user*/*", "authc"); shirofilterfactorybean.setfilterchaindefinitionmap(map); shirofilterfactorybean.setfilters(filtermap); return shirofilterfactorybean; } //自己定义realm @bean public myshirorealm myshirorealm() { myshirorealm myshirorealm = new myshirorealm(); return myshirorealm; } @bean public securitymanager securitymanager() { defaultwebsecuritymanager securitymanager = new defaultwebsecuritymanager(); securitymanager.setrealm(myshirorealm()); //缓存管理 securitymanager.setcachemanager(jediscachemanager()); //会话管理 securitymanager.setsessionmanager(sessionmanager()); return securitymanager; } //密码盐 可以不必实现 因为一般密码可以自己定义自己的密码加密规则 /* @bean public hashedcredentialsmatcher hashedcredentialsmatcher(){ hashedcredentialsmatcher hashedcredentialsmatcher = new hashedcredentialsmatcher(); hashedcredentialsmatcher.sethashalgorithmname("md5"); hashedcredentialsmatcher.sethashiterations(2); return hashedcredentialsmatcher; }*/ //开启aop注解 @bean public authorizationattributesourceadvisor authorizationattributesourceadvisor(securitymanager securitymanager) { authorizationattributesourceadvisor authorizationattributesourceadvisor = new authorizationattributesourceadvisor(); authorizationattributesourceadvisor.setsecuritymanager(securitymanager); return authorizationattributesourceadvisor; } @bean(name = "simplemappingexceptionresolver") public simplemappingexceptionresolver createsimplemappingexceptionresolver() { simplemappingexceptionresolver r = new simplemappingexceptionresolver(); properties mappings = new properties(); mappings.setproperty("databaseexception", "databaseerror");//数据库异常处理 mappings.setproperty("unauthorizedexception", "403"); r.setexceptionmappings(mappings); // none by default r.setdefaulterrorview("error"); // no default r.setexceptionattribute("ex"); // default is "exception" //r.setwarnlogcategory("example.mvclogger"); // no default return r; } //servlet注册器 -----》验证码的路径 @bean public servletregistrationbean servletregistrationbean() { system.out.println("----验证码---"); return new servletregistrationbean(new kaptchaservlet(), "/servlet/kaptcha.jpg"); } //自定义过滤器 ---》里面实现了对验证码校验 @bean("myfilter") public formvalid formvalid() { return new formvalid(); } //jedis缓存 @bean public jediscachemanager jediscachemanager() { return new jediscachemanager(); } @bean public sessionmanager sessionmanager() { defaultwebsessionmanager defaultwebsessionmanager = new defaultwebsessionmanager(); defaultwebsessionmanager.setsessionidcookie(simplecookie()); defaultwebsessionmanager.setsessiondao(sessiondao()); //可以设置shiro提供的会话管理机制 //defaultwebsessionmanager.setsessiondao(new enterprisecachesessiondao()); return defaultwebsessionmanager; } //这里就是会话管理的操作类 @bean public sessiondao sessiondao() { return new redissessiondao(); } //这里需要设置一个cookie的名称 原因就是会跟原来的session的id值重复的 @bean public simplecookie simplecookie() { simplecookie simplecookie = new simplecookie("redissession"); return simplecookie; } }
shiro中的权限控制
#需要同时拥有order:add和order:query权限才可以访问 /order-add = perms["order:add","order:query"] #只需要order:del权限就可以访问 /order-del = perms["order:del"]
perms表示的就是权限控制,中括号中就是需要访问等号之前路径,需要的权限名称。如果在使用shiro过滤器的时候,不配置过滤器,就会使用默认的过滤器。
以下是默认权限过滤器的源码。
public class permissionsauthorizationfilter extends authorizationfilter { public permissionsauthorizationfilter() { } public boolean isaccessallowed(servletrequest request, servletresponse response, object mappedvalue) throws ioexception { subject subject = this.getsubject(request, response); string[] perms = (string[])mappedvalue; boolean ispermitted = true; if (perms != null && perms.length > 0) { if (perms.length == 1) { if (!subject.ispermitted(perms[0])) { ispermitted = false; } } else if (!subject.ispermittedall(perms)) { ispermitted = false; } } return ispermitted; } }
从上面的代码可以看出,我们的配置会默认被强转为string类型的字符串数组。当只有一个权限时,会直接判断有没有该权限; 当配置多个权限时,从下面的代码可以看出只用在请求url的用户拥有所有的权限时,才会返回true,否则就会被拒绝访问。
总结
到此这篇关于springboot整合shiro与自定义过滤器的文章就介绍到这了,更多相关springboot整合shiro与自定义过滤器内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!