shiro 自定义filter
1.自定义登录filter
package com.creatunion.callcenter.filter; import com.alibaba.fastjson.JSONObject;
import com.creatunion.callcenter.model.SysUser;
import com.creatunion.callcenter.utils.Result;
import com.creatunion.callcenter.utils.ResultCode;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.apache.shiro.web.util.WebUtils; import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;
import java.io.PrintWriter; /**
* 自定义登录filter
*/
public class AuthenticationFilter extends FormAuthenticationFilter {
@Override
protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request, ServletResponse response) throws Exception {
WebUtils.getAndClearSavedRequest(request);
SysUser user = (SysUser) SecurityUtils.getSubject().getPrincipal();
Result result = new Result(true, ResultCode.SUCCESS_LOGIN.getCode(), ResultCode.SUCCESS_LOGIN.getMessage(), user);
responseOutWithJson(response,result);
return false;
} /**
* 以JSON格式输出
* @param response
*/
protected void responseOutWithJson(ServletResponse response, Object responseObject) {
String jsonString= JSONObject.toJSONString(responseObject);
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json; charset=utf-8");
PrintWriter out = null;
try {
out = response.getWriter();
out.append(jsonString);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (out != null) {
out.close();
}
}
}
}
2.加入过虑器链
package com.creatunion.callcenter.config; import com.creatunion.callcenter.filter.AuthenticationFilter;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
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.LinkedHashMap;
import java.util.Map;
import java.util.Properties; @Configuration
public class ShiroConfig {
@Bean
public ShiroFilterFactoryBean shirFilter(SecurityManager securityManager) {
System.out.println("ShiroConfiguration.shirFilter()");
ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
shiroFilterFactoryBean.setSecurityManager(securityManager);
//拦截器.
Map<String,String> filterChainDefinitionMap = new LinkedHashMap<String,String>();
// 配置不会被拦截的链接 顺序判断
filterChainDefinitionMap.put("/static/**", "anon");
//配置退出 过滤器,其中的具体的退出代码Shiro已经替我们实现了
//filterChainDefinitionMap.put("/logout", "logout");
//<!-- 过滤链定义,从上向下顺序执行,一般将/**放在最为下边 -->:这是一个坑呢,一不小心代码就不好使了;
//<!-- authc:所有url都必须认证通过才可以访问; anon:所有url都都可以匿名访问-->
filterChainDefinitionMap.put("/**", "authc");
// 如果不设置默认会自动寻找Web工程根目录下的"/login.jsp"页面
shiroFilterFactoryBean.setLoginUrl("/login"); // 登录成功后要跳转的链接
//shiroFilterFactoryBean.setSuccessUrl("http://27.185.2.218:81/callcenter/loginSuccess"); //未授权界面;
shiroFilterFactoryBean.setUnauthorizedUrl("/403");
shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap); Map<String, Filter> filterMap = new LinkedHashMap<>(8);
// 这里只能使用 new 新建实例
//map里面key值要为authc才能使用自定义的过滤器
filterMap.put("authc", new AuthenticationFilter());
shiroFilterFactoryBean.setFilters(filterMap);
return shiroFilterFactoryBean;
} /**
* 凭证匹配器
* (由于我们的密码校验交给Shiro的SimpleAuthenticationInfo进行处理了
* )
* @return
*/
@Bean
public HashedCredentialsMatcher hashedCredentialsMatcher(){
HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();
hashedCredentialsMatcher.setHashAlgorithmName("md5");//散列算法:这里使用MD5算法;
hashedCredentialsMatcher.setHashIterations(2);//散列的次数,比如散列两次,相当于 md5(md5(""));
return hashedCredentialsMatcher;
} @Bean
public MyShiroRealm myShiroRealm(){
MyShiroRealm myShiroRealm = new MyShiroRealm();
myShiroRealm.setCredentialsMatcher(hashedCredentialsMatcher());
return myShiroRealm;
} @Bean
public SecurityManager securityManager(){
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
securityManager.setRealm(myShiroRealm());
return securityManager;
} /**
* 开启shiro aop注解支持.
* 使用代理方式;所以需要开启代码支持;
* @param securityManager
* @return
*/
@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;
}
}
shiro 自定义filter的更多相关文章
- 解决shiro自定义filter后,ajax登录无法登录,并且无法显示静态资源的问题
这个问题困扰了我一天,看了下面两个文章,豁然开朗: https://www.cnblogs.com/gj1990/p/8057348.html https://412887952-qq-com.ite ...
- shiro 返回json字符串 + 自定义filter
前言: 在前后端分离的项目中, 在使用shiro的时候, 我们绝大部分时候, 并不想让浏览器跳转到那个页面去, 而是告诉前端, 你没有登录, 或者没有访问权限. 那这时候, 我们就需要返回json字符 ...
- 细说shiro之自定义filter
写在前面 我们知道,shiro框架在Java Web应用中使用时,本质上是通过filter方式集成的. 也就是说,它是遵循过滤器链规则的:filter的执行顺序与在web.xml中定义的顺序一致,如下 ...
- 解决Shiro+SpringBoot自定义Filter不生效问题
在SpringBoot+Shiro实现安全框架的时候,自定义扩展了一些Filter,并注册到ShiroFilter,但是运行的时候发现总是在ShiroFilter之前就进入了自定义Filter,结果当 ...
- Shiro权限管理框架(五):自定义Filter实现及其问题排查记录
明确需求 在使用Shiro的时候,鉴权失败一般都是返回一个错误页或者登录页给前端,特别是后台系统,这种模式用的特别多.但是现在的项目越来越多的趋向于使用前后端分离的方式开发,这时候就需要响应Json数 ...
- Shiro自定义过滤器
项目中需要所有首次登录的用户必须修改密码才可使用系统,项目采用的是Shiro框架. 突然想到了配置文件org.apache.shiro.spring.web.ShiroFilterFactoryBea ...
- Shiro的Filter机制详解---源码分析
Shiro的Filter机制详解 首先从spring-shiro.xml的filter配置说起,先回答两个问题: 1, 为什么相同url规则,后面定义的会覆盖前面定义的(执行的时候只执行最后一个). ...
- shiro【filter】
alt+7 OncePerRequestFilter public final void doFilter(ServletRequest request, ServletResponse respon ...
- shiro自定义拦截url
在实际项目上,我们针对不同的用户(guste,user,admin,mobile user)等等,需要进入不同的页面,比如,手机端用户需要进入Mobile/这个路径下的,这个时候,我们需要自定义拦截u ...
随机推荐
- 百度URL链接中文转码
百度搜索链接规则为: http://www.baidu.com/s?wd=[搜索词目]&cl=3 有多个搜索词通过加号进行链接: http://www.baidu.com/s?wd=keywo ...
- 1 .net 用事物提交执行存储过程
public static void delModelReturn(string performanceId,DateTime? effectiveDate=null) { using (SqlCon ...
- Java学习笔记【四、类、对象、接口】
编程语言的发展 机器语言 过程语言 面向对象编程--封装.继承.多态 关键字 extends implements override overload super this static abstra ...
- 安装openblas库
http://www.openblas.net/ Linux:下载源码直接make即可
- Java 访问 C++ 方法:JavaCPP
JavaCPP提供了在Java中高效访问本地C++的方法.采用JNI技术实现,支持所有Java实现包括Android系统,Avian 和 RoboVM. JavaCPP提供了一系列的Annotatio ...
- linux使用nginx配置web服务器
环境: CenterOS 7 1.安装nginx之前先安装nginx所需的依赖包 yum -y install zlib zlib-devel openssl openssl-devel pcre p ...
- JSON parse error: syntax error, expect {, actual error, pos 0, fastjson-version 1.2.58; nested exception is com.alibaba.fastjson.JSONExcetion: syntax error, except {, actual error, pos ...
这个报错信息告诉你,你提交的参数需要是json类型.所以,POST请求携带的数据需要序列化一下json.dumps(data).
- Summer training #7
B:读懂题意模拟 #include <bits/stdc++.h> #include <cstring> #include <iostream> #include ...
- 【转】关于 Ruby 解释器:一些你需要知道的
关于 Ruby 解释器:一些你需要知道的 原文:Ruby Interpreters: What You Need to Know 使用正确的 Ruby 解释器来运行程序可以发挥重要作用,不幸的是很难找 ...
- [Ahoi2009]self 同类分布
1799: [Ahoi2009]self 同类分布 Time Limit: 50 Sec Memory Limit: 64 MBSubmit: 2357 Solved: 1079[Submit][ ...