You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

70 lines
2.5 KiB
Java

6 years ago
package com.bsd.cases.shiro;
import com.bsd.cases.model.BoUsers;
import com.bsd.cases.service.BoUsersService;
import com.bsd.cases.util.JWTUtil;
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.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
@Component
public class CommonRealm extends AuthorizingRealm {
@Resource
private BoUsersService boUsersService;
/**
* Shiro
*/
@Override
public boolean supports(AuthenticationToken token) {
return token instanceof JWTToken;
}
/**
* checkRole,checkPermission
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
String key = JWTUtil.getKey(principals.toString());
BoUsers boUsers = boUsersService.selectByUserNoOrOpenId(key);
SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
// simpleAuthorizationInfo.addRole(user.getRole().toString());
// Set<String> permission = new HashSet<>(Arrays.asList(user.getPermission().split(",")));
// simpleAuthorizationInfo.addStringPermissions(permission);
return simpleAuthorizationInfo;
}
/**
* 使
*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken auth) throws AuthenticationException {
String token = (String) auth.getCredentials();
// 解密获得username用于和数据库进行对比
String key = JWTUtil.getKey(token);
if (key == null) {
throw new AuthenticationException("token invalid");
}
BoUsers boUsers = boUsersService.selectByUserNoOrOpenId(key);
if (boUsers == null) {
throw new AuthenticationException("User didn't existed!");
}
if (!JWTUtil.verify(token, key)) {
throw new AuthenticationException("Username or password error");
}
return new SimpleAuthenticationInfo(token, token, "common_ream");
}
}