《十分鐘入門》
1.匯入依賴
<dependencies>
<!-- shiro -->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>1.4.1</version>
</dependency>
<!-- configure logging -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>1.7.21</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.21</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.12</version>
</dependency>
</dependencies>
2.組態檔:
log4j.properties
// An highlighted block
log4j.rootLogger=INFO, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m %n
# General Apache libraries
log4j.logger.org.apache=WARN
# Spring
log4j.logger.org.springframework=WARN
# Default Shiro logging
log4j.logger.org.apache.shiro=INFO
# Disable verbose logging
log4j.logger.org.apache.shiro.util.ThreadContext=WARN
log4j.logger.org.apache.shiro.cache.ehcache.EhCache=WARN
shiro.ini
[users]
# user 'root' with password 'secret' and the 'admin' role
root = secret, admin
# user 'guest' with the password 'guest' and the 'guest' role
guest = guest, guest
# user 'presidentskroob' with password '12345' ("That's the same combination on
# my luggage!!!" ;)), and role 'president'
presidentskroob = 12345, president
# user 'darkhelmet' with password 'ludicrousspeed' and roles 'darklord' and 'schwartz'
darkhelmet = ludicrousspeed, darklord, schwartz
# user 'lonestarr' with password 'vespa' and roles 'goodguy' and 'schwartz'
lonestarr = vespa, goodguy, schwartz
# -----------------------------------------------------------------------------
# Roles with assigned permissions
#
# Each line conforms to the format defined in the
# org.apache.shiro.realm.text.TextConfigurationRealm#setRoleDefinitions JavaDoc
# -----------------------------------------------------------------------------
[roles]
# 'admin' role has all permissions, indicated by the wildcard '*'
admin = *
# The 'schwartz' role can do anything (*) with any lightsaber:
schwartz = lightsaber:*
# The 'goodguy' role is allowed to 'drive' (action) the winnebago (type) with
# license plate 'eagle5' (instance specific id)
goodguy = winnebago:drive:eagle5
3.HelloWord:
HelloWord:
class Quickstart {
private static final transient Logger log = LoggerFactory.getLogger(Quickstart.class);
public static void main(String[] args) {
//基本的得到工廠物件操作
Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
SecurityManager securityManager = factory.getInstance();
SecurityUtils.setSecurityManager(securityManager);
//獲得一個Subject物件
Subject currentUser = SecurityUtils.getSubject();
//通過當前用戶拿到Session
Session session = currentUser.getSession();
session.setAttribute("someKey", "aValue");
String value = (String) session.getAttribute("someKey");
if (value.equals("aValue")) {
log.info("Retrieved the correct value! [" + value + "]");
}
//判斷當前用戶是否被認證
if (!currentUser.isAuthenticated()) {
//token 令牌
UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa");
//設定記住我
token.setRememberMe(true);
try {
//進行登錄操作
currentUser.login(token);
} catch (UnknownAccountException uae) {
log.info("There is no user with username of " + token.getPrincipal());
} catch (IncorrectCredentialsException ice) {
log.info("Password for account " + token.getPrincipal() + " was incorrect!");
} catch (LockedAccountException lae) {
log.info("The account for username " + token.getPrincipal() + " is locked. " +
"Please contact your administrator to unlock it.");
}
// ... catch more exceptions here (maybe custom ones specific to your application?
catch (AuthenticationException ae) {
//unexpected condition? error?
}
}
//say who they are:
//print their identifying principal (in this case, a username):
log.info("User [" + currentUser.getPrincipal() + "] logged in successfully.");
//test a role:
if (currentUser.hasRole("schwartz")) {
log.info("May the Schwartz be with you!");
} else {
log.info("Hello, mere mortal.");
}
//粗粒度
//test a typed permission (not instance-level)
if (currentUser.isPermitted("lightsaber:wield")) {
log.info("You may use a lightsaber ring. Use it wisely.");
} else {
log.info("Sorry, lightsaber rings are for schwartz masters only.");
}
//細粒度
//a (very powerful) Instance Level permission:
if (currentUser.isPermitted("winnebago:drive:eagle5")) {
log.info("You are permitted to 'drive' the winnebago with license plate (id) 'eagle5'. " +
"Here are the keys - have fun!");
} else {
log.info("Sorry, you aren't allowed to drive the 'eagle5' winnebago!");
}
//注銷
currentUser.logout();
//結束
System.exit(0);
}
}
《完整程序》
1.匯入相關依賴
<!-- shiro整合spring -->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.7.0</version>
</dependency>
<!-- shiro整合mybatis -->
<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>mssql-jdbc</artifactId>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.12</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.12</version>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.0</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring5</artifactId>
</dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-java8time</artifactId>
</dependency>
2.寫config類(spring環境已經搭建好了)
(1)Realm類
/**
* 自定義的Realm類,繼承AuthorizingRealm
*/
public class UserRealm extends AuthorizingRealm {
@Autowired
private AccountServiceImpl accountService;
/**
* 授權
* @param principalCollection
* @return
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
System.out.println("執行了--->授權方法");
//拿到當前登錄的物件
Subject subject = SecurityUtils.getSubject();
Account currentAccount = (Account) subject.getPrincipal();
//授權資訊
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
//將資料庫中的權限資訊賦值給當前資訊
info.addStringPermission(currentAccount.getPerms());
return info;
}
/**
* 認證
* @param token
* @return
* @throws AuthenticationException
*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
System.out.println("執行了--->認證方法");
UsernamePasswordToken userToken = (UsernamePasswordToken) token;
//從資料庫中獲取資料
Account account = accountService.findAccountByName(userToken.getUsername());
//判斷資料庫中是否有當前物件,沒有的話拋出例外,UnknownAccountException
if (account == null){
return null;
}
//密碼認證
return new SimpleAuthenticationInfo(account,account.getPassword(),"");
}
}
(2)ShiroConfig:
@Configuration
public class ShiroConfig {
/**
* 3.shiro過濾器工廠,ShiroFilterFactoryBean
* @param defaultWebSecurityManager 安全管理器
* @return 過濾器工廠
*/
@Bean
public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManager") DefaultWebSecurityManager defaultWebSecurityManager){
//實體化工廠物件
ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
//設定安全管理器
shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager);
/**
* 添加shiro的內置過濾器
* anon: 無需認證就可以訪問
* authc: 必須認證了才可以訪問
* user: 必須有記住我才可以用(不常用)
* perms: 擁有對某個資源的權限才能訪問
* role: 擁有某個角色權限才能訪問
*/
//攔截
Map<String,String> filterMap = new LinkedHashMap<>();
//授權,沒有授權會跳轉到未授權頁面,
filterMap.put("/user/add","perms[user:add]");
filterMap.put("/user/update","perms[user:update]");
filterMap.put("/user/*","authc");
shiroFilterFactoryBean.setFilterChainDefinitionMap(filterMap);
//設定登錄的請求頁面
shiroFilterFactoryBean.setLoginUrl("/toLogin");
//設定未授權頁面
shiroFilterFactoryBean.setUnauthorizedUrl("/noAuth");
return shiroFilterFactoryBean;
}
/**
* 2.DefaultWebSecurityManager
* @param userRealm realm物件
* @return 安全管理器
*/
@Bean(name = "securityManager")
public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm){
//實體化安全管理器物件
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
//關聯Realm
securityManager.setRealm(userRealm);
return securityManager;
}
/**
* 1.創建realm物件,自定義類,繼承AuthorizingRealm
* realm物件
* @return realm物件
*/
@Bean(name="userRealm")
public UserRealm userRealm(){
return new UserRealm();
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/222834.html
標籤:java
上一篇:String原始碼決議
