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

首頁 > 學院 > 開發設計 > 正文

shiro的使用1 簡單的認證

2019-11-08 19:25:17
字體:
來源:轉載
供稿:網友

shiro的使用1 簡單的認證

最近在重構,有空學了一個簡單的安全框架shiro,資料比較少,在百度和google上能搜到的中文我看過了,剩下的時間有空會研究下官網的文章和查看下源碼

簡單的分享一些學習過程;

1,簡單的一些概念上的認知

2,使用認證的基本流程

3,shiro集成sPRing完成簡單的認證流程,已實現

1建一個maven的web項目,引入依賴  springmvc的的依賴      <dependency>            <groupId>org.springframework</groupId>            <artifactId>spring-webmvc</artifactId>            <version>3.2.0.RELEASE</version>        </dependency>shiro跟spring集成的插件 <dependency>            <groupId>org.apache.shiro</groupId>            <artifactId>shiro-spring</artifactId>            <version>1.2.3</version>        </dependency>
2配置web.xml指出spring容器的配置文件位置<context-param>        <param-name>contextConfigLocation</param-name>        <param-value>classpath*:context_config.xml</param-value>    </context-param>指出spring在web容器中的代號    <context-param>        <param-name>webAppRootKey</param-name>        <param-value>wechatSystem</param-value>    </context-param>初始化spring的容器    <listener>        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>    </listener>spring mvc的分發器    <servlet>          <servlet-name>admin</servlet-name>          <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>        <init-param>            <param-name>contextConfigLocation</param-name>            <param-value>classpath*:admin-dispatcher-servlet.xml</param-value>        </init-param>        <load-on-startup>1</load-on-startup>     </servlet>     <servlet-mapping>          <servlet-name>admin</servlet-name>          <url-pattern>/</url-pattern>     </servlet-mapping>spring跟shiro集成的過濾代理 <filter>        <filter-name>shiroFilter</filter-name>        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>        <init-param>            <param-name>targetFilterLifecycle</param-name>            <param-value>true</param-value>        </init-param>    </filter>    <filter-mapping>        <filter-name>shiroFilter</filter-name>        <url-pattern>/admin/*</url-pattern>    </filter-mapping>    <!– 字符過濾,保存中文的時候用到 –>    <filter>        <filter-name>characterEncoding</filter-name>        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>        <init-param>            <param-name>encoding</param-name>            <param-value>UTF-8</param-value>        </init-param>        <init-param>            <param-name>forceEncoding</param-name>            <param-value>true</param-value>        </init-param>    </filter>    <filter-mapping>        <filter-name>characterEncoding</filter-name>        <url-pattern>/*</url-pattern>    </filter-mapping>
3配置shiroFilter實例 <!–shiro的配置,關鍵兩點,配置SecurityManager和依賴的RealM–>    <bean id=”shiroFilter” class=”org.apache.shiro.spring.web.ShiroFilterFactoryBean”>        <property name=”securityManager” ref=”securityManager” />        <property name=”loginUrl” value=”/admin/login” />        <property name=”successUrl” value=”/admin/home” />        <property name=”unauthorizedUrl” value=”/admin/login” />        <property name=”filters”>            <map>                <entry key=”anno” value-ref=”anno”/>                <entry key=”authc” value-ref=”authc”/>            </map>        </property>        <property name=”filterChainDefinitionMap”>            <map>                <entry key=”anon” value=”anon”/>                <entry key=”authc” value=”authc”/>            </map>        </property>        <property name=”filterChainDefinitions”>            <value>                /admin/login=anon                /admin/validCode=anon                /user/**=authc                /role/**=authc                /permission/**=authc                /**=authc            </value>        </property>    </bean>    <bean id=”authc” class=”com.util.filter.MyaccessFilter”/>    <bean id=”anno” class=”org.apache.shiro.web.filter.authc.AnonymousFilter”/>    <bean id=”securityManager” class=”org.apache.shiro.web.mgt.DefaultWebSecurityManager”>        <property name=”realm” ref=”myRealm”/>    </bean>    <bean id=”myRealm” class=”com.util.MySQLJdbcRealM”/>
4開發跟shiro交互的RealM,一般把權限信息放到db中
package com.util;import com.domain.User;import com.domain.UserDto;import com.google.common.base.Strings;import com.service.UserDtoService;import com.service.UserService;import org.apache.shiro.authc.*;import org.apache.shiro.authz.AuthorizationInfo;import org.apache.shiro.authz.SimpleAuthorizationInfo;import org.apache.shiro.realm.jdbc.JdbcRealm;import org.apache.shiro.subject.PrincipalCollection;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Component;import javax.annotation.Resource;/*** User: cutter.li* Date: 2014/6/19 0019* Time: 15:24* 備注: 自定義的mysql數據源*/@Componentpublic class MysqlJdbcRealM extends JdbcRealm {    @Resource    private UserService userService;    //登錄認證    @Override    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {        UsernamePassWordToken usernamePasswordToken = (UsernamePasswordToken) token;        String username = String.valueOf(usernamePasswordToken.getUsername());        User user = userService.findByUserName(username);        AuthenticationInfo authenticationInfo = null;        if (null != user) {            String password = new String(usernamePasswordToken.getPassword());            if (password.equals(user.getPassword())) {                authenticationInfo = new SimpleAuthenticationInfo(user.getUsername(), user.getPassword(), getName());            }        }        return authenticationInfo;    }    //授權    @Override    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {        String username = (String) principals.getPrimaryPrincipal();        if (!Strings.isNullOrEmpty(username)) {            SimpleAuthorizationInfo authenticationInfo = new SimpleAuthorizationInfo();            authenticationInfo.setRoles(userService.findRolesStr(username));            authenticationInfo.setStringPermissions(userService.findPermissionsStr(username));            return authenticationInfo;        }        return null;    }}
 
5簡單的登錄頁面,功能測試
6controller的實現:
 @RequestMapping(value = “login”, method = RequestMethod.POST)    public ResponseEntity<Message> loginSubmit(String username, String password, String vcode, HttpServletRequest request) {        message.setSuccess();        validateLogin(message, username, password, vcode);        try {//            String code = request.getsession().getAttribute(AppConstant.KAPTCHA_SESSION_KEY).toString();//            if (!vcode.equalsIgnoreCase(code)) {//                message.setCode(AppConstant.VALIDCODE_ERROR);//                message.setMsg(“驗證碼錯誤”);//            }            if (message.isSuccess()) {                Subject subject = SecurityUtils.getSubject();                subject.login(new UsernamePasswordToken(username, password));                if (subject.isAuthenticated()) {                        message.setMsg(“登錄成功”);                } else {                    message.setCode(AppConstant.USERNAME_NOTEXIST);                    message.setMsg(“用戶名/密碼錯誤”);                }            }        }catch (AuthenticationException ex){            message.setCode(AppConstant.USERNAME_NOTEXIST);            message.setMsg(“用戶名/密碼錯誤”);            ex.printStackTrace();        }        finally {            return new ResponseEntity<Message>(message, HttpStatus.OK);        }    }
 
7指定認證的策略和多數據源    <!–shiro的配置–>    <bean id=”shiroFilter” class=”org.apache.shiro.spring.web.ShiroFilterFactoryBean”>        <property name=”securityManager” ref=”securityManager” />        <property name=”loginUrl” value=”/admin/login” />        <property name=”successUrl” value=”/admin/home” />        <property name=”unauthorizedUrl” value=”/admin/login” />        <property name=”filters”>            <map>                <entry key=”anno” value-ref=”anno”/>                <entry key=”authc” value-ref=”authc”/>            </map>        </property>        <property name=”filterChainDefinitionMap”>            <map>                <entry key=”anon” value=”anon”/>                <entry key=”authc” value=”authc”/>            </map>        </property>        <property name=”filterChainDefinitions”>            <value>                /admin/login=anon                /admin/validCode=anon                /user/**=authc                /role/**=authc                /permission/**=authc                /**=authc            </value>        </property>    </bean>    <bean id=”authc” class=”com.util.filter.MyAccessFilter”/>    <bean id=”anno” class=”org.apache.shiro.web.filter.authc.AnonymousFilter”/>    <bean id=”securityManager” class=”org.apache.shiro.web.mgt.DefaultWebSecurityManager”>        <property name=”authenticator” ref=”modelAuthricator”/>    </bean>    <bean id=”modelAuthricator” class=”org.apache.shiro.authc.pam.ModularRealmAuthenticator”>        <property name=”authenticationStrategy” ref=”firstSuccess”/>        <property name=”realms”>           <list>             <ref local=”myRealm”/>           </list>        </property>    </bean>    <bean id=”firstSuccess” class=”org.apache.shiro.authc.pam.FirstSuccessfulStrategy”/>    <bean id=”myRealm” class=”com.util.MysqlJdbcRealM”/>

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 绥阳县| 滨州市| 钦州市| 嘉鱼县| 敦化市| 上饶市| 西盟| 竹溪县| 和林格尔县| 江津市| 焉耆| 宁武县| 丘北县| 岱山县| 扶沟县| 新安县| 东乌| 榆树市| 山阴县| 江津市| 博湖县| 修武县| 中超| 西丰县| 江西省| 通海县| 台东县| 五原县| 新沂市| 华宁县| 卓尼县| 曲阳县| 义乌市| 肃北| 定兴县| 邵武市| 灵璧县| 大足县| 台山市| 深水埗区| 海阳市|