shiro 基于springmvc中做登陆功能

时间:2023-11-10 19:01:20

1.添加依赖

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

2.ApplicationContext-mvc.xml配置文件

 <?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task.xsd
"> <mvc:annotation-driven/>
<mvc:default-servlet-handler/> <context:component-scan base-package="com.wfd360.controller"/> <!-- 未认证或未授权时跳转必须在springmvc里面配,spring-shiro里的shirofilter配不生效 -->
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<!--表示捕获的异常 -->
<prop key="org.apache.shiro.authz.UnauthorizedException">
<!--捕获该异常时跳转的路径 -->
/403
</prop>
<!--表示捕获的异常 -->
<prop key="org.apache.shiro.authz.UnauthenticatedException">
<!--捕获该异常时跳转的路径 -->
/403
</prop>
</props>
</property>
</bean> <!-- 配置SpringMVC的视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean> <import resource="classpath:spring-shiro.xml"/> </beans>

3.spring-shiro.xml配置文件

 <?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.xsd">
<!--开启shiro的注解-->
<bean id="advisorAutoProxyCreator" class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator">
<property name="proxyTargetClass" value="true"></property>
</bean>
<bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor"/>
<!--注入自定义的Realm-->
<bean id="customRealm" class="com.wfd360.shiro.CustomRealm"></bean>
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<property name="realm" ref="customRealm"></property>
</bean> <!--配置ShiroFilter-->
<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
<property name="securityManager" ref="securityManager"></property>
<!--登入页面-->
<property name="loginUrl" value="/login.jsp"></property>
<!--登入成功页面-->
<property name="successUrl" value="/index.jsp"/>
<!-- <property name="filters">
<map>
&lt;!&ndash;退出过滤器&ndash;&gt;
<entry key="logout" value-ref="logoutFilter" />
</map>
</property>-->
<!--URL的拦截-->
<property name="filterChainDefinitions" >
<value>
/share = authc
/logout = logout
</value>
</property> </bean>
<!--自定义退出LogoutFilter-->
<!-- <bean id="logoutFilter" class="com.test.filter.SystemLogoutFilter">
<property name="redirectUrl" value="/login"/>
</bean>-->
</beans>

4.创建对象 CustomRealm.java

 package com.wfd360.shiro;

 import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection; import java.util.ArrayList;
import java.util.List; /**
* @author www.wfd360.com
* @date 2018/2/26 14:05
*/
public class CustomRealm extends AuthorizingRealm {
/**
* 授权
* @param principalCollection
* @return
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
String userName = (String) principalCollection.getPrimaryPrincipal();
List<String> permissionList=new ArrayList<String>();
permissionList.add("user:add");
permissionList.add("user:delete");
if (userName.equals("zhou")) {
permissionList.add("user:query");
}
SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
info.addStringPermissions(permissionList);
info.addRole("admin");
return info;
}
/**
* 认证
* @param authenticationToken
* @return
* @throws AuthenticationException
*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
String userName = (String) authenticationToken.getPrincipal();
if ("".equals(userName)) {
return null;
}
SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(userName,"123456",this.getName());
return info;
}
}

5.控制层ShiroController.java对象

 package com.wfd360.controller;

 import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod; /**
* Created by Administrator on 2018/10/29.
*/
@Controller
public class ShiroController { @RequestMapping(value = "/loginData", method = RequestMethod.POST)
public String login(String userName, String passwd, Model model) {
Subject subject = SecurityUtils.getSubject();
UsernamePasswordToken token = new UsernamePasswordToken(userName, passwd);
try {
subject.login(token);
} catch (UnknownAccountException e) {
e.printStackTrace();
model.addAttribute("userName", "用户名错误!");
return "login";
} catch (IncorrectCredentialsException e) {
e.printStackTrace();
model.addAttribute("passwd", "密码错误");
return "login";
}
return "index";
} @RequestMapping(value = "/index2")
public String index() {
System.out.println("------index-------");
return "login";
}
}

6.登陆jsp页面login.jsp

 <%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2018/10/29
Time: 11:51
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>登陆界面</title>
</head>
<body>
<h2>登陆界面</h2>
<form action="/loginData" method="post">
用户名:<input name="userName">
密码:<input name="passwd">
<input type="submit">
</form>
</body>
</html>

7.web.xml配置

 <!-- shiro 过滤器 start -->
<filter>
<filter-name>shiroFilter</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
<!-- 设置true由servlet容器控制filter的生命周期 -->
<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 过滤器 end -->

8.测试完成!