shiro demo优化

This commit is contained in:
haiming 2019-04-19 17:15:09 +08:00
parent 045c5ff487
commit 866332a289
3 changed files with 58 additions and 40 deletions

View File

@ -5,6 +5,8 @@ import java.util.Date;
import javax.servlet.http.HttpSession;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.crypto.RandomNumberGenerator;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.apache.shiro.subject.Subject;
import org.nutz.boot.NbApp;
@ -20,40 +22,43 @@ import io.nutz.demo.simple.bean.User;
@IocBean(create="init")
public class MainLauncher {
@Inject
protected Dao dao;
@Inject
protected Dao dao;
@Ok("raw")
@At("/time/now")
public long now() {
return System.currentTimeMillis();
}
@Ok("raw")
@At("/shiro/test")
public boolean isAuthenticated(HttpSession session) {
Subject subject = SecurityUtils.getSubject();
return subject.isAuthenticated();
Subject subject = SecurityUtils.getSubject();
return subject.isAuthenticated();
}
public void init() {
Daos.createTablesInPackage(dao, User.class, false);
dao.insert(newUser("admin", "123456"));
dao.insert(newUser("wendal", "123123"));
Daos.createTablesInPackage(dao, User.class, false);
dao.insert(newUser("admin", "123456"));
dao.insert(newUser("wendal", "123123"));
}
protected static User newUser(String name, String password) {
User user = new User();
user.setName(name);
user.setSalt(R.UU32());
user.setPassword(new Sha256Hash(password, user.getSalt()).toHex());
user.setCreateTime(new Date());
return user;
User user = new User();
user.setName(name);
RandomNumberGenerator rng = new SecureRandomNumberGenerator();
String salt = rng.nextBytes().toBase64();
user.setSalt(salt);
String hashedPasswordBase64 = new Sha256Hash(password, salt, 1024).toBase64();
user.setPassword(hashedPasswordBase64);
user.setCreateTime(new Date());
return user;
}
public static void main(String[] args) throws Exception {
new NbApp().setPrintProcDoc(true).run();
new NbApp().setPrintProcDoc(true).run();
}
}

View File

@ -39,12 +39,9 @@ public class UserModule {
User user = dao.fetch(User.class, username);
if (user == null)
return false;
Sha256Hash hash = new Sha256Hash(password, user.getSalt());
if (!hash.toHex().equals(user.getPassword())) {
return false;
}
Subject subject = SecurityUtils.getSubject();
subject.login(new SimpleShiroToken(user.getId()));
ThreadContext.bind(subject);
subject.login(new UsernamePasswordToken(username,password,false));
return true;
}

View File

@ -1,25 +1,29 @@
package io.nutz.demo.simple.shiro;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAccount;
import org.apache.shiro.authc.*;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.cache.CacheManager;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.nutz.dao.Dao;
import org.nutz.integration.shiro.AbstractSimpleAuthorizingRealm;
import org.nutz.integration.shiro.SimpleShiroToken;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import io.nutz.demo.simple.bean.User;
@IocBean(name="shiroRealm", fields="dao")
public class SimpleAuthorizingRealm extends AbstractSimpleAuthorizingRealm {
@IocBean(name="shiroRealm")
public class SimpleAuthorizingRealm extends AuthorizingRealm {
@Inject
Dao dao;
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
// null usernames are invalid
@ -27,23 +31,28 @@ public class SimpleAuthorizingRealm extends AbstractSimpleAuthorizingRealm {
throw new AuthorizationException("PrincipalCollection method argument cannot be null.");
}
long userId = ((Number) principals.getPrimaryPrincipal()).longValue();
User user = dao().fetch(User.class, userId);
User user = dao.fetch(User.class, userId);
if (user == null)
return null;
SimpleAuthorizationInfo auth = new SimpleAuthorizationInfo();
auth.addRole(user.getName());
auth.addStringPermission("user:list");
return auth;
return auth;
}
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
SimpleShiroToken upToken = (SimpleShiroToken) token;
UsernamePasswordToken upToken = (UsernamePasswordToken) token;
User user = dao().fetch(User.class, (Long)upToken.getPrincipal());
if (user == null)
User user = dao.fetch(User.class, upToken.getUsername());
if (user == null) {
return null;
return new SimpleAccount(user.getId(), user.getPassword(), getName());
}
SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user,
user.getPassword().toCharArray(), ByteSource.Util.bytes(user.getSalt()), getName());
info.setCredentialsSalt(ByteSource.Util.bytes(user.getSalt()));
// info.
return info;
}
public SimpleAuthorizingRealm() {
@ -52,7 +61,14 @@ public class SimpleAuthorizingRealm extends AbstractSimpleAuthorizingRealm {
public SimpleAuthorizingRealm(CacheManager cacheManager, CredentialsMatcher matcher) {
super(cacheManager, matcher);
setAuthenticationTokenClass(SimpleShiroToken.class);
HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();
hashedCredentialsMatcher.setHashAlgorithmName("SHA-256");
hashedCredentialsMatcher.setHashIterations(1024);
// 这一行决定hex还是base64
hashedCredentialsMatcher.setStoredCredentialsHexEncoded(false);
// 设置token类型是关键!!!
setCredentialsMatcher(hashedCredentialsMatcher);
setAuthenticationTokenClass(UsernamePasswordToken.class);
}
public SimpleAuthorizingRealm(CacheManager cacheManager) {
@ -62,5 +78,5 @@ public class SimpleAuthorizingRealm extends AbstractSimpleAuthorizingRealm {
public SimpleAuthorizingRealm(CredentialsMatcher matcher) {
this(null, matcher);
}
}