
正文
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 <!-- shiro -->
<filter>
<filter-name>shiroFilter</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
<!-- 设置true由servlet容器控制filter的生命周期 -->
<init-param>
<param-name>targetFilterLifecycle</param-name>
<param-value>true</param-value>
</init-param>
</filter> <filter-mapping>
<filter-name>shiroFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
3. 跟spring IOC容器组合部分 <!--配置securityManager(安全管理) -->
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<property name="cacheManager" ref="cacheManager"/>
<property name="authenticator" ref="authenticator"></property>
<property name="realm" ref="jdbcRealm"></property>
<!-- 改变remember 的时间-->
<property name="rememberMeManager.cookie.maxAge" value="10"></property>
</bean>
<!-- 缓存管理器
<bean id="cacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">
<!-- 加入ehcache jar包和配置文件 -->
<property name="cacheManagerConfigFile" value="classpath:ehcache.xml"/>
</bean>-->
<bean id="authenticator"
class="org.apache.shiro.authc.pam.ModularRealmAuthenticator">
<property name="authenticationStrategy">
<bean class="org.apache.shiro.authc.pam.AtLeastOneSuccessfulStrategy"></bean>
</property>
</bean>
<!--配置 realm(范围) 实现了Realm的bean -->
<bean id="jdbcRealm" class="com.tx.shiro.realm.MyShiroRealm">
<property name="credentialsMatcher">
<bean class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
<property name="hashAlgorithmName" value="MD5"></property>
<property name="hashIterations" value="1024"></property>
</bean>
</property>
</bean>
<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
<!--这里根据项目制定路径 -->
<property name="securityManager" ref="securityManager"/>
<property name="loginUrl" value="/"/>
<property name="successUrl" value="/customer/customer.action"/>
<property name="filterChainDefinitions">
<value>
#允许匿名访问的url
/sysUser/login = anon
#登出
/sysUser/loginout = logout
#不允许匿名访问的url
/** = authc
</value>
</property>
</bean>
<!-- 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>
<!-- shiro -->
<filter>
<filter-name>shiroFilter</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
<!-- 设置true由servlet容器控制filter的生命周期 -->
<init-param>
<param-name>targetFilterLifecycle</param-name>
<param-value>true</param-value>
</init-param>
</filter> <filter-mapping>
<filter-name>shiroFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
3. 跟spring IOC容器组合部分 <!--配置securityManager(安全管理) -->
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<property name="cacheManager" ref="cacheManager"/>
<property name="authenticator" ref="authenticator"></property>
<property name="realm" ref="jdbcRealm"></property>
<!-- 改变remember 的时间-->
<property name="rememberMeManager.cookie.maxAge" value="10"></property>
</bean>
<!-- 缓存管理器
<bean id="cacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">
<!-- 加入ehcache jar包和配置文件 -->
<property name="cacheManagerConfigFile" value="classpath:ehcache.xml"/>
</bean>-->
<bean id="authenticator"
class="org.apache.shiro.authc.pam.ModularRealmAuthenticator">
<property name="authenticationStrategy">
<bean class="org.apache.shiro.authc.pam.AtLeastOneSuccessfulStrategy"></bean>
</property>
</bean>
<!--配置 realm(范围) 实现了Realm的bean -->
<bean id="jdbcRealm" class="com.tx.shiro.realm.MyShiroRealm">
<property name="credentialsMatcher">
<bean class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
<property name="hashAlgorithmName" value="MD5"></property>
<property name="hashIterations" value="1024"></property>
</bean>
</property>
</bean>
<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
<!--这里根据项目制定路径 -->
<property name="securityManager" ref="securityManager"/>
<property name="loginUrl" value="/"/>
<property name="successUrl" value="/customer/customer.action"/>
<property name="filterChainDefinitions">
<value>
#允许匿名访问的url
/sysUser/login = anon
#登出
/sysUser/loginout = logout
#不允许匿名访问的url
/** = authc
</value>
</property>
</bean>
<!--配置securityManager(安全管理) -->
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<property name="cacheManager" ref="cacheManager"/>
<property name="authenticator" ref="authenticator"></property>
<property name="realm" ref="jdbcRealm"></property>
<!-- 改变remember 的时间-->
<property name="rememberMeManager.cookie.maxAge" value="10"></property>
</bean>
<!-- 缓存管理器
<bean id="cacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">
<!-- 加入ehcache jar包和配置文件 -->
<property name="cacheManagerConfigFile" value="classpath:ehcache.xml"/>
</bean>-->
<bean id="authenticator"
class="org.apache.shiro.authc.pam.ModularRealmAuthenticator">
<property name="authenticationStrategy">
<bean class="org.apache.shiro.authc.pam.AtLeastOneSuccessfulStrategy"></bean>
</property>
</bean>
<!--配置 realm(范围) 实现了Realm的bean -->
<bean id="jdbcRealm" class="com.tx.shiro.realm.MyShiroRealm">
<property name="credentialsMatcher">
<bean class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
<property name="hashAlgorithmName" value="MD5"></property>
<property name="hashIterations" value="1024"></property>
</bean>
</property>
</bean>
<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
<!--这里根据项目制定路径 -->
<property name="securityManager" ref="securityManager"/>
<property name="loginUrl" value="/"/>
<property name="successUrl" value="/customer/customer.action"/>
<property name="filterChainDefinitions">
<value>
#允许匿名访问的url
/sysUser/login = anon
#登出
/sysUser/loginout = logout
#不允许匿名访问的url
/** = authc
</value>
</property>
</bean>
Warning:下一步配置com.tx.shiro.realm.MyShiroRealm
4.编写MyShiroRealm import javax.servlet.http.HttpServletRequest; import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired; import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.tx.beans.SysUser;
import com.tx.service.SysUserService; public class MyShiroRealm extends AuthorizingRealm{ @Autowired
SysUserService sysUserService; @Autowired
HttpServletRequest request; @Override//这里可以配置角色权限
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) { return null;
} @Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken)token;
String username = usernamePasswordToken.getUsername(); Wrapper<SysUser> wrapper = new EntityWrapper<SysUser>().eq("user_name", username);
SysUser user = sysUserService.selectOne(wrapper); request.getSession().setAttribute("loginUser", user); //使用MD5盐值加密
ByteSource credentialsSalt = ByteSource.Util.bytes(username); return new SimpleAuthenticationInfo(username, user.getUserPassword(), credentialsSalt, getName()); } }
5.登录Controller编写 @ResponseBody
@PostMapping("/login")
public AJAXResult login(@RequestParam(value="rememberMe",required=false) String rememberMe, SysUser sysUser ,HttpSession session) {
AJAXResult result = new AJAXResult();
try { Subject currentUser = SecurityUtils.getSubject();
if (!currentUser.isAuthenticated()) {
UsernamePasswordToken token = new UsernamePasswordToken(sysUser.getUserName(), sysUser.getUserPassword());
// rememberme
if("remember-me".equals(rememberMe)) {
token.setRememberMe(true);
}
try {
// 执行登录.
currentUser.login(token);
} catch (AuthenticationException ae) {
System.out.println("登录失败! " +ae );
}
}
result.setResult(true); } catch (Exception e) {
e.printStackTrace();
result.setMsg("服务器内部错误!!");
} return result;
}
import javax.servlet.http.HttpServletRequest; import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired; import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.tx.beans.SysUser;
import com.tx.service.SysUserService; public class MyShiroRealm extends AuthorizingRealm{ @Autowired
SysUserService sysUserService; @Autowired
HttpServletRequest request; @Override//这里可以配置角色权限
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) { return null;
} @Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken)token;
String username = usernamePasswordToken.getUsername(); Wrapper<SysUser> wrapper = new EntityWrapper<SysUser>().eq("user_name", username);
SysUser user = sysUserService.selectOne(wrapper); request.getSession().setAttribute("loginUser", user); //使用MD5盐值加密
ByteSource credentialsSalt = ByteSource.Util.bytes(username); return new SimpleAuthenticationInfo(username, user.getUserPassword(), credentialsSalt, getName()); } }
@ResponseBody
@PostMapping("/login")
public AJAXResult login(@RequestParam(value="rememberMe",required=false) String rememberMe, SysUser sysUser ,HttpSession session) {
AJAXResult result = new AJAXResult();
try { Subject currentUser = SecurityUtils.getSubject();
if (!currentUser.isAuthenticated()) {
UsernamePasswordToken token = new UsernamePasswordToken(sysUser.getUserName(), sysUser.getUserPassword());
// rememberme
if("remember-me".equals(rememberMe)) {
token.setRememberMe(true);
}
try {
// 执行登录.
currentUser.login(token);
} catch (AuthenticationException ae) {
System.out.println("登录失败! " +ae );
}
}
result.setResult(true); } catch (Exception e) {
e.printStackTrace();
result.setMsg("服务器内部错误!!");
} return result;
}
本代码只是部分代码,具体逻辑根据项目情况编写!
6.Otherehcache.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>
<?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>







