shiro的登录验证

package com.book.app.utils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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.beans.factory.annotation.Autowired;

import com.book.app.bean.Role;
import com.book.app.bean.User;
import com.book.app.service.UserService;
/**
*
* 功能:授权和认证
* 作者:张
* 2018年10月18日上午10:16:58
*/
public class MyRealm extends AuthorizingRealm {
@Autowired
private UserService userService;

@Override
//登录验证
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
//获得邮箱
SimpleAuthenticationInfo info=null;
String email= (String) token.getPrincipal();
Map<String,Object> map = new HashMap<String,Object>();
map.put("email", email);
User user = login(map);
if(user != null) {
info = new SimpleAuthenticationInfo(user.getEmail(),user.getAccount(),getName());
}
return info;
}
private User login(Map<String, Object> map) {
return userService.login(map);
}
@Override
//权限分配
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
Map<String,Object> map = new HashMap<String, Object>();
map.put("email", (String)principals.getPrimaryPrincipal());
User user = login(map);
if(user !=null) {
List<String> roleNames= new ArrayList<String>();
List<Role> listRole = user.getListRole();
for(Role r:listRole) {
roleNames.add(r.getrName());
}
info.addRoles(roleNames);
}
return info;
}


}

posted @ 2018-12-06 16:22  心态良  Views(278)  Comments(0Edit  收藏  举报