这里的案例我是用Spring Boot去实现的;这是只是简单的演示了登陆,并没有设置权限的分配。
1.创建Spring Boot项目
创建的时候记得选web和Freemarker。
2.导入Maven
这里我把变动的那部分全部都贴了出来。
pom.xml
<properties>
<java.version>1.8</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>1.2.2</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.2.2</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-web</artifactId>
<version>1.2.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
3.创建实体类
创建实体类用户登陆验证的传值。
domain/User.java
package com.benzhu.shiro.domain;
public class User {
private String username;
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
4.创建自定义Realm
realm/CustomRealm.java
package com.benzhu.shiro.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.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
@Component("realm")
public class CustomRealm extends AuthorizingRealm {
Map<String,String> userMap = new HashMap<String, String>(16);
{
userMap.put("benzhu","5282d562ad1f43221a173ab92c1793d2"); //加密和加盐了
super.setName("customRealm");
}
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
String username = (String) principals.getPrimaryPrincipal();
//从缓存中拿到角色数据
Set<String> roles = getRolesByUserName(username);
//从缓存中拿到权限数据
Set<String> permissions = getPermissionUserName(username);
//返回对象
SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
authorizationInfo.setRoles(roles);
authorizationInfo.setStringPermissions(permissions);
return authorizationInfo;
}
private Set<String> getPermissionUserName(String username) {
Set<String> sets = new HashSet<String>();
sets.add("admin:update");
return sets;
}
private Set<String> getRolesByUserName(String username) {
Set<String> sets = new HashSet<String>();
sets.add("admin");
return sets;
}
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
//1.从主体传过来的认证信息中获取用户名
String username = (String) token.getPrincipal();
//2.通过用户名到数据库中获取凭证
String password = getPasswordByUserName(username);
if(password == null){
return null;
}
SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(username,password,"customRealm");
//加盐验证
authenticationInfo.setCredentialsSalt(ByteSource.Util.bytes("benzhu"));
return authenticationInfo;
}
private String getPasswordByUserName(String username) {
//模拟数据库查询
return userMap.get(username);
}
}
5.创建Shiro过滤器
filter/ShiroConfiguration.java
package com.benzhu.shiro.Filter;
import com.benzhu.shiro.realm.CustomRealm;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.annotation.Resource;
import java.util.LinkedHashMap;
@Configuration
public class ShiroConfiguration {
@Resource(name = "realm")
private CustomRealm customRealm;
@Bean(name="shiroFilter")
public ShiroFilterFactoryBean shiroFilter(@Qualifier("securityManager") DefaultWebSecurityManager manager) {
ShiroFilterFactoryBean bean=new ShiroFilterFactoryBean();
bean.setSecurityManager(manager);
//配置登录的url和登录成功的url以及验证失败的url
//loginUrl:没有登录的用户请求需要登录的页面时自动跳转到登录页面。
bean.setLoginUrl("/login");
//unauthorizedUrl:没有权限默认跳转的页面,登录的用户访问了没有被授权的资源自动跳转到的页面。
bean.setUnauthorizedUrl("/error");
//配置访问权限
LinkedHashMap<String, String> filterChainDefinitionMap=new LinkedHashMap<>();
filterChainDefinitionMap.put("/login", "anon");
filterChainDefinitionMap.put("/sublogin", "anon");
filterChainDefinitionMap.put("/usererror", "anon");
filterChainDefinitionMap.put("/**","authc");
bean.setFilterChainDefinitionMap(filterChainDefinitionMap);
return bean;
}
//配置核心安全事务管理器
@Bean(name="securityManager")
public DefaultWebSecurityManager securityManager() {
DefaultWebSecurityManager manager=new DefaultWebSecurityManager();
manager.setRealm(customRealm);
HashedCredentialsMatcher matcher = new HashedCredentialsMatcher(); //创建加密对象
matcher.setHashAlgorithmName("md5"); //加密的算法
matcher.setHashIterations(1);//加密次数
customRealm.setCredentialsMatcher(matcher); //放入自定义Realm
return manager;
}
}
6.创建controller
controller/UserController.java
package com.benzhu.shiro.controller;
import com.benzhu.shiro.domain.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.UnauthorizedException;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller("UserController")
@RequestMapping("/")
public class UserController {
@RequestMapping(value = "login")
public String login(){
return "login";
}
@RequestMapping(value = "usererror")
public String error(){
return "error";
}
@RequestMapping(value = "sublogin")
public String sublogin(User user){
Subject subject = SecurityUtils.getSubject();
UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(),user.getPassword());
try {
subject.login(token);
try {
subject.checkRole("admin");
subject.checkPermission("admin:update");
return "index";
}catch (UnauthorizedException exception){
System.out.println("角色授权或者权限授权失败!");
return "error";
}
}catch (AuthenticationException e){
System.out.println("认证失败!");
return "error";
}
}
}
7.编写前端页面
templates文件夹
templates/login.ftl
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/html">
<head>
<meta charset="utf-8">
<title>登陆</title>
</head>
<body>
<form action="sublogin" method="post">
用户名:<input type="text" name="username"><br>
密码:<input type="password" name="password"><br>
<input type="submit" value="登陆">
</form>
</body>
</html>
templates/error.ftl
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>错误</title>
</head>
<body>
账号或者密码错误。<br>
<a href="/login">返回登陆</a>
</body>
</html>
templates/index.ftl
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>首页</title>
</head>
<body>
恭喜你,登陆成功。
</body>
</html>
8.运行程序测试
本案例加密的账号是benzhu密码是123456。
评论