Java學習

          java,spring,structs,hibernate,jsf,ireport,jfreechart,jasperreport,tomcat,jboss -----本博客已經搬家了,新的地址是 http://www.javaly.cn 如果有對文章有任何疑問或者有任何不懂的地方,歡迎到www.javaly.cn (Java樂園)指出,我會盡力幫助解決。一起進步

           

          擴展acegi以支持驗證碼

          主要是通用改寫擴展authenticationProcessingFilter類來實現,當然還有開源框架JCaptcha來生成驗證碼
          Java代碼 復制代碼
          1. public class AuthenticationProcessingFilter implements Filter, InitializingBean, ApplicationEventPublisherAware {   
          2. public static final String ACEGI_SAVED_REQUEST_KEY = "ACEGI_SAVED_REQUEST_KEY";   
          3. public static final String ACEGI_SECURITY_LAST_EXCEPTION_KEY = "ACEGI_SECURITY_LAST_EXCEPTION";   
          4.   
          5. public static final String ACEGI_SECURITY_FORM_USERNAME_KEY = "j_username";   
          6. public static final String ACEGI_SECURITY_FORM_PASSWORD_KEY = "j_password";   
          7. public static final String ACEGI_SECURITY_LAST_USERNAME_KEY = "ACEGI_SECURITY_LAST_USERNAME";   
          8.   
          9. private ApplicationEventPublisher eventPublisher;   
          10. private AuthenticationDetailsSource authenticationDetailsSource = new AuthenticationDetailsSourceImpl();   
          11. private AuthenticationManager authenticationManager;   
          12.   
          13. private String authenticationFailureUrl;   
          14. private String defaultTargetUrl;   
          15. private String filterProcessesUrl = getDefaultFilterProcessesUrl();   
          16. private boolean alwaysUseDefaultTargetUrl = false;   
          17.   
          18. private RememberMeServices rememberMeServices = new NullRememberMeServices();   
          19. protected MessageSourceAccessor messages = AcegiMessageSource.getAccessor();   
          20. private Properties exceptionMappings = new Properties();   
          21. private boolean continueChainBeforeSuccessfulAuthentication = false;   
          22. public boolean isContinueChainBeforeSuccessfulAuthentication() {   
          23. return continueChainBeforeSuccessfulAuthentication;   
          24. }   
          25. public void setContinueChainBeforeSuccessfulAuthentication(   
          26. boolean continueChainBeforeSuccessfulAuthentication) {   
          27. this.continueChainBeforeSuccessfulAuthentication = continueChainBeforeSuccessfulAuthentication;   
          28. }   
          29. public String getDefaultFilterProcessesUrl() {   
          30. return "/j_acegi_security_check";   
          31. }   
          32. public void destroy() {}   
          33.   
          34. public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {   
          35. if (!(request instanceof HttpServletRequest)) {   
          36. throw new ServletException("Can only process HttpServletRequest");   
          37. }   
          38. if (!(response instanceof HttpServletResponse)) {   
          39. throw new ServletException("Can only process HttpServletResponse");   
          40. }   
          41. HttpServletRequest httpRequest = (HttpServletRequest) request;   
          42. HttpServletResponse httpResponse = (HttpServletResponse) response;   
          43.   
          44. String username = obtainUsername(httpRequest);   
          45. String password = obtainPassword(httpRequest);   
          46. if (username == null) {   
          47. username = "";   
          48. }   
          49. if (password == null) {   
          50. password = "";   
          51. }   
          52. if (requiresAuthentication(httpRequest, httpResponse)) {   
          53. Authentication authResult;   
          54. try {   
          55. //加入驗證碼   
          56. if(!onPreAuthentication(httpRequest, httpResponse)){   
          57. httpRequest.getSession().setAttribute(ACEGI_SECURITY_LAST_USERNAME_KEY,   
          58. username);   
          59. throw new AuthenticationCodeException("請輸入正確的驗證碼!");   
          60. }   
          61.   
          62. UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username,   
          63. password);   
          64. setDetails(httpRequest, authRequest);   
          65. httpRequest.getSession().setAttribute(ACEGI_SECURITY_LAST_USERNAME_KEY,username);   
          66. authResult = this.getAuthenticationManager().authenticate(authRequest);   
          67. // Authentication success   
          68. if (continueChainBeforeSuccessfulAuthentication) {   
          69. filterChain.doFilter(httpRequest, httpResponse);   
          70. }   
          71. //可以在此加入驗證成功后的功能代碼   
          72. successfulAuthentication(httpRequest, httpResponse, authResult);   
          73. String targetUrl = alwaysUseDefaultTargetUrl ? null : obtainFullRequestUrl(httpRequest);   
          74. if (targetUrl == null) {   
          75. targetUrl = getDefaultTargetUrl();   
          76. }   
          77. if (!targetUrl.startsWith("http://") && !targetUrl.startsWith("https://")) {   
          78. targetUrl = httpRequest.getContextPath() + targetUrl;   
          79. }   
          80. httpResponse.sendRedirect(httpResponse.encodeRedirectURL(targetUrl));   
          81. return ;   
          82. catch (AuthenticationException failed) {   
          83. // Authentication failed   
          84. unsuccessfulAuthentication(httpRequest, httpResponse, failed);   
          85. String failureUrl = exceptionMappings.getProperty(failed.getClass().getName(), authenticationFailureUrl);   
          86. if (!failureUrl.startsWith("http://") && !failureUrl.startsWith("https://")) {   
          87. failureUrl = httpRequest.getContextPath() + failureUrl;   
          88. }   
          89. httpResponse.sendRedirect(httpResponse.encodeRedirectURL(failureUrl));   
          90. return;   
          91. }   
          92. }   
          93.   
          94. filterChain.doFilter(request, response);   
          95. }   
          96.   
          97. public Authentication attemptAuthentication(HttpServletRequest request,HttpServletResponse response)   
          98. throws AuthenticationException, IOException{   
          99. String username = obtainUsername(request);   
          100. String password = obtainPassword(request);   
          101. // System.out.println("username: "+username +" passward:"+password) ;   
          102. if (username == null) {   
          103. username = "";   
          104. }   
          105. if (password == null) {   
          106. password = "";   
          107. }   
          108. UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username,   
          109. password);   
          110. setDetails(request, authRequest);   
          111. request.getSession().setAttribute(ACEGI_SECURITY_LAST_USERNAME_KEY,   
          112. username);   
          113. return this.getAuthenticationManager().authenticate(authRequest);   
          114. }   
          115.   
          116. protected void setDetails(HttpServletRequest request,   
          117. UsernamePasswordAuthenticationToken authRequest) {   
          118. authRequest.setDetails(new WebAuthenticationDetails(request));   
          119. }   
          120.   
          121.   
          122. protected boolean requiresAuthentication(HttpServletRequest request, HttpServletResponse response) {   
          123. String uri = request.getRequestURI();   
          124. int pathParamIndex = uri.indexOf(';');   
          125. if (pathParamIndex > 0) {   
          126. uri = uri.substring(0, pathParamIndex);   
          127. }   
          128.   
          129. return uri.endsWith(request.getContextPath() + filterProcessesUrl);   
          130. }   
          131.   
          132.   
          133. public void init(FilterConfig arg0) throws ServletException {}   
          134.   
          135. public void afterPropertiesSet() throws Exception {}   
          136.   
          137. public void setApplicationEventPublisher(ApplicationEventPublisher context) {   
          138. this.eventPublisher = context;   
          139. }   
          140.   
          141. public void setAuthenticationDetailsSource(AuthenticationDetailsSource authenticationDetailsSource) {   
          142. Assert.notNull(authenticationDetailsSource, "AuthenticationDetailsSource required");   
          143. this.authenticationDetailsSource = authenticationDetailsSource;   
          144. }   
          145.   
          146.   
          147.   
          148. public boolean isAlwaysUseDefaultTargetUrl() {   
          149. return alwaysUseDefaultTargetUrl;   
          150. }   
          151.   
          152. public void setAlwaysUseDefaultTargetUrl(boolean alwaysUseDefaultTargetUrl) {   
          153. this.alwaysUseDefaultTargetUrl = alwaysUseDefaultTargetUrl;   
          154. }   
          155.   
          156. public String getAuthenticationFailureUrl() {   
          157. return authenticationFailureUrl;   
          158. }   
          159.   
          160. public void setAuthenticationFailureUrl(String authenticationFailureUrl) {   
          161. this.authenticationFailureUrl = authenticationFailureUrl;   
          162. }   
          163.   
          164. public String getDefaultTargetUrl() {   
          165. return defaultTargetUrl;   
          166. }   
          167.   
          168. public void setDefaultTargetUrl(String defaultTargetUrl) {   
          169. this.defaultTargetUrl = defaultTargetUrl;   
          170. }   
          171.   
          172. public String getFilterProcessesUrl() {   
          173. return filterProcessesUrl;   
          174. }   
          175.   
          176. public void setFilterProcessesUrl(String filterProcessesUrl) {   
          177. this.filterProcessesUrl = filterProcessesUrl;   
          178. }   
          179.   
          180. protected String obtainPassword(HttpServletRequest request) {   
          181. String password=request.getParameter(ACEGI_SECURITY_FORM_PASSWORD_KEY);   
          182. if(password!=null){   
          183. return MD5.toMD5(request.getParameter(ACEGI_SECURITY_FORM_PASSWORD_KEY));   
          184. }   
          185. return password;   
          186. }   
          187.   
          188.   
          189. protected String obtainUsername(HttpServletRequest request) {   
          190. return request.getParameter(ACEGI_SECURITY_FORM_USERNAME_KEY);   
          191. }   
          192.   
          193. //加入驗證碼   
          194. protected boolean onPreAuthentication(HttpServletRequest request, HttpServletResponse response)   
          195. throws AuthenticationException, IOException {   
          196. String randNum=request.getParameter("randNum");   
          197. String rand=(String)request.getSession().getAttribute("rand");   
          198. if(rand.equals(randNum)){   
          199. return true;   
          200. }   
          201. return false;   
          202. }   
          203. //可以在此加入驗證成功后的功能代碼   
          204. protected void onSuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response,   
          205. Authentication authResult) throws IOException {}   
          206. protected void onUnsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response,   
          207. AuthenticationException failed) throws IOException {}   
          208.   
          209. protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response,   
          210. Authentication authResult) throws IOException {   
          211. //logger.info("Authentication success: " + authResult.toString());   
          212. SecurityContextHolder.getContext().setAuthentication(authResult);   
          213. onSuccessfulAuthentication(request, response, authResult);   
          214. rememberMeServices.loginSuccess(request, response, authResult);   
          215. // Fire event   
          216. if (this.eventPublisher != null) {   
          217. eventPublisher.publishEvent(new InteractiveAuthenticationSuccessEvent(authResult, this.getClass()));   
          218. }   
          219. }   
          220. protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response,   
          221. AuthenticationException failed) throws IOException {   
          222. SecurityContextHolder.getContext().setAuthentication(null);   
          223. //logger.info("Updated SecurityContextHolder to contain null Authentication");   
          224. try {   
          225. request.getSession().setAttribute(ACEGI_SECURITY_LAST_EXCEPTION_KEY, failed);   
          226. catch (Exception ignored) {}   
          227. onUnsuccessfulAuthentication(request, response, failed);   
          228. rememberMeServices.loginFail(request, response);   
          229. }   
          230. public static String obtainFullRequestUrl(HttpServletRequest request) {   
          231. SavedRequest savedRequest = (SavedRequest) request.getSession()   
          232. .getAttribute(ACEGI_SAVED_REQUEST_KEY);   
          233. return (savedRequest == null) ? null : savedRequest.getFullRequestUrl();   
          234. }   
          235. public Properties getExceptionMappings() {   
          236. return exceptionMappings;   
          237. }   
          238. public void setExceptionMappings(Properties exceptionMappings) {   
          239. this.exceptionMappings = exceptionMappings;   
          240. }   
          241. public MessageSourceAccessor getMessages() {   
          242. return messages;   
          243. }   
          244. public void setMessages(MessageSourceAccessor messages) {   
          245. this.messages = messages;   
          246. }   
          247. public RememberMeServices getRememberMeServices() {   
          248. return rememberMeServices;   
          249. }   
          250. public void setRememberMeServices(RememberMeServices rememberMeServices) {   
          251. this.rememberMeServices = rememberMeServices;   
          252. }   
          253. public ApplicationEventPublisher getEventPublisher() {   
          254. return eventPublisher;   
          255. }   
          256. public void setEventPublisher(ApplicationEventPublisher eventPublisher) {   
          257. this.eventPublisher = eventPublisher;   
          258. }   
          259. public AuthenticationDetailsSource getAuthenticationDetailsSource() {   
          260. return authenticationDetailsSource;   
          261. }   
          262. public AuthenticationManager getAuthenticationManager() {   
          263. return authenticationManager;   
          264. }   
          265. public void setAuthenticationManager(AuthenticationManager authenticationManager) {   
          266. this.authenticationManager = authenticationManager;   
          267. }   
          268. }  

          posted on 2008-07-17 15:05 找個美女做老婆 閱讀(942) 評論(0)  編輯  收藏


          只有注冊用戶登錄后才能發表評論。


          網站導航:
          博客園   IT新聞   Chat2DB   C++博客   博問  
           

          導航

          統計

          公告

          本blog已經搬到新家了, 新家:www.javaly.cn
           http://www.javaly.cn

          常用鏈接

          留言簿(6)

          隨筆檔案

          文章檔案

          搜索

          最新評論

          閱讀排行榜

          評論排行榜

          主站蜘蛛池模板: 永善县| 昌邑市| 南丰县| 兴隆县| 大城县| 犍为县| 浦东新区| 广汉市| 滦南县| 满洲里市| 华宁县| 通道| 伊宁县| 呼图壁县| 梨树县| 凤城市| 大庆市| 新绛县| 马公市| 怀来县| 城固县| 三亚市| 武城县| 宝山区| 合水县| 团风县| 莒南县| 贡觉县| 方城县| 邯郸市| 临武县| 米脂县| 合肥市| 容城县| 辉县市| 色达县| 吉木萨尔县| 甘洛县| 谢通门县| 西乌珠穆沁旗| 宝兴县|