public class MyShiroRealm extends AuthorizingRealm{ // 用于获取用户信息及用户权限信息的业务接口private BusinessManager businessManager; // 获取授权信息Authorizationprotected AuthorizationInfo doGetAuthorizationInfo( PrincipalCollection principals) { String username = (String) principals.fromRealm( getName()).iterator().next(); if( username != null ){ // 查询用户授权信息Collection<String> pers=businessManager.queryPermissions(username); if( pers != null && !pers.isEmpty() ){ SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(); for( String each:pers ) info.addStringPermissions( each ); return info; } } return null; } // 获取认证信息Authenticationprotected AuthenticationInfo doGetAuthenticationInfo( AuthenticationToken authcToken ) throws AuthenticationException { UsernamePasswordToken token = (UsernamePasswordToken) authcToken; // 通过表单接收的用户名String username = Username(); if( username != null && !"".equals(username) ){ LoginAccount account = ( username ); if( account != null ){ return new SimpleAuthenticationInfo( LoginName(),Password(),getName() ); } } return null; } }
<filter> <filter-name>shiroFilter</filter-name> <filter-class> org.springframework.web.filter.DelegatingFilterProxy </filter-class> </filter> <filter-mapping> <filter-name>shiroFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean"> <property name="securityManager" ref="securityManager"/> <property name="loginUrl" value="/login.do"/> <property name="successUrl" value="/welcome.do"/> <property name="unauthorizedUrl" value="/403.do"/> <property name="filters"> <util:map> <entry key="authc" value-ref="formAuthenticationFilter"/> </util:map> </property> <property name="filterChainDefinitions"> <value> /=anon /login.do*=authc /logout.do*=anon # 权限配置示例/security/account/view.do=authc,perms[SECURITY_ACCOUNT_VIEW] /** = authc </value> </property> </bean> <bean id="securityManager" class="org.apache.DefaultWebSecurityManager"> <property name="realm" ref="myShiroRealm"/> </bean> <bean id="myShiroRealm" class="xxx.packagename.MyShiroRealm"> <!-- businessManager 用来实现用户名密码的查询 --> <property name="businessManager" ref="businessManager"/> <property name="cacheManager" ref="shiroCacheManager"/> </bean> <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/> <bean id="shiroCacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager"> <property name="cacheManager" ref="cacheManager"/> </bean> <bean id="formAuthenticationFilter" class="org.apache.shiro.web.filter.authc.FormAuthenticationFilter"/>
<!-- captcha servlet--> <servlet> <servlet-name>kaptcha</servlet-name> <servlet-class> de.kaptcha.servlet.KaptchaServlet </servlet-class> </servlet> <servlet-mapping> <servlet-name>kaptcha</servlet-name> <url-pattern>/images/kaptcha.jpg</url-pattern> </servlet-mapping>
public class CaptchaFormAuthenticationFilter extends FormAuthenticationFilter{ public static final String DEFAULT_CAPTCHA_PARAM = "captcha"; private String captchaParam = DEFAULT_CAPTCHA_PARAM; public String getCaptchaParam() { return captchaParam; } public void setCaptchaParam(String captchaParam) { this.captchaParam = captchaParam; } protected String getCaptcha(ServletRequest request) { CleanParam(request, getCaptchaParam()); } // 创建 Token protected CaptchaUsernamePasswordToken createToken( ServletRequest request, ServletResponse response) { String username = getUsername(request); String password = getPassword(request); String captcha = getCaptcha(request); boolean rememberMe = isRememberMe(request); String host = getHost(request); return new CaptchaUsernamePasswordToken( username, password, rememberMe, host,captcha); } // 验证码校验protected void doCaptchaValidate( HttpServletRequest request ,CaptchaUsernamePasswordToken token ){ String captcha = (Session().getAttribute( de.kaptcha.Constants.KAPTCHA_SESSION_KEY); if( captcha!=null && !captcha.Captcha()) ){ throw new IncorrectCaptchaException ("验证码错误!"); } } // 认证protected boolean executeLogin(ServletRequest request, ServletResponse response) throws Exception { CaptchaUsernamePasswordToken token = createToken(request, response); try { doCaptchaValidate( (HttpServletRequest)request,token ); Subject subject = getSubject(request, response); subject.login(token); return onLoginSuccess(token, subject, request, response); } catch (AuthenticationException e) { return onLoginFailure(token, e, request, response); } } }
public class IncorrectCaptchaException extends AuthenticationException{ public IncorrectCaptchaException() { super(); } public IncorrectCaptchaException(String message, Throwable cause) { super(message, cause); } public IncorrectCaptchaException(String message) { super(message); } public IncorrectCaptchaException(Throwable cause) { super(cause); } }
Object objAttribute( org.apache.shiro.web.filter.authc.FormAuthenticationFilter .DEFAULT_ERROR_KEY_ATTRIBUTE_NAME); AuthenticationException authExp = (AuthenticationException)obj; if( authExp != null ){ String expMsg=""; if(authExp instanceof UnknownAccountException || authExp instanceof IncorrectCredentialsException){ expMsg="错误的用户账号或密码!"; }else if( authExp instanceof IncorrectCaptchaException){ expMsg="验证码错误!"; }else{ expMsg="登录异常 :"Message() ; } out.print("<div class="error">"+expMsg+"</div>"); }
public class MyCasRealm extends CasRealm{ // 获取授权信息protected AuthorizationInfo doGetAuthorizationInfo( PrincipalCollection principals) { //... 与前面 MyShiroRealm 相同} public String getCasServerUrlPrefix() { return "casserver/login"; } public String getCasService() { return "casclient/shiro-cas"; } }
<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean"> <property name="securityManager" ref="securityManager"/> <property name="loginUrl" value="casserver/login?service=casclient/shiro-cas"/> <property name="successUrl" value="/welcome.do"/> <property name="unauthorizedUrl" value="/403.do"/> <property name="filters"> <util:map> <entry key="authc" value-ref="formAuthenticationFilter"/> <entry key="cas" value-ref="casFilter"/> </util:map> </property> <property name="filterChainDefinitions"> <value> /shiro-cas*=cas /logout.do*=anon /casticketerror.do*=anon # 权限配置示例/security/account/view.do=authc,perms[SECURITY_ACCOUNT_VIEW] /** = authc </value> </property> </bean> <bean id="securityManager" class="org.apache.DefaultWebSecurityManager"> <property name="realm" ref="myShiroRealm"/> </bean> <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/> <!-- CAS Realm --> <bean id="myShiroRealm" class="xxx.packagename.MyCasRealm"> <property name="cacheManager" ref="shiroCacheManager"/> </bean> <bean id="shiroCacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager"> <property name="cacheManager" ref="cacheManager"/> </bean> <bean id="formAuthenticationFilter" class="org.apache.shiro.web.filter.authc.FormAuthenticationFilter"/> <!-- CAS Filter --> <bean id="casFilter" class="org.apache.shiro.cas.CasFilter"> <property name="failureUrl" value="casticketerror.do"/> </bean>
@RequestMapping(params = "main") public ModelAndView login(User user,HttpSession session, HttpServletRequest request) { ModelAndView modelView = new ModelAndView(); Subject currentUser = Subject(); UsernamePasswordToken token = new UsernamePasswordToken( Usercode(), Password())); token.setRememberMe(true); try { currentUser.login(token); } catch (AuthenticationException e) { modelView.addObject("message", "login errors"); modelView.setViewName("/login"); e.printStackTrace(); } if(currentUser.isAuthenticated()){ session.setAttribute("userinfo", user); modelView.setViewName("/main"); }else{ modelView.addObject("message", "login errors"); modelView.setViewName("/login"); } return modelView; }
Subject currentUser = Subject();
UsernamePasswordToken token = new UsernamePasswordToken( Usercode(),Password()));
currentUser.login(token);
protected AuthenticationInfo doGetAuthenticationInfo()
if(currentUser.isAuthenticated())
@Service("monitorRealm")
public class MonitorRealm extends AuthorizingRealm { /* * @Autowired UserService userService; * * @Autowired RoleService roleService; * * @Autowired LoginLogService loginLogService; */ public MonitorRealm() { super(); } @Override protected AuthorizationInfo doGetAuthorizationInfo( PrincipalCollection principals) { /* 这里编写授权代码 */ Set<String> roleNames = new HashSet<String>(); Set<String> permissions = new HashSet<String>(); roleNames.add("admin"); permissions.add("user.do?myjsp"); permissions.add("login.do?main"); permissions.add("login.do?logout"); SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(roleNames); info.setStringPermissions(permissions); return info; } @Override protected AuthenticationInfo doGetAuthenticationInfo( AuthenticationToken authcToken) throws AuthenticationException { /* 这里编写认证代码 */ UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
// User user = securityApplication.Username()); User user = new User(); user.Username()); user.setUserName("admin"); user.ptMD5("admin"));
// if (user != null) { return new UserName(), Password(), getName()); } public void clearCachedAuthorizationInfo(String principal) { SimplePrincipalCollection principals = new SimplePrincipalCollection( principal, getName()); clearCachedAuthorizationInfo(principals); }
}
@Controller
@RequestMapping(value="user")
public class UserController { /** * 跳转到myjsp页面 * * @return */ @RequestMapping(params = "myjsp") public String home() { Subject currentUser = Subject(); if(currentUser.isPermitted("user.do?myjsp")){ return "/my"; }else{ return "error/noperms"; } }
}
文章已被作者锁定,不允许评论。
<script type="text/javascript"> dp.SyntaxHighlighter.HighlightAll('code', true, true); $$('#main .blog_content pre[name=code]').each(function(pre, index){ // blog content var post_id = 2364195; var location = window.location; source_url = location.protocol + "//" + location.host + location.pathname + location.search; pre.writeAttribute('codeable_id', post_id); pre.writeAttribute('codeable_type', "Blog"); pre.writeAttribute('source_url', source_url); pre.writeAttribute('pre_index', index); pre.writeAttribute('title', 'Spring Shiro配置案例分析'); }); fix_image_size($$('div.blog_content img'), 700); function processComment() { $$('#main .blog_comment > div').each(function(comment){// comment var post_id = comment.id.substr(2); $$("#"+comment.id+" pre[name=code]").each(function(pre, index){ var location = window.location; source_url = location.protocol + "//" + location.host + location.pathname + location.search; source_url += "#" + comment.id; pre.writeAttribute('codeable_id', post_id); pre.writeAttribute('codeable_type', "BlogComment"); pre.writeAttribute('source_url', source_url); pre.writeAttribute('pre_index', index); pre.writeAttribute('title', 'Spring Shiro配置案例分析'); }); }); } function quote_comment(id) { new Ajax.Request('/editor/quote', { parameters: {'id':id, 'type':'BlogComment'}, onSuccess:function(response){editor.area.sponseText); Element.scrollTo(editor.area.element);} }); } code_favorites_init(); processComment(); new WeiboShare({share_buttons: $('share_weibo'), img_scope: $('blog_content')}); </script> 艾伦蓝本文发布于:2024-02-03 08:58:03,感谢您对本站的认可!
本文链接:https://www.4u4v.net/it/170692188149988.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
留言与评论(共有 0 条评论) |