最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

springboot整合shiro與自定義過濾器的全過程

 更新時間:2022年01月06日 09:12:55   作者:yx726843014  
這篇文章主要給大家介紹了關(guān)于springboot整合shiro與自定義過濾器以及Shiro中權(quán)限控制的相關(guān)資料,文中通過實例代碼介紹的非常詳細(xì),需要的朋友可以參考下

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);
    }
*/
    //用戶提交表單時候  創(chuàng)建的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是為了接收前臺發(fā)送過來的數(shù)據(jù)

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>();
        //驗證碼的路徑   不要跟下面需要認(rèn)證的寫在一個路徑里  會被攔截的
        map.put("/servlet/**", "anon");
        //需要把要授權(quán)的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;
    }

    //密碼鹽   可以不必實現(xiàn)    因為一般密碼可以自己定義自己的密碼加密規(guī)則
/*    @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");//數(shù)據(jù)庫異常處理
        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");
    }


    //自定義過濾器 ---》里面實現(xiàn)了對驗證碼校驗
    @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());
        //可以設(shè)置shiro提供的會話管理機(jī)制
        //defaultWebSessionManager.setSessionDAO(new EnterpriseCacheSessionDAO());
        return defaultWebSessionManager;
    }



    //這里就是會話管理的操作類
    @Bean
    public SessionDAO sessionDAO() {
        return new RedisSessionDao();
    }

    //這里需要設(shè)置一個cookie的名稱  原因就是會跟原來的session的id值重復(fù)的
    @Bean
    public SimpleCookie simpleCookie() {
        SimpleCookie simpleCookie = new SimpleCookie("REDISSESSION");
        return simpleCookie;
    }
}

Shiro中的權(quán)限控制

#需要同時擁有order:add和order:query權(quán)限才可以訪問
/order-add = perms["order:add","order:query"]
#只需要order:del權(quán)限就可以訪問
/order-del = perms["order:del"]

perms表示的就是權(quán)限控制,中括號中就是需要訪問等號之前路徑,需要的權(quán)限名稱。如果在使用Shiro過濾器的時候,不配置過濾器,就會使用默認(rèn)的過濾器。

以下是默認(rèn)權(quán)限過濾器的源碼。

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;
? ? }
}

從上面的代碼可以看出,我們的配置會默認(rèn)被強(qiáng)轉(zhuǎn)為string類型的字符串?dāng)?shù)組。當(dāng)只有一個權(quán)限時,會直接判斷有沒有該權(quán)限; 當(dāng)配置多個權(quán)限時,從下面的代碼可以看出只用在請求url的用戶擁有所有的權(quán)限時,才會返回true,否則就會被拒絕訪問。

總結(jié)

到此這篇關(guān)于springboot整合shiro與自定義過濾器的文章就介紹到這了,更多相關(guān)springboot整合shiro與自定義過濾器內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論

兴化市| 东莞市| 温宿县| 谢通门县| 扶风县| 龙南县| 乌兰察布市| 宝坻区| 佛山市| 乌审旗| 石泉县| 鄂托克旗| 藁城市| 高陵县| 论坛| 台东县| 霍邱县| 舞钢市| 宁河县| 榆中县| 德庆县| 微山县| 克山县| 玛纳斯县| 遂川县| 新干县| 锦屏县| 屏山县| 合肥市| 丰镇市| 霍山县| 富锦市| 沐川县| 陇西县| 宣城市| 张北县| 虎林市| 甘孜县| 隆化县| 长宁县| 瓦房店市|