您的位置:首页 > 其它

Shiro入门之授权与认证

2017-09-03 21:11 267 查看

导读

本文简单介绍spring MVC 和Shiro的整合以及Shiro的授权与认证。

Spring与Shiro整合

引入依赖

在porn.xml文件下加入:

<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.3.2</version>
</dependency>


spring-mvc.xml文件配置

在spring配置文件中加入:

<!-- 继承自AuthorizingRealm的自定义Realm,即指定Shiro验证用户登录的类为自定义的UserRealm.java -->
<bean id="userRealm" class="com.li.demo.shiro.UserRealm"/>
<!-- 这里主要是设置自定义的单Realm应用,若有多个Realm,可使用'realms'属性代替 -->
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<property name="realm" ref="userRealm"/>
</bean>
<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
<!-- Shiro的核心安全接口,这个属性是必须的 -->
<property name="securityManager" ref="securityManager"/>
<!-- 要求登录时的链接(可根据项目的URL进行替换),非必须的属性,默认会自动寻找Web工程根目录下的"/login.html"页面 -->
<property name="loginUrl" value="/login.jsp"/>
<!-- 登录成功后要跳转的连接  -->
<property name="successUrl" value="/index.jsp"/>
<!-- 用户访问未对其授权的资源时,所显示的连接 -->
<property name="unauthorizedUrl" value="/"/>
<property name="filterChainDefinitions">
<!--某些资源及路径请求默认不拦截 -->
<value>
/js/** = anon
/statics/**=anon
/login.jsp=anon
/user/login = anon
/weblanguage=anon
/**=authc
</value>
</property>
</bean>


web.xml文件配置

在web.xml配置中加入Shiro过滤器

<filter>
<filter-name>shiroFilter</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
<init-param>
<param-name>targetFilterLifecycle</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>shiroFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>


Shiro认证

定义数据源

数据源一般是跟数据库连接的,这里我为了简便,就没有连。

public class UserRealm extends AuthorizingRealm{
@Override
protected AuthenticationInfo doGetAuthenticationInfo(
AuthenticationToken token) throws AuthenticationException {
String username = (String) token.getPrincipal();
String password = new String((char[]) token.getCredentials());
//账号不存在
if(!username.equals("li")  && !username.equals("huang")) {
throw new UnknownAccountException("账号或密码不正确");
}
//密码错误
if(!password.equals("123")) {
throw new IncorrectCredentialsException("账号或密码不正确");
}
//账号锁定 这里请忽略。。。
if(password.length() > 6){
throw new LockedAccountException("账号已被锁定,请联系管理员");
}
SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(username, password, getName());
return info;
}
}


登录请求逻辑处理

@Controller
public class UserLoginController {

@RequestMapping(value = "/user/login" , method = RequestMethod.POST )
@ResponseBody
public Map<String, Object> login(HttpServletRequest request,HttpServletResponse response,String username, String password) throws IOException {
HashMap<String, Object> data = new HashMap<String, Object>();
try {
Subject subject = SecurityUtils.getSubject();
UsernamePasswordToken token = new UsernamePasswordToken(username, password);
subject.login(token);

} catch (UnknownAccountException e) {
System.out.println(e.getMessage());
}catch (IncorrectCredentialsException e) {
System.out.println(e.getMessage());
}catch (LockedAccountException e) {
System.out.println(e.getMessage());
}catch (AuthenticationException e) {
System.out.println(e.getMessage());
}
data.put("code", "登录成功");
return data;
}
}


当用户在前端页面输入用户名“li”或“huang”及密码“123”就会登录成功。至于为什么用两个用户名,是为了下面的权限控制

Shiro授权

配置权限

在UserRealm.java文件中加入如下内容:

@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principal) {
// TODO Auto-generated method stub
String username = (String)principal.getPrimaryPrincipal();
Set<String> permisionSet = new HashSet<String>();
if (username.equals("li")) {
permisionSet.add("li:save");
permisionSet.add("li:update");
permisionSet.add("li:delete");
permisionSet.add("li:query");
}
if (username.equals("huang")) {
permisionSet.add("huang:updae");
permisionSet.add("huang:query");
}
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
info.setStringPermissions(permisionSet);
return
8c36
info;
}


配置好权限后,如果想在前端页面根据登录用户不同显示不同的内容可以利用标签控制,当然要现在.jsp文件中先引入shiro标签库 <%@ taglib prefix=”shiro” uri=”http://shiro.apache.org/tags” %>

<shiro:hasPermission name="li:delete">
<button type="button">删除</button>
</shiro:hasPermission>


根据前面的权限配置,只有登录名为“li”的用户才可以看到这个“删除”按钮的

@RequestMapping(value = "/user/save" , method = RequestMethod.POST )
@ResponseBody
@RequiresPermissions("li:save")
public Map<String, Object> save(HttpServletRequest request,HttpServletResponse response,String username) {
System.out.println("save");
return new HashMap<String, Object>();
}


同理,只有登录名为“li”的用户才可以进行‘保存’操作,不然会报异常。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: