shiro無狀態(tài)web集成的示例代碼
在一些環(huán)境中,可能需要把Web應(yīng)用做成無狀態(tài)的,即服務(wù)器端無狀態(tài),就是說服務(wù)器端不會存儲像會話這種東西,而是每次請求時帶上相應(yīng)的用戶名進行登錄。如一些REST風(fēng)格的API,如果不使用OAuth2協(xié)議,就可以使用如REST+HMAC認證進行訪問。HMAC(Hash-based Message Authentication Code):基于散列的消息認證碼,使用一個密鑰和一個消息作為輸入,生成它們的消息摘要。注意該密鑰只有客戶端和服務(wù)端知道,其他第三方是不知道的。訪問時使用該消息摘要進行傳播,服務(wù)端然后對該消息摘要進行驗證。如果只傳遞用戶名+密碼的消息摘要,一旦被別人捕獲可能會重復(fù)使用該摘要進行認證。解決辦法如:
1、每次客戶端申請一個Token,然后使用該Token進行加密,而該Token是一次性的,即只能用一次;有點類似于OAuth2的Token機制,但是簡單些;
2、客戶端每次生成一個唯一的Token,然后使用該Token加密,這樣服務(wù)器端記錄下這些Token,如果之前用過就認為是非法請求。
為了簡單,本文直接對請求的數(shù)據(jù)(即全部請求的參數(shù))生成消息摘要,即無法篡改數(shù)據(jù),但是可能被別人竊取而能多次調(diào)用。解決辦法如上所示。
服務(wù)器端
對于服務(wù)器端,不生成會話,而是每次請求時帶上用戶身份進行認證。
服務(wù)控制器
@RestController public class ServiceController { @RequestMapping("/hello") public String hello1(String[] param1, String param2) { return "hello" + param1[0] + param1[1] + param2; } }
當訪問/hello服務(wù)時,需要傳入param1、param2兩個請求參數(shù)。
加密工具類
com.github.zhangkaitao.shiro.chapter20.codec.HmacSHA256Utils:
//使用指定的密碼對內(nèi)容生成消息摘要(散列值) public static String digest(String key, String content); //使用指定的密碼對整個Map的內(nèi)容生成消息摘要(散列值) public static String digest(String key, Map<String, ?> map)
對Map生成消息摘要主要用于對客戶端/服務(wù)器端來回傳遞的參數(shù)生成消息摘要。
Subject工廠
public class StatelessDefaultSubjectFactory extends DefaultWebSubjectFactory { public Subject createSubject(SubjectContext context) { //不創(chuàng)建session context.setSessionCreationEnabled(false); return super.createSubject(context); } }
通過調(diào)用context.setSessionCreationEnabled(false)表示不創(chuàng)建會話;如果之后調(diào)用Subject.getSession()將拋出DisabledSessionException異常。
StatelessAuthcFilter
類似于FormAuthenticationFilter,但是根據(jù)當前請求上下文信息每次請求時都要登錄的認證過濾器。
public class StatelessAuthcFilter extends AccessControlFilter { protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception { return false; } protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception { //1、客戶端生成的消息摘要 String clientDigest = request.getParameter(Constants.PARAM_DIGEST); //2、客戶端傳入的用戶身份 String username = request.getParameter(Constants.PARAM_USERNAME); //3、客戶端請求的參數(shù)列表 Map<String, String[]> params = new HashMap<String, String[]>(request.getParameterMap()); params.remove(Constants.PARAM_DIGEST); //4、生成無狀態(tài)Token StatelessToken token = new StatelessToken(username, params, clientDigest); try { //5、委托給Realm進行登錄 getSubject(request, response).login(token); } catch (Exception e) { e.printStackTrace(); onLoginFail(response); //6、登錄失敗 return false; } return true; } //登錄失敗時默認返回401狀態(tài)碼 private void onLoginFail(ServletResponse response) throws IOException { HttpServletResponse httpResponse = (HttpServletResponse) response; httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED); httpResponse.getWriter().write("login error"); } }
獲取客戶端傳入的用戶名、請求參數(shù)、消息摘要,生成StatelessToken;然后交給相應(yīng)的Realm進行認證。
StatelessToken
public class StatelessToken implements AuthenticationToken { private String username; private Map<String, ?> params; private String clientDigest; //省略部分代碼 public Object getPrincipal() { return username;} public Object getCredentials() { return clientDigest;} }
用戶身份即用戶名;憑證即客戶端傳入的消息摘要。
StatelessRealm
用于認證的Realm。
public class StatelessRealm extends AuthorizingRealm { public boolean supports(AuthenticationToken token) { //僅支持StatelessToken類型的Token return token instanceof StatelessToken; } protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) { //根據(jù)用戶名查找角色,請根據(jù)需求實現(xiàn) String username = (String) principals.getPrimaryPrincipal(); SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo(); authorizationInfo.addRole("admin"); return authorizationInfo; } protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { StatelessToken statelessToken = (StatelessToken) token; String username = statelessToken.getUsername(); String key = getKey(username);//根據(jù)用戶名獲取密鑰(和客戶端的一樣) //在服務(wù)器端生成客戶端參數(shù)消息摘要 String serverDigest = HmacSHA256Utils.digest(key, statelessToken.getParams()); //然后進行客戶端消息摘要和服務(wù)器端消息摘要的匹配 return new SimpleAuthenticationInfo( username, serverDigest, getName()); } private String getKey(String username) {//得到密鑰,此處硬編碼一個 if("admin".equals(username)) { return "dadadswdewq2ewdwqdwadsadasd"; } return null; } }
此處首先根據(jù)客戶端傳入的用戶名獲取相應(yīng)的密鑰,然后使用密鑰對請求參數(shù)生成服務(wù)器端的消息摘要;然后與客戶端的消息摘要進行匹配;如果匹配說明是合法客戶端傳入的;否則是非法的。這種方式是有漏洞的,一旦別人獲取到該請求,可以重復(fù)請求;可以考慮之前介紹的解決方案。
Spring配置——spring-config-shiro.xml
<!-- Realm實現(xiàn) --> <bean id="statelessRealm" class="com.github.zhangkaitao.shiro.chapter20.realm.StatelessRealm"> <property name="cachingEnabled" value="false"/> </bean> <!-- Subject工廠 --> <bean id="subjectFactory" class="com.github.zhangkaitao.shiro.chapter20.mgt.StatelessDefaultSubjectFactory"/> <!-- 會話管理器 --> <bean id="sessionManager" class="org.apache.shiro.session.mgt.DefaultSessionManager"> <property name="sessionValidationSchedulerEnabled" value="false"/> </bean> <!-- 安全管理器 --> <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager"> <property name="realm" ref="statelessRealm"/> <property name="subjectDAO.sessionStorageEvaluator.sessionStorageEnabled" value="false"/> <property name="subjectFactory" ref="subjectFactory"/> <property name="sessionManager" ref="sessionManager"/> </bean> <!-- 相當于調(diào)用SecurityUtils.setSecurityManager(securityManager) --> <bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean"> <property name="staticMethod" value="org.apache.shiro.SecurityUtils.setSecurityManager"/> <property name="arguments" ref="securityManager"/> </bean>
sessionManager通過sessionValidationSchedulerEnabled禁用掉會話調(diào)度器,因為我們禁用掉了會話,所以沒必要再定期過期會話了。
<bean id="statelessAuthcFilter" class="com.github.zhangkaitao.shiro.chapter20.filter.StatelessAuthcFilter"/>
每次請求進行認證的攔截器。
<!-- Shiro的Web過濾器 --> <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean"> <property name="securityManager" ref="securityManager"/> <property name="filters"> <util:map> <entry key="statelessAuthc" value-ref="statelessAuthcFilter"/> </util:map> </property> <property name="filterChainDefinitions"> <value> /**=statelessAuthc </value> </property> </bean>
所有請求都將走statelessAuthc攔截器進行認證。
其他配置請參考源代碼。
客戶端
此處使用SpringMVC提供的RestTemplate進行測試。
此處為了方便,使用內(nèi)嵌jetty服務(wù)器啟動服務(wù)端:
public class ClientTest { private static Server server; private RestTemplate restTemplate = new RestTemplate(); @BeforeClass public static void beforeClass() throws Exception { //創(chuàng)建一個server server = new Server(8080); WebAppContext context = new WebAppContext(); String webapp = "shiro-example-chapter20/src/main/webapp"; context.setDescriptor(webapp + "/WEB-INF/web.xml"); //指定web.xml配置文件 context.setResourceBase(webapp); //指定webapp目錄 context.setContextPath("/"); context.setParentLoaderPriority(true); server.setHandler(context); server.start(); } @AfterClass public static void afterClass() throws Exception { server.stop(); //當測試結(jié)束時停止服務(wù)器 } }
在整個測試開始之前開啟服務(wù)器,整個測試結(jié)束時關(guān)閉服務(wù)器。
測試成功情況
@Test public void testServiceHelloSuccess() { String username = "admin"; String param11 = "param11"; String param12 = "param12"; String param2 = "param2"; String key = "dadadswdewq2ewdwqdwadsadasd"; MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>(); params.add(Constants.PARAM_USERNAME, username); params.add("param1", param11); params.add("param1", param12); params.add("param2", param2); params.add(Constants.PARAM_DIGEST, HmacSHA256Utils.digest(key, params)); String url = UriComponentsBuilder .fromHttpUrl("http://localhost:8080/hello") .queryParams(params).build().toUriString(); ResponseEntity responseEntity = restTemplate.getForEntity(url, String.class); Assert.assertEquals("hello" + param11 + param12 + param2, responseEntity.getBody()); }
對請求參數(shù)生成消息摘要后帶到參數(shù)中傳遞給服務(wù)器端,服務(wù)器端驗證通過后訪問相應(yīng)服務(wù),然后返回數(shù)據(jù)。
測試失敗情況
@Test public void testServiceHelloFail() { String username = "admin"; String param11 = "param11"; String param12 = "param12"; String param2 = "param2"; String key = "dadadswdewq2ewdwqdwadsadasd"; MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>(); params.add(Constants.PARAM_USERNAME, username); params.add("param1", param11); params.add("param1", param12); params.add("param2", param2); params.add(Constants.PARAM_DIGEST, HmacSHA256Utils.digest(key, params)); params.set("param2", param2 + "1"); String url = UriComponentsBuilder .fromHttpUrl("http://localhost:8080/hello") .queryParams(params).build().toUriString(); try { ResponseEntity responseEntity = restTemplate.getForEntity(url, String.class); } catch (HttpClientErrorException e) { Assert.assertEquals(HttpStatus.UNAUTHORIZED, e.getStatusCode()); Assert.assertEquals("login error", e.getResponseBodyAsString()); } }
在生成請求參數(shù)消息摘要后,篡改了參數(shù)內(nèi)容,服務(wù)器端接收后進行重新生成消息摘要發(fā)現(xiàn)不一樣,報401錯誤狀態(tài)碼。
到此,整個測試完成了,需要注意的是,為了安全性,請考慮本文開始介紹的相應(yīng)解決方案。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- spring boot 1.5.4 集成shiro+cas,實現(xiàn)單點登錄和權(quán)限控制
- SpringBoot集成Shiro進行權(quán)限控制和管理的示例
- springmvc集成shiro登錄權(quán)限示例代碼
- spring boot集成shiro詳細教程(小結(jié))
- 詳解Spring Boot 集成Shiro和CAS
- spring boot 集成shiro的配置方法
- Spring Boot集成Shiro并利用MongoDB做Session存儲的方法詳解
- 詳解spring與shiro集成
- Spring 應(yīng)用中集成 Apache Shiro的方法
- Shiro集成Spring之注解示例詳解
相關(guān)文章
使用java的HttpClient實現(xiàn)多線程并發(fā)
這篇文章主要介紹了使用java的HttpClient實現(xiàn)多線程并發(fā)的相關(guān)資料,需要的朋友可以參考下2016-09-09如何用匿名內(nèi)部類實現(xiàn) Java 同步回調(diào)
這篇文章主要介紹了如何用匿名內(nèi)部類實現(xiàn) Java 同步回調(diào),幫助大家更好的理解和學(xué)習(xí)Java,感興趣的朋友可以了解下2020-10-10Java中數(shù)組和List的互相轉(zhuǎn)換問題小結(jié)
這篇文章主要介紹了Java中數(shù)組和List的互相轉(zhuǎn)換問題小結(jié),本文通過實例代碼給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2024-03-03SpringBoot框架中Mybatis-plus的簡單使用操作匯總
這篇文章主要介紹了SpringBoot框架中Mybatis-plus的簡單使用,本文通過示例代碼給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-02-02Java基礎(chǔ)之static關(guān)鍵字的使用講解
這篇文章主要介紹了Java基礎(chǔ)之static關(guān)鍵字的使用講解,本篇文章通過簡要的案例,講解了該項技術(shù)的了解與使用,以下就是詳細內(nèi)容,需要的朋友可以參考下2021-07-07