shiro controller进行用户验证


@RequestMapping(value = "/checkUser",method= RequestMethod.POST)
public @ResponseBody
CommResult<Object> checkUser(HttpServletRequest request, HttpServletResponse response, ModelMap model) throws Exception {
CommResult<Object> cr = new CommResult<Object>();
try {

//随机数
String strData = request.getParameter( "strData" );
//加密后的随机数
String strSignedData = request.getParameter( "strSignedData" );
//B64编码的公钥证书
String strCertData = request.getParameter( "strCertData" );
//验证随机数的有效性
String certNumber = SecAuthUtil.getCertSN(strCertData);//ca序列号
String certExpDate = SecAuthUtil.getCertExpDate(strCertData);//CA有效期
CommResult cr2 = baseInterface.verifyCaSignData( strData, strSignedData, strCertData );
if (!cr2.isSuccess()) {
return cr2;
}
String commonCapName = baseInterface.getCertCommonOrgName( strCertData ); // 证书通用名
UcenterOrgUserVo userOrgVo = new UcenterOrgUserVo();
userOrgVo.setCaCompName( commonCapName );
userOrgVo.setStatus( DicDataEnum.dataStatusValid.getId() );
UcenterOrgUserVo ucenterOrgUserVo = null;
List<UcenterOrgUserVo> userVoList = this.ucenterOrgUserService.queryForList( userOrgVo );
if (!userVoList.isEmpty()) {
this.baseInterface.updateCaNumber( userVoList.get( 0 ).getId(),strCertData );
}
Subject currentUser = SecurityUtils.getSubject();
if (currentUser.isAuthenticated()) {
currentUser.logout();
}
UcenterUserVo userVo = this.ucenterUserService.getById( userVoList.get( 0 ).getUserId());
return dologin(currentUser, userVo, false );
}
catch (Exception e) {
cr.setSuccess(false);
cr.setResult(CommResultEnum.ERROR,"异常发生!");
cr.setMsg( "请检查CA是否已绑定!" );
log.error("异常发生!", e);
return cr;
}

}

private CommResult<Object> dologin(Subject currentUser,UcenterUserVo checkUser, boolean isCalogin) {
CommResult<Object> cr = new CommResult<Object>();
CommResultEnum res = CommResultEnum.SUCCESS;
UpmsToken token = new UpmsToken(checkUser.getAccount(), checkUser.getPassword(), isCalogin ? LoginType.USER_CA.getType() : LoginType.USER.getType());


try {
TokenManager.login(token);
} catch (LockedAccountException lae) {
res = CommResultEnum.USER_ACCOUNT_IS_LOCKED;
} catch (UnknownAccountException uae) {
res = CommResultEnum.USER_INVALID_USERNAME_OR_PASS;
} catch (IncorrectCredentialsException ice) {
res = CommResultEnum.USER_INVALID_USERNAME_OR_PASS;
} catch (AuthenticationException ae) {
res = CommResultEnum.USER_INVALID_USERNAME_OR_PASS;
} catch (Exception e) {
res = CommResultEnum.ERROR;
}
cr.setResult( res );
return cr;
}




public class UpmsToken extends UsernamePasswordToken {
private String loginType;

public UpmsToken(String username, String password, String loginType) {
super(username, password);
this.loginType = loginType;
}

public String getLoginType() {
return this.loginType;
}

public void setLoginType(String loginType) {
this.loginType = loginType;
}
}


[size=large][color=red][b]realm关联数据库[/b][/color][/size]

public class CAUserRealm extends AuthorizingRealm {
@Autowired
public IUcenterRoleMenuService ucenterRoleMenuService;
@Autowired
public IUcenterUserService ucenterUserService;

public CAUserRealm() {
}

protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
if (!SecurityUtils.getSubject().isAuthenticated()) {
this.doClearCache(principalCollection);
SecurityUtils.getSubject().logout();
return null;
} else {
Collection realms = principalCollection.fromRealm(this.getName());
if (realms.size() == 0) {
return null;
} else {
String userId = ShiroKit.getUser().getId();
if (StringUtils.isBlank(userId)) {
return null;
} else {
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
SecurityUcenterUserInfoVo securityUserInfoVo = this.ucenterRoleMenuService.querySecurityUserInfo(userId);
info.addRoles(securityUserInfoVo.getRoleCodeList());
info.addStringPermissions(securityUserInfoVo.getPermissions());
return info;
}
}
}
}

protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authToken) throws AuthenticationException {
UpmsToken token = (UpmsToken)authToken;
UcenterUserVo user = this.ucenterUserService.getUserByAccount(token.getUsername());
if (user == null) {
throw new UnknownAccountException("账号密码错误");
} else if (DicDataEnum.userLocked.getIntId().toString().equals(user.getStatus())) {
throw new LockedAccountException("账号被锁定");
} else if (DicDataEnum.userStop.getIntId().toString().equals(user.getStatus())) {
throw new LockedAccountException("账号已停用");
} else {
UpmsShiroUser shiroUser = new UpmsShiroUser();
shiroUser.setAccount(user.getAccount());
shiroUser.setId(user.getId());
shiroUser.setLoginType(token.getLoginType());
shiroUser.setOrgId(user.getOrgId());
shiroUser.setUserName(user.getUsername());
return new SimpleAuthenticationInfo(shiroUser, user.getPassword(), this.getName());
}
}

