<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                ??一站式輕松地調用各大LLM模型接口,支持GPT4、智譜、豆包、星火、月之暗面及文生圖、文生視頻 廣告
                http://blog.csdn.net/goodyuedandan/article/details/52176668 前幾個月在做一個常規的權限隔離功能的時候,恰好使用過Apache Shiro. Apache Shiro 是一款Java的安全框架,通常用作Web應用的權限校驗,身份驗證. > Apache Shiro is a powerful and easy-to-use Java security framework that performs authentication, > authorization, cryptography, and session management. With Shiro’s easy-to-understand API, you > can quickly and easily secure any application – from the smallest mobile applications to the > largest web and enterprise applications. 在參考過 IBM 開發社區關于Shiro的博客 一篇文章?[在Web項目中應用Apache Shiro](http://www.ibm.com/developerworks/cn/java/j-lo-shiro/) 與開濤博客的一個跟我學Shiro系列文章?[開濤博客-跟我學Shiro](http://jinnianshilongnian.iteye.com/blog/2024723) > 不得不說的是IBM Developer社區的文章一向屬于生動易懂. > 但是上面的這篇講得并沒有之前推薦的講Spring-DataJPA的那篇文章那樣淺顯, > 于是才有了現在這份筆記 ## [](http://blog.aquariuslt.com/2015/10/25/apache-shiro-spring-integration/#權限控制 "權限控制")權限控制 我所接觸到的權限控制大概可以分成兩個級別 URL和方法級別. 以常見的論壇用戶來舉例.論壇用戶簡要的分成兩種 管理員`Admin`,普通用戶`Normal`. 其中管理員能夠進入用戶管理,帖子管理的頁面進行CRUD操作. 普通用戶則只能進行自己帖子的CRU操作,以及頂貼什么的. 如果只進行URL級別的攔截,只需要在每一個URL的訪問時 獲取用戶的角色是`Admin`還是`Normal`即可. 如果是進行方法級別的攔截,則可能根據功能的設計衍生出很多設計方案(一眼就能想到的大概是樹狀,平行等). 但是由于跟數據庫的設計密切相關,所以這個級別不細講. 言歸正傳(不知道是不是看light大大博客看多了,語氣有點奇怪),下面結合上面的論壇用戶的一個場景進行邏輯與代碼的講解 ### [](http://blog.aquariuslt.com/2015/10/25/apache-shiro-spring-integration/#URL級別的權限控制 "URL級別的權限控制")URL級別的權限控制 #### [](http://blog.aquariuslt.com/2015/10/25/apache-shiro-spring-integration/#業務場景假設 "業務場景假設")業務場景假設 首先,我們假設有以下幾種種URL | 1 2 3 4 | /user/create //用戶創建,Admin專屬 /post/create //發帖 Admin,Normal共有 /login //登陸 /logout //注銷 | #### [](http://blog.aquariuslt.com/2015/10/25/apache-shiro-spring-integration/#Shiro基本配置 "Shiro基本配置")Shiro基本配置 ##### [](http://blog.aquariuslt.com/2015/10/25/apache-shiro-spring-integration/#Maven "Maven")Maven `$<shiro.version>`請自行替換成當前的最新版本 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | dependency> groupId>org.apache.shirogroupId> artifactId>shiro-coreartifactId> version>${shiro.version}version> dependency> dependency> groupId>org.apache.shirogroupId> artifactId>shiro-springartifactId> version>${shiro.version}version> dependency> dependency> groupId>org.apache.shirogroupId> artifactId>shiro-webartifactId> version>${shiro.version}version> dependency> dependency> groupId>org.apache.shirogroupId> artifactId>shiro-ehcacheartifactId> version>${shiro.version}version> dependency> | ##### [](http://blog.aquariuslt.com/2015/10/25/apache-shiro-spring-integration/#web-xml "web.xml")web.xml 為了實現與Spring同一個級別的URL攔截,需要將Shiro的Filter配置在Spring MVC的Dispatcher Servlet同一個級別 | 1 2 3 4 5 6 7 8 9 10 11 12 | filter> filter-name>shiroFilterfilter-name> filter-class>org.springframework.web.filter.DelegatingFilterProxyfilter-class> init-param> param-name>targetFilterLifecycleparam-name> param-value>trueparam-value> init-param> filter> filter-mapping> filter-name>shiroFilterfilter-name> url-pattern>/*url-pattern> filter-mapping> | ##### [](http://blog.aquariuslt.com/2015/10/25/apache-shiro-spring-integration/#Spring-ApplicationContext-xml "Spring ApplicationContext.xml")Spring ApplicationContext.xml 在與Spring進行整合的時候,為了方便拼切配置,在Spring 里面導入另一份專用于Shiro的xml配置 | 1 | import resource="config/security/applicationContext-shiro-captcha.xml"/> | ##### [](http://blog.aquariuslt.com/2015/10/25/apache-shiro-spring-integration/#Spring-applicationContext-shiro-captcha-xml "Spring applicationContext-shiro-captcha.xml")Spring applicationContext-shiro-captcha.xml 先將整個 shiro的xml配置貼出來,接下來在逐一解說其內容 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 | xml version="1.0" encoding="UTF-8"?> beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd" default-lazy-init="true"> description>Shiro安全配置description> bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager"> property name="realm" ref="shiroRealm"/> property name="cacheManager" ref="shiroEhcacheManager"/> bean> bean id="shiroRealm" class="com.quariuslt.service.security.BookingShiroRealm"> property name="loginSessionService" ref="loginSessionService"/> property name="userService" ref="userService"/> property name="cacheManager" ref="shiroEhcacheManager"/> bean> bean id="shiroEhcacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager"> property name="cacheManagerConfigFile" value="classpath:config/security/ehcache-shiro.xml"/> bean> bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/> bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor"> property name="securityManager" ref="securityManager"/> bean> bean id="captchaFilter" class="com.quariuslt.service.security.CaptchaFormAuthenticationFilter"/> bean id="adminPermissionFilter" class="com.quariuslt.service.security.AdminPermissionFilter"/> bean id="normalPermissionFilter" class="com.quariuslt.service.security.NormalPermissionFilter"/> bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean"> property name="securityManager" ref="securityManager"/> property name="loginUrl" value="/login"/> property name="successUrl" value="/booking/search"/> property name="unauthorizedUrl" value="/"/> property name="filters"> map> entry key="authc" value-ref="captchaFilter"/> --> --> map> property> property name="filterChainDefinitions"> value> /=authc /register = anon /forgot =anon /login = anon /login/action* = anon /logout = logout /js/** = anon /rest/**=anon /image/**=anon /jawr_loader.js=anon /user/create=roles[admin] /post/create/**=roles[normal|admin] /** =authc value> property> bean> beans> | #### [](http://blog.aquariuslt.com/2015/10/25/apache-shiro-spring-integration/#配置詳解 "配置詳解")配置詳解 首先要理解一件事情,就是Shiro的權限控制 源自于Web.xml的Filter,在Filter中獲取目標URL的請求,解析以達到根據請求是否到達下一集Filter的作用. 再要理解一件約定大于配置的問題,了解Shiro的一些默認配置解說. 在貼出來的`shiro-captcha.xml`配置代碼中: | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean"> property name="securityManager" ref="securityManager"/> property name="loginUrl" value="/login"/> property name="successUrl" value="/booking/search"/> property name="unauthorizedUrl" value="/"/> property name="filters"> map> entry key="authc" value-ref="captchaFilter"/> --> --> map> property> property name="filterChainDefinitions"> value> /=authc /register = anon /forgot =anon /login = anon /login/action* = anon /logout = logout /js/** = anon /rest/**=anon /image/**=anon /jawr_loader.js=anon /user/create=roles[admin] /post/create/**=roles[normal|admin] /** =authc value> property> bean> | 先來看`<property name="filterChainDefinitions">`中的屬性. 的內容,其實是url對應權限的一些mapping.表示對應的url mapping 需要對應的權限. 其中`authc`,`anon`,`logout`樣例中提及的這三個,是Shiro自己的默認配置 > `authc`表示,這這個mapping代表的url需要登陸之后才能查看 > `anon`表示,這個mapping代表的url全部放行,所以可以看到所有js文件與image文件都被放行了 > `logout`?表示這個mapping代表的url將進行一次注銷操作,在瀏覽器客戶端進行的是session的注銷,在服務器端則是進行緩存的刪除 其中?`roles[admin],roles[normal|admin]`?則是自己定義的過濾規則. 表示`/user/create`只有角色包含`admin`的有權限訪問 且`/post/create`則是角色是`admin`或`normal`的有權限訪問 ##### [](http://blog.aquariuslt.com/2015/10/25/apache-shiro-spring-integration/#登錄與注銷 "登錄與注銷")登錄與注銷 ###### [](http://blog.aquariuslt.com/2015/10/25/apache-shiro-spring-integration/#登錄 "登錄")登錄 對于所有需要登錄的URL可以通過?`authc`一個攔截器來攔截 在未登錄的狀態下,所有所有需要登錄的URL都是自動跳轉到上面XML所配置的`loginUrl`之中. 當然這里返回的是 一個對?`/login`路徑的get請求 | 1 | property name="loginUrl" value="/login"/> | ###### [](http://blog.aquariuslt.com/2015/10/25/apache-shiro-spring-integration/#注銷 "注銷")注銷 注銷也很簡單,只要任意url能夠跳轉到`/logout`,便會自動注銷. ##### [](http://blog.aquariuslt.com/2015/10/25/apache-shiro-spring-integration/#同步登錄與異步登陸 "同步登錄與異步登陸")同步登錄與異步登陸 其實在Shiro的配置中,通過閱讀源碼可以看出,其實`loginUrl`一個屬性,代表的是 當Method=Get的請求到達其值對應的url(/login)時,返回登錄的頁面. 當Method=Post的請求到達其值對應的url(/login)時,進入到的就是Shiro本身的登陸操作 該操作,通過讀取`securityManager`的配置, | 1 | property name="securityManager" ref="securityManager"/> | 通過自定義的realm?`BookingShiroRealm` > 此處`BookingShiroRealm`是自己定義的名稱,只是為了符合但是的業務需要起的名字 | 1 2 3 4 5 6 7 8 9 10 11 12 | bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager"> property name="realm" ref="shiroRealm"/> property name="cacheManager" ref="shiroEhcacheManager"/> bean> bean id="shiroRealm" class="com.quariuslt.service.security.BookingShiroRealm"> property name="loginSessionService" ref="loginSessionService"/> property name="userService" ref="userService"/> property name="cacheManager" ref="shiroEhcacheManager"/> bean> | 接下來解說一下 `BookingShiroRealm.java` 的內容 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 | public class BookingShiroRealm extends AuthorizingRealm { public static final String LOGIN_SESSION_NAME="loginSession"; public static final String SIMPLE_AUTHORIZATION_INFO="simpleAuthorizationInfo"; private LoginSessionService loginSessionService; private UserService userService; public LoginSessionService getLoginSessionService() { return loginSessionService; } public void setLoginSessionService(LoginSessionService loginSessionService) { this.loginSessionService = loginSessionService; } public UserService getUserService() { return userService; } public void setUserService(UserService userService) { this.userService = userService; } /*授權信息*/ @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) { LoginSession loginSession = (LoginSession) principals.fromRealm(getName()).iterator().next(); if(SecurityUtils.getSubject().getSession().getAttribute(LOGIN_SESSION_NAME)==null){ SecurityUtils.getSubject().getSession().setAttribute(LOGIN_SESSION_NAME, loginSession); } if(SecurityUtils.getSubject().getSession().getAttribute(SIMPLE_AUTHORIZATION_INFO)==null){ UserDto userDto=userService.findUserById(loginSession.getUserId()); if (userDto != null) { SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(); Set roleDtoSet=userService.getUserRolesByUserId(userDto.getId()); for(RoleDto roleDto:roleDtoSet){ info.addRole(roleDto.getName().toLowerCase()); } SecurityUtils.getSubject().getSession().setAttribute(SIMPLE_AUTHORIZATION_INFO, info); } else { return null; } } return (AuthorizationInfo)SecurityUtils.getSubject().getSession().getAttribute(SIMPLE_AUTHORIZATION_INFO); } /*認證信息*/ @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException { System.out.println("Come to BookingShiroRealm"); UsernamePasswordToken token=(UsernamePasswordToken)authenticationToken; String userId=token.getUsername(); String cryptedPassword= String.valueOf(token.getPassword()); if(StringUtils.isNotEmpty(userId)){ UserDto targetUser=userService.getByUserId(userId); System.out.println("TargetUser:"+userId+" InputPassWord:"+cryptedPassword+" DB PassWord:"+targetUser.getCryptedPassword()); if(cryptedPassword.equals(targetUser.getCryptedPassword())){ System.out.println("BookingShiroRealm:Login Success"); LoginSession loginSession=new LoginSession(targetUser.getId(), targetUser.getUserId(),targetUser.getEmail(),SecurityUtils.getSubject().getSession().getHost()); loginSessionService.clearSessionByUserId(userId); loginSessionService.save(loginSession); return new SimpleAuthenticationInfo(loginSession,targetUser.getCryptedPassword().toCharArray(),getName()); } } return null; } } | `AuthorizingRealm`是Shiro負責身份認證的抽象類. 需要實現其`doGetAuthenticationInfo`方法,實現 對提交過來的用戶名/密碼 等賬號信息,跟數據庫進行交互判定登陸是否成功的過程. 和實現其`doGetAuthorizationInfo`方法,實現對需要登陸之后 對權限的認證. 在說到登陸的校驗之前,可以看到在`doGetAuthenticationInfo`方法里面 有一個authenticationToken.里面包含了登陸傳遞過來的用戶名和密碼信息.這里又是怎么來的呢. 此時返回來回到Spring配置Shiro的xml?`applicationContext-shiro-captcha.xml` 會發現 | 1 2 3 4 5 6 7 | property name="filters"> map> entry key="authc" value-ref="captchaFilter"/> entry key="roles[admin]" value-ref="captchaFilter"/> entry key="roles[normal]" value-ref="captchaFilter"/> map> property> | 里面會有一個`captchaFilter`, 指向其注入的類?`CaptchaFormAuthenticationFilter.java` 附上`CaptchaFormAuthenticationFilter`代碼 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 | public class CaptchaFormAuthenticationFilter extends FormAuthenticationFilter { public static final String DEFAULT_CAPTCHA_PARAM = "captcha"; private String captchaParam = DEFAULT_CAPTCHA_PARAM; public String getCaptchaParam() { return captchaParam; } protected String getCaptcha(ServletRequest request) { return WebUtils.getCleanParam(request, getCaptchaParam()); } @Override protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) { setFailureAttribute(request, e); return true; } @Override protected void setFailureAttribute(ServletRequest request, AuthenticationException ae) { String className = ae.getClass().getName(); request.setAttribute(getFailureKeyAttribute(), className); } //這里進行密碼的加密 @Override protected CaptchaUsernamePasswordToken createToken(ServletRequest request, ServletResponse response) { System.out.println("Come to CreateToken"); String username = getUsername(request); String password = getPassword(request); String captcha = getCaptcha(request); boolean rememberMe = isRememberMe(request); String host = getHost(request); System.out.println("Captcha UserName(UserId):" + username); System.out.println("Captcha Password:" + password); System.out.println("Captcha RememberMe:" + rememberMe); return new CaptchaUsernamePasswordToken(username, password.toCharArray(), rememberMe, host, captcha); } @Override protected boolean executeLogin(ServletRequest request, ServletResponse response) throws Exception { CaptchaUsernamePasswordToken token = createToken(request, response); try { System.out.println("Execute Login~"); Subject subject = getSubject(request, response); subject.login(token); return onLoginSuccess(token,subject, request, response); } catch (AuthenticationException e) { return onLoginFailure(token,e, request, response); } } } | 繼承`FormAuthenticationFilter`的`CaptchaFormAuthenticationFilter`并重寫其`CaptchaUsernamePasswordToken`方法. 用于通過`/login`的POST方式提交過來的時候,便會先經過此filter的`createToken`方法進行token的生成 假設有一個登陸頁面的`/login`使用同步提交方式,即通過頁面的form表單,`action="/login"`,`method="POST"`提交到后臺,觸發流程是 > 1. 到達?`FormAuthenticationFilter`?根據表單 生成Token. > 2. 調用 Shiro專門處理認證的?`subject`其`login`方法進行登陸 > 3. `login`方法 通過調用 自定義的`BookingShiroRealm`方法所實現的頂級接口 來實現對數據庫的信息的讀取 > 4. 判定登陸用戶名與密碼 匹配之后,可以通過Shiro自己配置的緩存保存認證信息. 但是在這個時代,還通過同步登陸 實在是太TM撈了,其實異步登陸提交,只需要 手動調用subject.login方法即可 將第一步到達`FormAuthenticationFilter`的token手動生成 異步登陸的實現代碼 大概如下(以Controller為例) | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 | @RequestMapping(value = "/action", method = RequestMethod.POST,produces = MediaType.APPLICATION_JSON_VALUE) @ResponseBody public LoginMessage loginAction( @RequestParam(value = "username") String username, @RequestParam(value = "password") String password, @RequestParam(value = "rememberMe", required = false, defaultValue = "false") boolean rememberMe, ServletRequest request) { LoginMessage loginMessage = new LoginMessage(BKGConstants.ActionStatus.FAILURE.getDescription()); Subject subject = SecurityUtils.getSubject(); //嘗試獲取 跳轉到Login前的那個頁面的url if(null != WebUtils.getSavedRequest(request)) { String requestURI= WebUtils.getSavedRequest(request).getRequestURI(); loginMessage.setRedirect(requestURI); } try { String salt=userService.getByUserId(username).getSalt(); UsernamePasswordToken token = new UsernamePasswordToken(username, EncryptUtil.encrypt(password,salt)); subject.login(token); loginMessage.setStatus(BKGConstants.ActionStatus.SUCCESS.getDescription()); //嘗試判斷 用戶是不是第一次登陸 UserDto currentUser=userService.getByUserId(username); if (currentUser.getActive().equals(BKGConstants.UserAccountStatus.FIRST_LOGIN.getIndex())){ String redirectPath=request.getServletContext().getContextPath()+"/user/password/reset"; loginMessage.setRedirect(redirectPath); } } catch (UnknownAccountException e) { loginMessage.setMessage(BKGConstants.LoginFailureMessage.PASSWORD_WRONG.getDescription()); } catch (IncorrectCredentialsException |NullPointerException e) { loginMessage.setMessage(BKGConstants.LoginFailureMessage.USER_NOT_EXIST.getDescription()); } catch (AuthenticationException e) { loginMessage.setMessage(BKGConstants.LoginFailureMessage.ACCOUNT_LOCK.getDescription()); } return loginMessage; } class LoginMessage { private String status; private String message; private String redirect; public LoginMessage(String status) { this.status = status; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public String getRedirect() { return redirect; } public void setRedirect(String redirect) { this.redirect = redirect; } } | ##### [](http://blog.aquariuslt.com/2015/10/25/apache-shiro-spring-integration/#角色校驗 "角色校驗")角色校驗 登陸的時候,其實只是實現了?`登陸認證`,`緩存登錄信息`的過程. 并沒有實現,`權限賦予`的過程.只有第一次遇到 需要登陸且特定權限的url的時候,才會請求后臺是否有進入對應url的權限. 在講權限之前,概括一下數據庫的設計 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 | CREATE TABLE USERS ( ID BIGINT PRIMARY KEY NOT NULL AUTO_INCREMENT, ACTIVE BIT NOT NULL, ADDRESS VARCHAR(300), CITY VARCHAR(50), COMPANY VARCHAR(20), COUNTRY VARCHAR(50), CRYPTED_PASSWORD VARCHAR(255), DEPARTMENT VARCHAR(20), DISPLAY_NAME VARCHAR(128), EMAIL VARCHAR(60) NOT NULL, FAX VARCHAR(100), FIRST_NAME VARCHAR(40), GENDER VARCHAR(6), JOBTITLE VARCHAR(100), LAST_NAME VARCHAR(40), LOCATION VARCHAR(50), MIDDLE_NAME VARCHAR(40), OFFICE VARCHAR(20), OFFICECODE VARCHAR(22), PHONE VARCHAR(128), SALT VARCHAR(255) NOT NULL, STAFFID VARCHAR(20), STAFFROLE VARCHAR(15), TERRITORY VARCHAR(100), USERID VARCHAR(20) NOT NULL ); CREATE TABLE ROLES ( ID BIGINT PRIMARY KEY NOT NULL AUTO_INCREMENT, DESCRIPTION VARCHAR(255), NAME VARCHAR(255) NOT NULL ); CREATE UNIQUE INDEX UK_OFX66KERUAPI6VYQPV6F2OR37 ON ROLES (NAME); CREATE TABLE ROLE_USER ( ROLE_ID BIGINT NOT NULL, USER_ID BIGINT NOT NULL, PRIMARY KEY (ROLE_ID, USER_ID), FOREIGN KEY (ROLE_ID) REFERENCES ROLES (ID), FOREIGN KEY (USER_ID) REFERENCES USERS (ID) ); CREATE INDEX FK_NJAJEL6A2Q8TR36EMB9L8VW7N ON ROLE_USER (USER_ID); | 數據庫有三個表?`USERS`,`ROLES`,`USER_ROLE` 其實在設計上`User`表跟`ROLE`表是多對多的關系,即User里面有一個Set,Role里面也有一個Set 通過中間表`USER_ROLE`來實現多對多關聯. 下面來看 身份認證的具體實現 `BookingShiroRealm.java` | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) { LoginSession loginSession = (LoginSession) principals.fromRealm(getName()).iterator().next(); if(SecurityUtils.getSubject().getSession().getAttribute(LOGIN_SESSION_NAME)==null){ SecurityUtils.getSubject().getSession().setAttribute(LOGIN_SESSION_NAME, loginSession); } if(SecurityUtils.getSubject().getSession().getAttribute(SIMPLE_AUTHORIZATION_INFO)==null){ UserDto userDto=userService.findUserById(loginSession.getUserId()); if (userDto != null) { SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(); Set roleDtoSet=userService.getUserRolesByUserId(userDto.getId()); for(RoleDto roleDto:roleDtoSet){ info.addRole(roleDto.getName().toLowerCase()); } SecurityUtils.getSubject().getSession().setAttribute(SIMPLE_AUTHORIZATION_INFO, info); } else { return null; } } return (AuthorizationInfo)SecurityUtils.getSubject().getSession().getAttribute(SIMPLE_AUTHORIZATION_INFO); } | 通過 | 1 | Subject.getSession().setAttribute(SIMPLE_AUTHORIZATION_INFO,info) | 來實現一個 根據通過已經登陸的用戶,獲取其在數據庫中所具有的角色的名字的集合 生成字符串,然后存在Session里面. 當需要對應的權限,且發現已經有`SIMPLE_AUTHORIZATION_INFO`這個屬性,則根據屬性中是否含有對應字符串的來判定是否有對應權限. 當然 對應權限的獲取,也是通過shiro 配置里面的captchaFilter的具體實現類,實現其`isAccessAllowed`方法來判定. ## [](http://blog.aquariuslt.com/2015/10/25/apache-shiro-spring-integration/#Summary "Summary")Summary 本次主要分享了Share 如何在Spring中整合Apache Shiro的過程. 但是整體配置依然是通過XML統一配置,其實Shiro在近期的版本已經有了Annotation級別的方法能夠方便的對URL的Mapping進行注解. 具體的應用過程,就像Spring 2.X 升級到 3.X 的過程一樣,但是由于沒有實戰,不便多說.
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看