springmvc+shiro登录登出

springmvc + shiro 登录登出
2012-09-10 10:59 511人阅读 评论(1) 收藏 举报
[java] view plaincopyprint?

@Controller
@RequestMapping(value = "/roll")
public class RollLoginController {

@RequestMapping(value = "/login", method = RequestMethod.POST)
@ResponseBody
public String login(@RequestParam("username") String username,
@RequestParam("password") String password) {

Subject currentUser = SecurityUtils.getSubject();
String result = "login";
if (!currentUser.isAuthenticated()) {
result = login(currentUser,username,password);
}else{//重复登录
ShiroUser shiroUser = (ShiroUser) currentUser.getPrincipal();
if(!shiroUser.getLoginName().equalsIgnoreCase(username)){//如果登录名不同
currentUser.logout();
result = login(currentUser,username,password);
}
}
return result;
}

private String login(Subject currentUser,String username,String password){
String result = "login";
UsernamePasswordToken token = new UsernamePasswordToken(username,
password);
token.setRememberMe(false);
try {
currentUser.login(token);
result = "success";
} catch (UnknownAccountException uae) {
result = "failure";
} catch (IncorrectCredentialsException ice) {
result = "failure";
} catch (LockedAccountException lae) {
result = "failure";
} catch (AuthenticationException ae) {
result = "failure";
}
return result;
}

@RequestMapping(value = "/logout", method = RequestMethod.POST)
@ResponseBody
public String logout() {

Subject currentUser = SecurityUtils.getSubject();
String result = "logout";
currentUser.logout();
return result;
}

@RequestMapping(value = "/chklogin", method = RequestMethod.POST)
@ResponseBody
public String chkLogin() {

Subject currentUser = SecurityUtils.getSubject();

if (!currentUser.isAuthenticated()) {
return "false";
}

return "true";
}

}

applicationContext-shiro.xml
[html] view plaincopyprint?

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd"
default-lazy-init="true">

<description>Shiro Configuration</description>

<!-- Shiro's main business-tier object for web-enabled applications -->
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager" depends-on="userDao,groupDao">
<property name="realm" ref="shiroDbRealm" />
<property name="cacheManager" ref="cacheManager" />
</bean>

<!-- 項目自定义的Realm -->
<bean id="shiroDbRealm" class="org.springside.examples.miniweb.service.account.ShiroDbRealm">
<property name="accountManager" ref="accountManager"/>
</bean>

<!-- Shiro Filter -->
<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
<property name="securityManager" ref="securityManager" />
<property name="loginUrl" value="/login" />
<property name="successUrl" value="/account/user/" />
<property name="filterChainDefinitions">
<value>
/rollindex = anon
/index.html = anon
/login = authc
/logout = logout
/static/** = anon
/admin/** = user
/account/** = user
</value>
</property>
</bean>

<!-- 用户授权信息Cache -->
<bean id="cacheManager" class="org.apache.shiro.cache.MemoryConstrainedCacheManager" />

<!-- 保证实现了Shiro内部lifecycle函数的bean执行 -->
<bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>

<!-- AOP式方法级权限检查 -->
<bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator" depends-on="lifecycleBeanPostProcessor">
<property name="proxyTargetClass" value="true" />
</bean>

<bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
<property name="securityManager" ref="securityManager"/>
</bean>
</beans>

[java] view plaincopyprint?

ShiroDbRealm.java

[java] view plaincopyprint?

public class ShiroDbRealm extends AuthorizingRealm {

private static Logger logger = LoggerFactory.getLogger(ShiroDbRealm.class);

private static final String ALGORITHM = "MD5";
private AccountManager accountManager;

/**
* 认证回调函数, 登录时调用.
*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(
AuthenticationToken authcToken) throws AuthenticationException {
UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
User user = accountManager.findUserByLoginName(token.getUsername());
if (user != null) {
return new SimpleAuthenticationInfo(new ShiroUser(
user.getName(), user.getRealName()), user.getPassword(),
getName());
} else {
return null;
}
}

/**
* 授权查询回调函数, 进行鉴权但缓存中无用户的授权信息时调用.
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(
PrincipalCollection principals) {
ShiroUser shiroUser = (ShiroUser) principals.fromRealm(getName())
.iterator().next();
User user = accountManager
.findUserByLoginName(shiroUser.getLoginName());
//基于Permission的权限信息
if (user != null) {
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
for (Role role : user.getRoles()) {
for(Permission permission: role.getPermisssions()){
info.addStringPermission(permission.getValue());
}
}
return info;
} else {
return null;
}
}

/**
* 更新用户授权信息缓存.
*/
public void clearCachedAuthorizationInfo(String principal) {
SimplePrincipalCollection principals = new SimplePrincipalCollection(
principal, getName());
clearCachedAuthorizationInfo(principals);
}

/**
* 清除所有用户授权信息缓存.
*/
public void clearAllCachedAuthorizationInfo() {
Cache<Object, AuthorizationInfo> cache = getAuthorizationCache();
if (cache != null) {
for (Object key : cache.keys()) {
cache.remove(key);
}
}
}

@Autowired
public void setAccountManager(AccountManager accountManager) {
this.accountManager = accountManager;
}

public String encrypt(String plainText) {
String result = "";
byte[] hashPassword = null;
try {
hashPassword = Digests.md5(new ByteArrayInputStream(plainText
.getBytes()));
} catch (IOException e) {
e.printStackTrace();
}
result = Encodes.encodeHex(hashPassword);
return result;

}

@PostConstruct
public void initCredentialsMatcher() {//MD5加密
HashedCredentialsMatcher matcher = new HashedCredentialsMatcher(
ALGORITHM);
setCredentialsMatcher(matcher);
}

/**
* 自定义Authentication对象,使得Subject除了携带用户的登录名外还可以携带更多信息.
*/
public static class ShiroUser implements Serializable {

private static final long serialVersionUID = -1748602382963711884L;
private String loginName;
private String name;

public ShiroUser(String loginName, String name) {
this.loginName = loginName;
this.name = name;
}

public String getLoginName() {
return loginName;
}

/**
* 本函数输出将作为默认的<shiro:principal/>输出.
*/
@Override
public String toString() {
return loginName;
}

public String getName() {
return name;
}
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值