public void clearCachedAuthorizationInfo() {
PrincipalCollection principalCollection = SecurityUtils.getSubject().getPrincipals();
SimplePrincipalCollection principals = new SimplePrincipalCollection(principalCollection, this.getName());
super.clearCachedAuthorizationInfo(principals);
}

public void clearCachedAuthorizationInfo(PrincipalCollection principalCollection) {
SimplePrincipalCollection principals = new SimplePrincipalCollection(principalCollection, this.getName());
super.clearCachedAuthorizationInfo(principals);
}

public boolean isPermitted(PrincipalCollection principals, String permission) {
return super.isPermitted(principals, permission);
}

public String getName() {
return LoginType.USER.toString();
}
}


[size=large][color=red][b]shiro小工具[/b][/color][/size]

public class ShiroKit {
private static final String NAMES_DELIMETER = ",";
public static final String hashAlgorithmName = "MD5";
public static final int hashIterations = 1024;

public ShiroKit() {
}

public static String md5(String credentials, String saltSource) {
ByteSource salt = new Md5Hash(saltSource);
return (new SimpleHash("MD5", credentials, salt, 1024)).toString();
}

public static String md5(String credentials) {
return (new SimpleHash("MD5", credentials)).toString();
}

public static String getRandomSalt(int length) {
return RandomUtil.generateRandomString(length);
}

public static Subject getSubject() {
return SecurityUtils.getSubject();
}

public static boolean isUser() {
return getSubject() != null && getSubject().getPrincipal() != null;
}

public static boolean isGuest() {
return !isUser();
}

public static UpmsShiroUser getUser() {
return isGuest() ? null : (UpmsShiroUser)getSubject().getPrincipals().getPrimaryPrincipal();
}

public static Session getSession() {
return getSubject().getSession();
}

public static <T> T getSessionAttr(String key) {
Session session = getSession();
return session != null ? session.getAttribute(key) : null;
}

public static void setSessionAttr(String key, Object value) {
Session session = getSession();
session.setAttribute(key, value);
}

public static void removeSessionAttr(String key) {
Session session = getSession();
if (session != null) {
session.removeAttribute(key);
}

}

public static boolean hasRole(String roleName) {
return getSubject() != null && roleName != null && roleName.length() > 0 && getSubject().hasRole(roleName);
}

public static boolean lacksRole(String roleName) {
return !hasRole(roleName);
}

public static boolean hasAnyRoles(String roleNames) {
boolean hasAnyRole = false;
Subject subject = getSubject();
if (subject != null && roleNames != null && roleNames.length() > 0) {
String[] var3 = roleNames.split(",");
int var4 = var3.length;

for(int var5 = 0; var5 < var4; ++var5) {
String role = var3[var5];
if (subject.hasRole(role.trim())) {
hasAnyRole = true;
break;
}
}
}

return hasAnyRole;
}

public static boolean hasAllRoles(String roleNames) {
boolean hasAllRole = true;
Subject subject = getSubject();
if (subject != null && roleNames != null && roleNames.length() > 0) {
String[] var3 = roleNames.split(",");
int var4 = var3.length;

for(int var5 = 0; var5 < var4; ++var5) {
String role = var3[var5];
if (!subject.hasRole(role.trim())) {
hasAllRole = false;
break;
}
}
}

return hasAllRole;
}

public static boolean hasPermission(String permission) {
return getSubject() != null && permission != null && permission.length() > 0 && getSubject().isPermitted(permission);
}

public static boolean lacksPermission(String permission) {
return !hasPermission(permission);
}

public static boolean isAuthenticated() {
return getSubject() != null && getSubject().isAuthenticated();
}

public static boolean notAuthenticated() {
return !isAuthenticated();
}

public static String principal() {
if (getSubject() != null) {
Object principal = getSubject().getPrincipal();
return principal.toString();
} else {
return "";
}
}

public static boolean isAjax(ServletRequest request) {
return "XMLHttpRequest".equalsIgnoreCase(((HttpServletRequest)request).getHeader("X-Requested-With"));
}
}




<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<property name="authenticator" ref="authenticator"/>
<!-- 基于数据库登录校验的实现-->
<property name="realms">
<list>
<ref bean="ucenterUserRealm"/>
<ref bean="caRealm"/>
</list>
</property>
<!-- session 管理器 -->
<property name="sessionManager" ref="sessionManager"/>
<!-- 缓存管理器 -->
<property name="cacheManager" ref="upmsShiroCacheManager"/>
</bean>
<!-- 配置使用自定义认证器,可以实现多Realm认证,并且可以指定特定Realm处理特定类型的验证 -->
<bean id="authenticator" class="com.hisea.upms.security.shiro.pam.UpmsModularRealmAuthenticator">
<!-- 配置认证策略,只要有一个Realm认证成功即可,并且返回所有认证成功信息 -->
<property name="authenticationStrategy">
<bean class="org.apache.shiro.authc.pam.AtLeastOneSuccessfulStrategy"></bean>
</property>
<!-- 基于数据库登录校验的实现-->
<property name="realms">
<list>
<ref bean="ucenterUserRealm"/>
<ref bean="caRealm"/>
</list>
</property>
</bean>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值