1. 程式人生 > 其它 >dockeryapi百度雲下載,springboot面試題及答案高階

dockeryapi百度雲下載,springboot面試題及答案高階

Shiro的由來?
對於一個真正為其存在提供良好案例的框架,以及因此您使用它的理由,它應該滿足其他替代方案無法滿足的需求。為了理解這一點,我們需要了解Shiro的歷史以及建立時的替代方案。

在2008年進入Apache軟體基金會之前,Shiro已經有5年的歷史,之前被稱為JSecurity專案,該專案始於2003年初。2003年,Java應用程式開發人員的通用安全替代方案並不多 - Java認證和授權服務,也稱為JAAS。JAAS存在許多缺點 - 雖然其身份驗證功能在某種程度上是可以容忍的,但授權方面使用起來很麻煩且令人沮喪。此外,JAAS嚴重依賴於虛擬機器級安全性問題,例如,確定是否應允許在JVM中載入類。作為一名應用程式開發人員,我更關心應用程式終端使用者可以做什麼,而不是我的程式碼可以在JVM中做什麼。

由於我當時正在使用的應用程式,我還需要訪問一個乾淨的,與容器無關的會話機制。當時遊戲中唯一的會話選擇是HttpSessions,它需要一個Web容器,或EBJ 2.1 Stateful Session Beans,它需要一個EJB容器。我需要一些可以與容器分離的東西,可以在我選擇的任何環境中使用。

最後,存在加密問題。有時候我們都需要保證資料安全,但除非你是加密專家,否則Java密碼體系結構很難理解。API充滿了檢查異常,並且使用起來很麻煩。我希望有一個更清潔的開箱即用的解決方案,可以根據需要輕鬆加密和解密資料。

因此,從2003年初的安全狀況來看,您可以很快意識到在單一,有凝聚力的框架中沒有任何東西可以滿足所有這些要求。正因為如此,JSecurity,以及後來的Apache Shiro誕生了。

什麼是 Shiro?
Apache Shiro是一個功能強大且易於使用的Java安全框架,可執行身份驗證,授權,加密和會話管理,並可用於保護任何應用程式 - 從命令列應用程式,移動應用程式到最大的Web和企業應用程式。

Shiro的特性?
Authentication(認證), Authorization(授權), Session Management(會話管理), Cryptography(加密)被 Shiro 框架的開發團隊稱之為應用安全的四大基石。

Authentication(認證):使用者身份識別,通常被稱為使用者“登入”。

Authorization(授權):訪問控制。比如某個使用者是否具有某個操作的使用許可權。

Session Management(會話管理):特定於使用者的會話管理,甚至在非web 或 EJB 應用程式。

Cryptography(加密):在對資料來源使用加密演算法加密的同時,保證易於使用。y

表結構
user_info 使用者表
sys_user_role 使用者角色關聯表 (一對多的關係,一個角色對應多個使用者)

sys_permission 許可權表
sys_role_permission 角色許可權關聯表 (多對多關係)

sys_role 角色表

SpringBoot 及整合Shiro開始搭建
pom檔案

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>net.sourceforge.nekohtml</groupId>
<artifactId>nekohtml</artifactId>
<version>1.9.22</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

<!-- shiro 關鍵包-->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.4.0</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
</dependencies>
配置檔案

spring.datasource.url=jdbc:mysql://localhost:3306/test?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

spring.jpa.properties.hibernate.hbm2ddl.auto=update
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
spring.jpa.show-sql= true
spring.thymeleaf.cache=false
實體類

使用者類

@Entity
public class UserInfo implements Serializable {
@Id
@GeneratedValue
private Integer uid;
@Column(unique =true)
private String username;//帳號
private String name;//名稱(暱稱或者真實姓名,不同系統不同定義)
private String password; //密碼;
private String salt;//加密密碼的鹽
private byte state;//使用者狀態,0:建立未認證(比如沒有啟用,沒有輸入驗證碼等等)--等待驗證的使用者 , 1:正常狀態,2:使用者被鎖定.
@ManyToMany(fetch= FetchType.EAGER)//立即從資料庫中進行載入資料;
@JoinTable(name = "SysUserRole", joinColumns = { @JoinColumn(name = "uid") }, inverseJoinColumns ={@JoinColumn(name = "roleId") })
private List<SysRole> roleList;// 一個使用者具有多個角色
// 省略setget方法

}
角色類

@Entity
public class SysRole {
@Id@GeneratedValue
private Integer id; // 編號
private String role; // 角色標識程式中判斷使用,如"admin",這個是唯一的:
private String description; // 角色描述,UI介面顯示使用
private Boolean available = Boolean.FALSE; // 是否可用,如果不可用將不會新增給使用者

//角色 -- 許可權關係:多對多關係;
@ManyToMany(fetch= FetchType.EAGER)
@JoinTable(name="SysRolePermission",joinColumns={@JoinColumn(name="roleId")},inverseJoinColumns={@JoinColumn(name="permissionId")})
private List<SysPermission> permissions;

// 使用者 - 角色關係定義;
@ManyToMany
@JoinTable(name="SysUserRole",joinColumns={@JoinColumn(name="roleId")},inverseJoinColumns={@JoinColumn(name="uid")})
private List<UserInfo> userInfos;// 一個角色對應多個使用者
// 省略setget方法
}
許可權類

@Entity
public class SysPermission implements Serializable {
@Id@GeneratedValue
private Integer id;//主鍵.
private String name;//名稱.
@Column(columnDefinition="enum('menu','button')")
private String resourceType;//資源型別,[menu|button]
private String url;//資源路徑.
private String permission; //許可權字串,menu例子:role:*,button例子:role:create,role:update,role:delete,role:view
private Long parentId; //父編號
private String parentIds; //父編號列表
private Boolean available = Boolean.FALSE;
@ManyToMany
@JoinTable(name="SysRolePermission",joinColumns={@JoinColumn(name="permissionId")},inverseJoinColumns={@JoinColumn(name="roleId")})
private List<SysRole> roles;
}
根據以上的程式碼會自動生成user_info(使用者資訊表)、sys_role(角色表)、sys_permission(許可權表)、sys_user_role(使用者角色表)、sys_role_permission(角色許可權表)這五張表,為了方便測試我們給這五張表插入一些初始化資料:

INSERT INTO `user_info` (`uid`,`username`,`name`,`password`,`salt`,`state`) VALUES ('1', 'admin', '管理員', '9c77d6384a1d8a1cc581424e6f0e82d8','root30ea1b94d889ccadeb9f89af63317de2', 0);
INSERT INTO `sys_permission` (`id`,`available`,`name`,`parent_id`,`parent_ids`,`permission`,`resource_type`,`url`) VALUES (1,0,'使用者管理',0,'0/','userInfo:view','menu','userInfo/userList');
INSERT INTO `sys_permission` (`id`,`available`,`name`,`parent_id`,`parent_ids`,`permission`,`resource_type`,`url`) VALUES (2,0,'使用者新增',1,'0/1','userInfo:add','button','userInfo/userAdd');
INSERT INTO `sys_permission` (`id`,`available`,`name`,`parent_id`,`parent_ids`,`permission`,`resource_type`,`url`) VALUES (3,0,'使用者刪除',1,'0/1','userInfo:del','button','userInfo/userDel');
INSERT INTO `sys_role` (`id`,`available`,`description`,`role`) VALUES (1,0,'管理員','admin');
INSERT INTO `sys_role` (`id`,`available`,`description`,`role`) VALUES (2,0,'VIP會員','vip');
INSERT INTO `sys_role` (`id`,`available`,`description`,`role`) VALUES (3,1,'test','test');
INSERT INTO `sys_role_permission` VALUES ('1', '1');
INSERT INTO `sys_role_permission` (`permission_id`,`role_id`) VALUES (1,1);
INSERT INTO `sys_role_permission` (`permission_id`,`role_id`) VALUES (2,1);
INSERT INTO `sys_role_permission` (`permission_id`,`role_id`) VALUES (3,2);
INSERT INTO `sys_user_role` (`role_id`,`uid`) VALUES (1,1);
首先要配置的是ShiroConfig類,Apache Shiro 核心通過 Filter 來實現,就好像SpringMvc 通過DispachServlet 來主控制一樣。

類介紹:

ShiroFilterFactoryBean:是個攔截器,在請求進入控制層前將其攔截,需要將安全管理器SecurityManager注入其中。

SecurityManager:安全管理器,需要將自定義realm注入其中,以後還可以將快取、remeberme等注入其中

public interface AuthenticationToken extends Serializable {

Object getPrincipal();

Object getCredentials();
}
AuthenticationToken :

上面定義了介面原始碼,主要是兩個介面,一個是獲取委託人資訊,一個是獲取證明,常用的是使用者名稱和密碼的組合。

@Configuration
public class ShiroConfig {
@Bean
public ShiroFilterFactoryBean shirFilter(SecurityManager securityManager) {
System.out.println("ShiroConfiguration.shirFilter()");
ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
shiroFilterFactoryBean.setSecurityManager(securityManager);
//攔截器.
Map<String,String> filterChainDefinitionMap = new LinkedHashMap<String,String>();
// 配置不會被攔截的連結 順序判斷
filterChainDefinitionMap.put("/static/**", "anon");
//配置退出 過濾器,其中的具體的退出程式碼Shiro已經替我們實現了
filterChainDefinitionMap.put("/logout", "logout");
//<!-- 過濾鏈定義,從上向下順序執行,一般將/**放在最為下邊 -->:這是一個坑呢,一不小心程式碼就不好使了;
//<!-- authc:所有url都必須認證通過才可以訪問; anon:所有url都都可以匿名訪問-->
filterChainDefinitionMap.put("/**", "authc");
// 如果不設定預設會自動尋找Web工程根目錄下的"/login.jsp"頁面
shiroFilterFactoryBean.setLoginUrl("/login");
// 登入成功後要跳轉的連結
shiroFilterFactoryBean.setSuccessUrl("/index");

//未授權介面;
shiroFilterFactoryBean.setUnauthorizedUrl("/403");
shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
return shiroFilterFactoryBean;
}

@Bean
public MyShiroRealm myShiroRealm(){
MyShiroRealm myShiroRealm = new MyShiroRealm();
return myShiroRealm;
}


@Bean
public SecurityManager securityManager(){
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
securityManager.setRealm(myShiroRealm());
return securityManager;
}
}
自定義realm
MyShiroRealm繼承 AuthorizingRealm,重寫doGetAuthorizationInfo授權方法,和doGetAuthenticationInfo認證方法

package com.example.config;

import com.example.entity.SysPermission;
import com.example.entity.SysRole;
import com.example.entity.UserInfo;
import com.example.service.UserInfoService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
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 javax.annotation.Resource;

/**
* @ProjectName: springboot-shiro
* @Package: com.example.config
* @ClassName: MyShiroRealm
* @Description:
* @Author: Ni Shichao
* @Version: 1.0
*/
public class MyShiroRealm extends AuthorizingRealm {
@Resource
private UserInfoService userInfoService;
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
System.out.println("許可權配置-->MyShiroRealm.doGetAuthorizationInfo()");
SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
UserInfo userInfo = (UserInfo)principals.getPrimaryPrincipal();
for(SysRole role:userInfo.getRoleList()){
authorizationInfo.addRole(role.getRole());
for(SysPermission p:role.getPermissions()){
authorizationInfo.addStringPermission(p.getPermission());
}
}
return authorizationInfo;
}

/*主要是用來進行身份認證的,也就是說驗證使用者輸入的賬號和密碼是否正確。*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token)
throws AuthenticationException {
System.out.println("MyShiroRealm.doGetAuthenticationInfo()");
// 獲取使用者的輸入的賬號.
String username = (String)token.getPrincipal();
// 獲取使用者的輸入的密碼
System.out.println(token.getCredentials());
//通過username從資料庫中查詢 User物件,如果找到,沒找到.
//實際專案中,這裡可以根據實際情況做快取,如果不做,Shiro自己也是有時間間隔機制,2分鐘內不會重複執行該方法
UserInfo userInfo = userInfoService.findByUsername(username);
System.out.println("----->>userInfo="+userInfo);
if(userInfo == null){
return null;
}

// 進行認證,將正確資料給shiro處理
// 密碼不用自己比對,AuthenticationInfo認證資訊物件,一個介面,new他的實現類物件SimpleAuthenticationInfo
/* 第一個引數隨便放,可以放user物件,程式可在任意位置獲取 放入的物件
* 第二個引數必須放密碼,
* 第三個引數放 當前realm的名字,因為可能有多個realm*/
SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
userInfo, //使用者名稱
userInfo.getPassword(), //密碼
ByteSource.Util.bytes(userInfo.getSalt()),
getName() //realm name
);
//清除之前的授權資訊
super.clearCachedAuthorizationInfo(authenticationInfo.getPrincipals());
// 存入使用者物件
SecurityUtils.getSubject().getSession().setAttribute("login", userInfo);
// 返回給安全管理器,securityManager,由securityManager比對資料庫查詢出的密碼和頁面提交的密碼
// 如果有問題,向上拋異常,一直拋到控制器
return authenticationInfo;
}

}

AuthenticationToken 說明
public interface AuthenticationToken extends Serializable {

Object getPrincipal();

Object getCredentials();

}
上面定義了介面原始碼,主要是兩個介面,一個是獲取委託人資訊,一個是獲取證明,常用的是使用者名稱和密碼的組合。

這裡AuthenticationToken只提供介面,一般我們的實體類包含了get/set方法,但是這裡抽出了get方法,方便使用者自己擴充套件所需要的實現。

其中擴充套件介面HostAuthenticationToken提供了獲取使用者客戶host的功能,原始碼如下:

public interface HostAuthenticationToken extends AuthenticationToken {
String getHost();
}
RememberMeAuthenticationToken提供了記住使用者的標識:

public interface RememberMeAuthenticationToken extends AuthenticationToken {

boolean isRememberMe();

}
Controller類說明
登入過程其實只是處理異常的相關資訊,具體的登入驗證交給shiro來處理

@Controller
public class HomeController {

@RequestMapping({"/","/index"})
public String index(){
return"/index";
}


@RequestMapping("/login")
public String login(HttpServletRequest request, Map<String, Object> map) throws Exception{
System.out.println("HomeController.login()");
// 登入失敗從request中獲取shiro處理的異常資訊。
// shiroLoginFailure:就是shiro異常類的全類名.
String exception = (String) request.getAttribute("shiroLoginFailure");
System.out.println("exception=" + exception);
String msg = "";
if (exception != null) {
if (UnknownAccountException.class.getName().equals(exception)) {
System.out.println("UnknownAccountException -- > 賬號不存在:");
msg = "UnknownAccountException -- > 賬號不存在:";
} else if (IncorrectCredentialsException.class.getName().equals(exception)) {
System.out.println("IncorrectCredentialsException -- > 密碼不正確:");
msg = "IncorrectCredentialsException -- > 密碼不正確:";
} else if ("kaptchaValidateFailed".equals(exception)) {
System.out.println("kaptchaValidateFailed -- > 驗證碼錯誤");
msg = "kaptchaValidateFailed -- > 驗證碼錯誤";
} else {
msg = "else >> "+exception;
System.out.println("else -- >" + exception);
}
}
map.put("msg", msg);
// 此方法不處理登入成功,由shiro進行處理
return "/login";
}

@RequestMapping("/403")
public String unauthorizedRole(){
System.out.println("------沒有許可權-------");
return "403";
}
}
其它dao層和service的程式碼就不貼出來了大家直接看程式碼。

頁面說明
登入頁面

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Login</title>
</head>
<body>
錯誤資訊:<h4 th:text="${msg}"></h4>
<form action="" method="post">
<p>賬號:<input type="text" name="username" value="admin"/></p>
<p>密碼:<input type="text" name="password" value="123456"/></p>
<p><input type="submit" value="登入"/></p>
</form>
</body>
</html>
index頁面

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>index</title>
</head>
<body>

<div th:text="'歡迎你'+${session.login.username}"></div>
<a th:href="@{/logout}">退出登入</a>
</body>
</html>
新增使用者過程
/**
* 新增使用者
* @return
*/
@RequestMapping("/userSave")
@RequiresPermissions("userInfo:save")//許可權管理;
public String userSave(UserInfo user){
userInfoService.save(user);
return "redirect:userList";
}
Service中的程式碼

public void save(UserInfo userInfo) {
String password = userInfo.getPassword();
String[] saltAndCiphertext = UserRegisteAndLogin.encryptPassword(userInfo.getUsername(),password);
userInfo.setSalt(saltAndCiphertext[0]);
userInfo.setPassword(saltAndCiphertext[1]);
userInfoDao.save(userInfo);
}
密碼加密處理

/**
* 使用者註冊時加密使用者的密碼
* 輸入密碼明文 返回密文與鹽值
* @param password
* @return 第一個是密文 第二個是密碼鹽值
*/
public static String[] encryptPassword(String username,String password)
{
String salt = new SecureRandomNumberGenerator().nextBytes().toHex(); //生成鹽值
salt = username+salt;
int hashIterations = 2;//加密的次數
String hashAlgorithmName = "md5";//加密方式
Object simpleHash = new SimpleHash(hashAlgorithmName, password,
salt, hashIterations);
String[] strings = new String[]{salt, simpleHash.toString()};
return strings;
}

html頁面

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>新增使用者頁面</title>
</head>
<body>


<form action="/userInfo/userSave" method="post">
<p>暱稱:<input type="text" name="name" /></p>
<p>賬號:<input type="text" name="username" /></p>
<p>密碼:<input type="text" name="password" /></p>
<p><input type="submit" value="儲存"/></p>
</form>
</body>
</html>

測試
http://localhost:8080/login 頁面

登入成功跳轉 index 頁面

上面這些操作時候觸發MyShiroRealm.doGetAuthorizationInfo()這個方面,也就是許可權校驗的方法。

可以在資料庫中修改不同的許可權進行測試,deml中有隊使用者的增刪查改,就不展示了,大家可以下載demo自行測試。

github地址:

https://github.com/xiaonongOne/springboot-shiro