1.配置Mybatis和mvc环境
2.shiro.ini
[main]
authc.loginUrl=/login
perms.unauthorizedUrl=/unauth.jsp
roles.unauthorizedUrl=/unauth.jsp
userRealm = org.shiro.realm.UserRealm
hashMatcher = org.apache.shiro.authc.credential.HashedCredentialsMatcher
hashMatcher.hashAlgorithmName=md5
userRealm.credentialsMatcher=$hashMatcher
securityManager.realms=$userRealm
[urls]
/admin/user/**=authc,roles[admin]
/admin/role/**=authc,roles[abc]
/admin/**=authc
/login=anon
/logout = logout
3.InitServlet.java
用于在自定义realm中加载bean
public class InitServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static WebApplicationContext wc;
@Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
//初始化spring的工厂
wc = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
}
public static WebApplicationContext getWc() {
return wc;
}
public static Object getBean(String name) {
return wc.getBean(name);
}
}
<servlet-mapping>
<servlet-name>shiro</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>initServlet</servlet-name>
<servlet-class>org.shiro.web.InitServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
4.自定义Realm
public class UserRealm extends AuthorizingRealm {
/**
* 授权
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(
PrincipalCollection principals) {
User user = ((User)principals.getPrimaryPrincipal());
int uid = user.getId();
System.out.println(user.getId()+","+user.getNickname());
IUserService userService = (IUserService)InitServlet.getBean("userService");
//得到用户所有角色
List<String> roles = userService.listRoleSnByUser(uid);
//得到用户角色对应的 资源URL
List<Resource> reses = userService.listAllResource(uid);
List<String> permissions = new ArrayList<String>();
for(Resource r:reses) {
permissions.add(r.getUrl());
}
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
info.setRoles(new HashSet<String>(roles));
info.setStringPermissions(new HashSet<String>(permissions));
return info;
}
/**
* 认证
*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(
AuthenticationToken token) throws AuthenticationException {
System.out.println("ccccccccccc-------------------------");
IUserService userService = (IUserService)InitServlet.getBean("userService");
String username = token.getPrincipal().toString();
String password = new String((char[])token.getCredentials());
System.out.println("password----------------------------"+password);
User user = userService.login(username, password);//得到用户
System.out.println("username----------------------------"+username);
SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, user.getPassword(), this.getName());
info.setCredentialsSalt(ByteSource.Util.bytes(user.getUsername()));//解密 前边 设置的盐值是用户名
return info;
}
}