国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 網(wǎng)站 > 幫助中心 > 正文

基于springboot實現(xiàn)整合shiro實現(xiàn)登錄認證以及授權(quán)過程解析

2024-07-09 22:42:46
字體:
供稿:網(wǎng)友

這篇文章主要介紹了基于springboot實現(xiàn)整合shiro實現(xiàn)登錄認證以及授權(quán)過程解析,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下

1.添加shiro的依賴

<dependency>  <groupId>org.apache.shiro</groupId>      <artifactId>shiro-spring-boot-web-         starter</artifactId>  <version>1.4.0</version></dependency>

2.先創(chuàng)建一個Realm

public class MyShiroRealm extends AuthorizingRealm {  @Autowired  private RoleService roleService;//角色模模塊  @Autowired  private UserService userService;//用戶模塊  @Autowired  private PermissionService permissionService;//權(quán)限模塊  /**   * 用戶身份識別(登錄")   * @param authenticationToken   * @return   * @throws AuthenticationException   */  @Override  protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {    UsernamePasswordToken authToken = (UsernamePasswordToken) authenticationToken;    // 獲取用戶輸入的賬號    String userName = authToken.getUsername();     //通過賬號查找用戶信息    User user= userService.selectUserOne(userName);// 將賬戶名,密碼,鹽值,getName()實例化到SimpleAuthenticationInfo中交給Shiro來管理    SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(                              user,                              user.getPassWord(),                                    //這里是設(shè)置的密碼鹽                              ByteSource.Util.bytes(user.getSalt()),                              getName());    return authenticationInfo;  }  /**   * 訪問控制。比如某個用戶是否具有某個操作的使用權(quán)限   * @param principalCollection   * @return   */  @Override  protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {    SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();    String userName = (String) principalCollection.getPrimaryPrincipal();    if (userName == null) {      log.error("授權(quán)失敗,用戶信息為空!!!");      return null;    }    try {      //獲取用戶角色集      Set<String> listRole= roleService.findRoleByUsername(userName);      simpleAuthorizationInfo.addRoles(listRole);      //通過角色獲取權(quán)限集      for (String role : listRole) {        Set<String> permission= permissionService.findPermissionByRole(role);        simpleAuthorizationInfo.addStringPermissions(permission);      }      return simpleAuthorizationInfo;    } catch (Exception e) {      log.error("授權(quán)失敗,請檢查系統(tǒng)內(nèi)部錯誤!!!", e);    }    return simpleAuthorizationInfo;  }}


3.創(chuàng)建shiro的配置類

@Configurationpublic class ShiroConfiguration {   //配置自定義的Realm  @Bean  public MyShiroRealm myShiroRealm(HashedCredentialsMatcher matcher){    MyShiroRealm myShiroRealm= new MyShiroRealm();     //在這里配置密碼加密    myShiroRealm.setCredentialsMatcher(matcher);    return myShiroRealm;  }   //將Realm注冊到securityManager中  @Bean  public DefaultWebSecurityManager securityManager(HashedCredentialsMatcher matcher){    DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();    securityManager.setRealm(myShiroRealm(matcher));    return securityManager;  }  //如果沒有此name,將會找不到shiroFilter的Bean  @Bean(name = "shiroFilter")  public ShiroFilterFactoryBean shiroFilter(org.apache.shiro.mgt.SecurityManager securityManager){    ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();    shiroFilterFactoryBean.setSecurityManager(securityManager);    shiroFilterFactoryBean.setLoginUrl("/login");     //表示指定登錄頁面    shiroFilterFactoryBean.setSuccessUrl("/user/list");  // 登錄成功后要跳轉(zhuǎn)的鏈接    shiroFilterFactoryBean.setUnauthorizedUrl("/403");  //未授權(quán)頁面    Map<String,String> filterChainDefinitionMap = new LinkedHashMap<>();//攔截器, 配置不會被攔截的鏈接 順序判斷    filterChainDefinitionMap.put("/login","anon");           //所有匿名用戶均可訪問到Controller層的該方法下    filterChainDefinitionMap.put("/userLogin","anon");    filterChainDefinitionMap.put("/image/**","anon");    filterChainDefinitionMap.put("/css/**", "anon");    filterChainDefinitionMap.put("/fonts/**","anon");    filterChainDefinitionMap.put("/js/**","anon");    filterChainDefinitionMap.put("/logout","logout");    filterChainDefinitionMap.put("/**", "authc"); //authc:所有url都必須認證通過才可以訪問; anon:所有url都都可以匿名訪問    //filterChainDefinitionMap.put("/**", "user");    //user表示配置記住我或認證通過可以訪問的地址    shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);    return shiroFilterFactoryBean;  }  /**   * SpringShiroFilter首先注冊到spring容器   * 然后被包裝成FilterRegistrationBean   * 最后通過FilterRegistrationBean注冊到servlet容器   * @return   */  @Bean  public FilterRegistrationBean delegatingFilterProxy(){    FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();    DelegatingFilterProxy proxy = new DelegatingFilterProxy();    proxy.setTargetFilterLifecycle(true);    proxy.setTargetBeanName("shiroFilter");    filterRegistrationBean.setFilter(proxy);    return filterRegistrationBean;  }  //設(shè)置cookie  @Bean  public SimpleCookie rememberMeCookie(){    //這個參數(shù)是cookie的名稱,對應(yīng)前端的checkbox的name=rememberMe    SimpleCookie simpleCookie = new SimpleCookie("rememberMe");    //記住我cookie生效時間3個小時(單位秒)    simpleCookie.setMaxAge(10800);    return simpleCookie;  }  //cookie管理對象,記住我功能  @Bean  public CookieRememberMeManager rememberMeManager(){    CookieRememberMeManager cookieRememberMeManager = new CookieRememberMeManager();    cookieRememberMeManager.setCookie(rememberMeCookie());    return cookieRememberMeManager;  }  /**   * 密碼匹配憑證管理器(密碼加密需要此配置)   * @return   */  @Bean(name = "hashedCredentialsMatcher")  public HashedCredentialsMatcher hashedCredentialsMatcher() {    HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();    hashedCredentialsMatcher.setHashAlgorithmName("MD5");    hashedCredentialsMatcher.setHashIterations(1024);// 設(shè)置加密次數(shù)    return hashedCredentialsMatcher;  }  //如果沒有這兩個配置,可能會授權(quán)失敗,所以依賴中還需要配置aop的依賴  @Bean  public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(HashedCredentialsMatcher matcher) {    AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();    authorizationAttributeSourceAdvisor.setSecurityManager(securityManager(matcher));    return authorizationAttributeSourceAdvisor;  }  @Bean  @ConditionalOnMissingBean  public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator(){    DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator=new DefaultAdvisorAutoProxyCreator();    defaultAdvisorAutoProxyCreator.setProxyTargetClass(true);    return defaultAdvisorAutoProxyCreator;  }}
發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 梧州市| 灯塔市| 黑水县| 溧阳市| 什邡市| 南昌县| 合作市| 鹤庆县| 紫阳县| 常德市| 长治市| 珠海市| 家居| 龙胜| 宜兴市| 赤壁市| 衡山县| 诸城市| 三明市| 瑞安市| 特克斯县| 福贡县| 保德县| 波密县| 惠州市| 石景山区| 桂林市| 郁南县| 师宗县| 广灵县| 清水河县| 罗定市| 扎赉特旗| 荃湾区| 称多县| 巧家县| 兴安盟| 当涂县| 楚雄市| 白山市| 商丘市|