常用的Java EE安全框架有shiro、spring security。shiro被应用非常广泛,可以集成cas,搭建单点登录系统。spring security则被认为比较重,应用没有shiro广泛。shiro提供用户名、密码验证,及密码的加密存储,会话Session的管理,与web集成,支持HTTPS的拦截。
Apache Shiro Security Configuration
/** = auth
org.apache.shiro
shiro-core
${shiro.version}
org.apache.shiro
shiro-web
${shiro.version}
org.apache.shiro
shiro-spring
${shiro.version}
org.crazycake
shiro-redis
${shiro.redis.version}
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
String username = (String)principals.getPrimaryPrincipal();
SysUser user = getUserByName(username);
SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
SysRole sysRole = sysRolePermService.getSysRoleByUserId(user.getId());
addRole(authorizationInfo,sysRole);
List sysPermissions = sysRolePermService.getSysPermissionByUserId(user.getId());
addPermissions(authorizationInfo,sysPermissions);
return authorizationInfo;
}
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
String username = (String)token.getPrincipal();
SysUser user = getUserByName(username);
//交给AuthenticatingRealm使用CredentialsMatcher进行密码匹配,如果觉得人家的不好可以自定义实现
if (user != null){
return new SimpleAuthenticationInfo(user.getUserName(),"", getName());
}
return null;
}
@Override
protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
HttpServletRequest httpRequest = (HttpServletRequest)request;
HttpServletResponse httpResponse = (HttpServletResponse)response;
//支持跨域
supportCrossDomain(httpResponse);
// 对外API,通过Service-Token进行认证
String url = httpRequest.getRequestURI().substring(httpRequest.getContextPath().length());
if (url.startsWith(HTTP_API_URL)) {
if (validateSign(httpRequest.getHeader("Service-Token"))) {
return true;
}
else {
return false;
}
}
//运营后台通过cookie,token,sid进行认证
Subject currentSubject = SecurityUtils.getSubject();
if (! currentSubject.isAuthenticated()){
SysUser sysTokenUser = loginAuthService.validTokenAuth((HttpServletRequest) request);
SysUser sysCookieUser = loginAuthService.validCookieAuth((HttpServletRequest) request);
if (sysTokenUser == null && sysCookieUser == null){
return false;
}
SysUser sysUser = null;
if (sysTokenUser != null){
sysUser = sysTokenUser;
}else {
sysUser = sysCookieUser;
}
UsernamePasswordToken token = new UsernamePasswordToken(sysUser.getUserName(),"");
currentSubject.login(token);
Session session = currentSubject.getSession();
session.setAttribute("LoginUser",sysUser);
}
//在request里设置登录用户
SysUser currentUser = (SysUser) currentSubject.getSession().getAttribute("LoginUser");
request.setAttribute("loginId", currentUser.getId());
return true;
}
@Override
protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
response.setContentType("application/json; charset=utf-8");
response.getWriter().write(json);
return false;
}
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import java.util.Set;
public class RedisManager extends org.crazycake.shiro.RedisManager {
private String host = "127.0.0.1";
private int port = 6379;
// 0 - never expire
private int expire = 0;
// timeout for jedis try to connect to redis server, not expire time! In
// milliseconds
private int timeout = 0;
private String password = "";
private int dataBase;
private static JedisPool jedisPool = null;
public RedisManager() {
}
/**
* 初始化方法
*/
public void init() {
if (jedisPool == null) {
if (password != null && "".equals(password.trim())) {
password = null;
}
jedisPool = new JedisPool(new JedisPoolConfig(), host, port, timeout, password, dataBase);
}
}
/**
* get value from redis
*
* @param key
* @return
*/
public byte[] get(byte[] key) {
byte[] value = null;
Jedis jedis = jedisPool.getResource();
try {
value = jedis.get(key);
} finally {
jedis.close();
}
return value;
}
/**
* set
*
* @param key
* @param value
* @return
*/
public byte[] set(byte[] key, byte[] value) {
Jedis jedis = jedisPool.getResource();
try {
jedis.set(key, value);
if (this.expire != 0) {
jedis.expire(key, this.expire);
}
} finally {
jedis.close();
}
return value;
}
/**
* set
*
* @param key
* @param value
* @param expire
* @return
*/
public byte[] set(byte[] key, byte[] value, int expire) {
Jedis jedis = jedisPool.getResource();
try {
jedis.set(key, value);
if (expire != 0) {
jedis.expire(key, expire);
}
} finally {
jedis.close();
}
return value;
}
/**
* del
*
* @param key
*/
public void del(byte[] key) {
Jedis jedis = jedisPool.getResource();
try {
jedis.del(key);
} finally {
jedis.close();
}
}
/**
* flush
*/
public void flushDB() {
Jedis jedis = jedisPool.getResource();
try {
jedis.flushDB();
} finally {
jedis.close();
}
}
/**
* size
*/
public Long dbSize() {
Long dbSize = 0L;
Jedis jedis = jedisPool.getResource();
try {
dbSize = jedis.dbSize();
} finally {
jedis.close();
}
return dbSize;
}
/**
* keys
*
* @param pattern
* @return
*/
public Set keys(String pattern) {
Set keys = null;
Jedis jedis = jedisPool.getResource();
try {
keys = jedis.keys(pattern.getBytes());
} finally {
jedis.close();
}
return keys;
}
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
public int getExpire() {
return expire;
}
public void setExpire(int expire) {
this.expire = expire;
}
public int getTimeout() {
return timeout;
}
public void setTimeout(int timeout) {
this.timeout = timeout;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getDataBase() {
return dataBase;
}
public void setDataBase(int dataBase) {
this.dataBase = dataBase;
}
}