引入相关的依赖:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.hurriane.learn</groupId>
<artifactId>learn-shiro</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<dependencies>
<!-- 单元测试 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
<scope>test</scope>
</dependency>
<!-- 日志 -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.25</version>
</dependency>
<!-- 容器 -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<!-- springmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.3.10.RELEASE</version>
</dependency>
<!-- shiro的注解需要使用spring的aop功能 -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.11</version>
</dependency>
<!-- shiro整合到spring -->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.4.0</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
</dependencies>
</project>
在web.xml中配置spring的listener,springmvc的servlet,shiro的filter:
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Archetype Created Web Application</display-name>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/springContext-*.xml</param-value>
</context-param>
<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>
<init-param>
<param-name>targetBeanName</param-name>
<param-value>shiroFilter</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>shiroFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value></param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
springmvc的配置文件可参考https://blog.csdn.net/hurricane_li/article/details/78588482,
spring整合shiro的配置文件为:
<?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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
<property name="securityManager" ref="securityManager" />
<property name="loginUrl" value="/auth/login" />
<property name="successUrl" value="/user/admin" />
<!-- shiro执行退出,再进行登录,默认跳转到文档的根路径下,如果需要制定可以通过successUrl属性制定
相关问题:https://www.cnblogs.com/yeming/p/5480639.html
-->
<property name="unauthorizedUrl" value="/auth/unauthorized" />
<property name="filterChainDefinitions">
<value>
/auth/logout = logout
/** = authc
</value>
</property>
</bean>
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<property name="realm" ref="customRealm"/>
</bean>
<bean name="credentialsMatcher" class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
<property name="hashAlgorithmName" value="md5"></property>
<property name="hashIterations" value="2"></property>
</bean>
<!-- 开启shiro对注解的支持 -->
<bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
<property name="securityManager" ref="securityManager"></property>
</bean>
<aop:config proxy-target-class="true"></aop:config>
</beans>
认证接口:
package com.hurricane.learn.shiro.auth.controller;
import javax.servlet.http.HttpServletRequest;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.UnauthenticatedException;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("auth")
public class AuthController {
@RequestMapping("/login")
public String login(HttpServletRequest request) {
Object attribute = request.getAttribute("shiroLoginFailure");
System.out.println(attribute);
if (!StringUtils.isEmpty(attribute)) {
if (UnknownAccountException.class.getName().equals(attribute)) {
request.setAttribute("errorText", "用户名不存在");
}else if (IncorrectCredentialsException.class.getName().equals(attribute)) {
request.setAttribute("errorText", "密码错误");
}else {
request.setAttribute("errorText", "未知错误");
}
}
return "auth/login";
}
@RequestMapping("/unauthorized")
public String unauthorized() {
return "auth/unauthorized";
}
}
自定义的realm:
package com.hurricane.learn.shiro.auth.realm;
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.authc.credential.CredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import com.hurricane.learn.shiro.user.entity.User;
@Component("customRealm")
public class CustomRealm extends AuthorizingRealm{
@Autowired
public void setCredentialsMatcher(CredentialsMatcher credentialsMatcher) {
super.setCredentialsMatcher(credentialsMatcher);
}
/**
* 授权
*/
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection collection) {
//获取到当前用户
Object primaryPrincipal = collection.getPrimaryPrincipal();
//通过获取到的用户名,封装对应的权限并返回
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
info.addRole("role1");
info.addStringPermission("user:add");
return info;
}
/**
* 验证
*/
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
if (StringUtils.isEmpty(token.getPrincipal())) return null;
User dbUser = findUserByUserName(token.getPrincipal());
if (dbUser==null) {
return null;
}
// 这里面的password为从数据库中得到的,这里传入的principle可以在授权时通过collection.getPrimaryPrincipal()获取到
AuthenticationInfo info = new SimpleAuthenticationInfo(dbUser,dbUser.getPassword(),ByteSource.Util.bytes(dbUser.getSalt()),"realm1");
return info;
}
/**
* 这一步需要从数据库中获取数据,这里只是模拟相应的数据
* @param principal 用户名
* @return 从数据库中查询到的用户实体
*/
private User findUserByUserName(Object principal) {
if (StringUtils.isEmpty(principal)) {
return null;
}
String username = "hurricane";
if (!principal.equals(username)) {
return null;
}
User user = new User();
user.setId("1");
user.setUserName(username);
user.setNickName("小刚");
user.setSalt("sss");
//123加盐sss并进行两次md5散列
user.setPassword("755ac1a684638060155ccc37625b954b");
return user;
}
}
应用接口:
package com.hurricane.learn.shiro.user.controller;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/user")
public class UserController {
@RequestMapping("index")
public String index() {
return "user/index";
}
@RequiresPermissions("user:admin")
@RequestMapping("admin")
public String admin() {
return "user/admin";
}
}
以上为主要代码。
完整代码可以从GitHub中获得,链接:https://github.com/hurricane123/learn-shiro
补充:
MD5散列并且可以指定散列次数,shiro实现的使用:
package com.hurricane.learn.shiro.auth.util;
import org.apache.shiro.crypto.hash.Md5Hash;
public class Md5IterGenerator {
public static String getEncodeString(String rawString) {
Md5Hash md5Hash = new Md5Hash(rawString, "sss", 2);
return md5Hash.toString();
}
public static void main(String[] args) {
System.out.println(getEncodeString("123"));
}
}
参考:
1.燕青的视频教程