SSM整合Shiro 身份验证及密码加密简单实现

1.导入maven的相关依赖

    <!-- shiro -->
        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-all</artifactId>
            <version>1.3.2</version>
        </dependency>
        
        <dependency>
        <groupId>net.sf.ehcache</groupId>
        <artifactId>ehcache-core</artifactId>
        <version>2.5.7</version>
        </dependency>

2.web.xml中配置DelegatingFilterProxy

 1 <!-- shiro -->
 2     <filter>
 3         <filter-name>shiroFilter</filter-name>
 4         <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
 5         <!-- 设置true由servlet容器控制filter的生命周期 -->
 6         <init-param>
 7           <param-name>targetFilterLifecycle</param-name>
 8           <param-value>true</param-value>
 9         </init-param>
10     </filter>
11 
12     <filter-mapping>
13         <filter-name>shiroFilter</filter-name>
14         <url-pattern>/*</url-pattern>
15     </filter-mapping>

 

3. 跟spring IOC容器组合部分

 

 

 1 <!--配置securityManager(安全管理)  -->
 2     <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
 3         <property name="cacheManager" ref="cacheManager"/>
 4          <property name="authenticator" ref="authenticator"></property>
 5          <property name="realm" ref="jdbcRealm"></property>
 6         <!-- 改变remember 的时间-->
 7         <property name="rememberMeManager.cookie.maxAge" value="10"></property>
 8     </bean>
 9      <!-- 缓存管理器
10     <bean id="cacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">
11              <!-- 加入ehcache jar包和配置文件 -->
12         <property name="cacheManagerConfigFile" value="classpath:ehcache.xml"/>
13     </bean>-->
14  <bean id="authenticator" 
15      class="org.apache.shiro.authc.pam.ModularRealmAuthenticator">
16      <property name="authenticationStrategy">
17       <bean class="org.apache.shiro.authc.pam.AtLeastOneSuccessfulStrategy"></bean>
18      </property>
19     </bean>
20      <!--配置 realm(范围)      实现了Realm的bean -->
21     <bean id="jdbcRealm" class="com.tx.shiro.realm.MyShiroRealm">
22         <property name="credentialsMatcher">
23          <bean class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
24           <property name="hashAlgorithmName" value="MD5"></property>
25           <property name="hashIterations" value="1024"></property>
26          </bean>
27         </property>
28     </bean>
29     <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
30      <!--这里根据项目制定路径 -->
31         <property name="securityManager" ref="securityManager"/>
32         <property name="loginUrl" value="/"/>
33         <property name="successUrl" value="/customer/customer.action"/>
34         <property name="filterChainDefinitions">
35             <value>
36                #允许匿名访问的url
37                 /sysUser/login = anon
38           #登出
39                 /sysUser/loginout = logout
40                 #不允许匿名访问的url
41                 /** = authc
42             </value>
43         </property>
44     </bean>

 

 Warning:下一步配置com.tx.shiro.realm.MyShiroRealm

4.编写MyShiroRealm

 1 import javax.servlet.http.HttpServletRequest;
 2 
 3 import org.apache.shiro.authc.AuthenticationException;
 4 import org.apache.shiro.authc.AuthenticationInfo;
 5 import org.apache.shiro.authc.AuthenticationToken;
 6 import org.apache.shiro.authc.SimpleAuthenticationInfo;
 7 import org.apache.shiro.authc.UsernamePasswordToken;
 8 import org.apache.shiro.authz.AuthorizationInfo;
 9 import org.apache.shiro.realm.AuthorizingRealm;
10 import org.apache.shiro.subject.PrincipalCollection;
11 import org.apache.shiro.util.ByteSource;
12 import org.springframework.beans.factory.annotation.Autowired;
13 
14 import com.baomidou.mybatisplus.mapper.EntityWrapper;
15 import com.baomidou.mybatisplus.mapper.Wrapper;
16 import com.tx.beans.SysUser;
17 import com.tx.service.SysUserService;
18 
19 public class MyShiroRealm extends AuthorizingRealm{
20     
21     @Autowired
22     SysUserService sysUserService;
23     
24     @Autowired
25     HttpServletRequest request;
26     
27     @Override//这里可以配置角色权限
28     protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
29         
30         return null;
31     }
32 
33     @Override
34     protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
35         UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken)token;
36         String username = usernamePasswordToken.getUsername();
37         
38         Wrapper<SysUser> wrapper = new EntityWrapper<SysUser>().eq("user_name", username);
39         SysUser user  = sysUserService.selectOne(wrapper);
40         
41         request.getSession().setAttribute("loginUser", user);
42         
43         //使用MD5盐值加密  
44         ByteSource credentialsSalt = ByteSource.Util.bytes(username);
45         
46         return new SimpleAuthenticationInfo(username,  user.getUserPassword(), credentialsSalt, getName());
47         
48     }
49 
50 }

 

5.登录Controller编写

 1 @ResponseBody
 2     @PostMapping("/login")
 3     public AJAXResult login(@RequestParam(value="rememberMe",required=false) String rememberMe, SysUser sysUser ,HttpSession session) {
 4         AJAXResult result = new AJAXResult();
 5         try {
 6             
 7             Subject currentUser = SecurityUtils.getSubject();
 8             if (!currentUser.isAuthenticated()) {
 9                 UsernamePasswordToken token = new UsernamePasswordToken(sysUser.getUserName(), sysUser.getUserPassword());
10                 // rememberme 
11                 if("remember-me".equals(rememberMe)) {
12                     token.setRememberMe(true);
13                 }
14                 try {
15                     // 执行登录. 
16                     currentUser.login(token);
17                 } catch (AuthenticationException ae) {
18                     System.out.println("登录失败! " +ae );
19                 }
20             }
21             result.setResult(true);
22             
23         } catch (Exception e) {
24             e.printStackTrace();
25             result.setMsg("服务器内部错误!!");
26         }
27         
28         
29         return result;
30     }

本代码只是部分代码,具体逻辑根据项目情况编写!


 

6.Other

ehcache.xml

<?xml version="1.0" encoding="UTF-8"?>
<ehcache name="shirocache">
    <diskStore path="java.io.tmpdir" />
    
    <cache name="passwordRetryCache"
           maxEntriesLocalHeap="2000"
           eternal="false"
           timeToIdleSeconds="1800"
           timeToLiveSeconds="0"
           overflowToDisk="false"
           statistics="true">
    </cache>
</ehcache>

 

转载于:https://www.cnblogs.com/tmlh/p/9306189.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值