上一篇文章我们介绍了Shiro自带的JdbcRealm的使用,传送门:第一个例子JdbcRealm的使用
在做登录实现之前我们先做注册实现,很简单只需要做常规的insert即可,需要注意就密码需要加密。
public int save(UserEntity entity) {
entity.setPassword(CryptUtils.sha512(entity.getLoginName(),entity.getPassword()));
//添加角色
return super.save(entity);
}
/**
* 密码工具类
*/
public class CryptUtils {
public static String generateSalt(String text){
return new SimpleHash("md5",text,text,1024).toHex().substring(0,16);
}
public static String sha512(String username,String passwrod){
return new SimpleHash("sha-512",passwrod,generateSalt(username),1024).toBase64();
}
}
自定义Realm的用法和JdbcRealm的用法差不多,下面我们来写一个
新建一个类名为:SystemAuthorizingRealm,继承自:AuthorizingRealm
public class SystemAuthorizingRealm extends AuthorizingRealm {
/**
* 授权
* @param principalCollection
* @return
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
return null;
}
/**
* 认证
* @param authenticationToken
* @return
* @throws AuthenticationException
*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken)
throws AuthenticationException {
return null;
}
}
当然也可以继承AuthenticatingRealm,只需实现认证方法doGetAuthenticationInfo(),AuthorizingRealm是AuthenticatingRealm的子类,实现了认证和授权功能,比父类更强大。
doGetAuthenticationInfo(AuthenticationToken authenticationToken):认证方法,用来登录的时候跟数据库用户名密码匹配的一个方法,只需要返回一个SimpleAuthenticationInfo,下面我们来实现一下。
public class SystemAuthorizingRealm extends AuthorizingRealm {
@Autowired
private UserService userService;
/**
* 认证
* @param authenticationToken
* @return
* @throws AuthenticationException
*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken)
throws AuthenticationException {
//获取用户名
String username = (String) authenticationToken.getPrincipal();
UserEntity user = userService.getByUsername(username);
if (user != null){
SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(username,user.getPassword()
,ByteSource.Util.bytes(CryptUtils.generateSalt(user.getLoginName())),getName());
return simpleAuthenticationInfo;
}else {
return null;
}
}
}
new SimpleAuthenticationInfo():构造有需要传递2-4参数都有,可自行选择,我这里用的是4个参数分别的用户名、密码、密码盐,realm名称。密码盐我是根据用户名来实现,你们自己实现即可。
public SimpleAuthenticationInfo(Object principal, Object credentials, String realmName) {
this.principals = new SimplePrincipalCollection(principal, realmName);
this.credentials = credentials;
}
public SimpleAuthenticationInfo(Object principal, Object hashedCredentials, ByteSource credentialsSalt, String realmName) {
this.principals = new SimplePrincipalCollection(principal, realmName);
this.credentials = hashedCredentials;
this.credentialsSalt = credentialsSalt;
}
public SimpleAuthenticationInfo(PrincipalCollection principals, Object credentials) {
this.principals = new SimplePrincipalCollection(principals);
this.credentials = credentials;
}
public SimpleAuthenticationInfo(PrincipalCollection principals, Object hashedCredentials, ByteSource credentialsSalt) {
this.principals = new SimplePrincipalCollection(principals);
this.credentials = hashedCredentials;
this.credentialsSalt = credentialsSalt;
}
doGetAuthorizationInfo(PrincipalCollection principalCollection):授权方法,用于登录成功后执行的授权方法,具体实现如下:
public class SystemAuthorizingRealm extends AuthorizingRealm {
@Autowired
private RoleService roleService;
/**
* 授权
* @param principalCollection
* @return
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
//获取用户名
String username = (String) principalCollection.getPrimaryPrincipal();
UserEntity user = userService.getByUsername(username);
if (user != null){
List<RoleEntity> roleList = user.getRoleList();
//添加角色权限
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
for (RoleEntity roleEntity : roleList) {
RoleEntity role = roleService.getByRoleName(roleEntity.getEnname());
info.setStringPermissions(role.getMenuList().stream().map(MenuEntity::getPermission).collect(Collectors.toSet()));
}
info.setRoles(roleList.stream().map(RoleEntity::getEnname).collect(Collectors.toSet()));
return info;
}
return null;
}
}
最后返回一个SimpleAuthorizationInfo(),设置从数据库查到的角色权限即可。
Spring配置realm
<bean class="com.demo.sys.security.realm.SystemAuthorizingRealm" id="systemAuthorizingRealm">
<property name="credentialsMatcher">
<bean class="org.apache.shiro.authc.credential.HashedCredentialsMatcher" id="credentialsMatcher">
<property name="hashIterations" value="1024"></property>
<property name="hashAlgorithmName" value="sha-512"></property>
<property name="storedCredentialsHexEncoded" value="false"></property>
</bean>
</property>
</bean>
<bean class="org.apache.shiro.web.mgt.DefaultWebSecurityManager" id="securityManager">
<property name="realm" ref="systemAuthorizingRealm"></property>
</bean>
后述问题
1. 不想在Web页面URL后面显示;JSSONID=xxx,如:http:localhost:8080/login;JSESSONID=xxx
<bean class="org.apache.shiro.web.session.mgt.DefaultWebSessionManager" id="sessionManager">
<property name="sessionIdUrlRewritingEnabled" value="false"></property>
</bean>
<bean class="org.apache.shiro.web.mgt.DefaultWebSecurityManager" id="securityManager">
<property name="realm" ref="systemAuthorizingRealm"></property>
<property name="sessionManager" ref="sessionManager"></property>
</bean>
2. 控制台报:JSESSONID SessionException: There is no session with id [9f3e2cbd-5a1a-4813-8138-a41497a9
<bean id="simpleCookie" class="org.apache.shiro.web.servlet.SimpleCookie">
<constructor-arg name="name" value="shiro.sesssion"/>
<property name="path" value="/"/>
</bean>
<bean class="org.apache.shiro.web.session.mgt.DefaultWebSessionManager" id="sessionManager">
<property name="sessionIdCookie" ref="simpleCookie"></property>
<property name="sessionIdUrlRewritingEnabled" value="false"></property>
</bean>
<bean class="org.apache.shiro.web.mgt.DefaultWebSecurityManager" id="securityManager">
<property name="realm" ref="systemAuthorizingRealm"></property>
<property name="sessionManager" ref="sessionManager"></property>
</bean>