SpringBoot整合安全權限框架Shiro

一、什麼是Shiro

Apache Shiro 是 Java 的一個安全框架。功能強大,使用簡單的Java安全框架,它爲開發人員提供一個直觀而全面的認證,授權,加密及會話管理的解決方案。
Shiro 包含 10 個內容:
1) Authentication:身份認證/登錄,驗證用戶是不是擁有相應的身份。
2) Authorization:授權,即權限驗證,驗證某個已認證的用戶是否擁有某個權限;即判斷用戶是否能做事情,常見的如:驗證某個用戶是否擁有某個角色。或者細粒度的驗證某個用戶對某個資源是否具有某個權限。
3) Session Manager:會話管理,即用戶登錄後就是一次會話,在沒有退出之前,它的所有信息都在會話中;會話可以是普通 JavaSE 環境的,也可以是如 Web 環境的。
4) Cryptography:加密,保護數據的安全性,如密碼加密存儲到數據庫,而不是明文存儲。
5) Web Support:Web支持,可以非常容易的集成到 web 環境。
6) Caching:緩存,比如用戶登錄後,其用戶信息、擁有的角色/權限不必每次去查,這樣可以提高效率。
7) Concurrency:shiro 支持多線程應用的併發驗證,即如在一個線程中開啓另一個線程,能把權限自動傳播過去。
8) Testing:提供測試支持。
9) Run As:允許一個用戶假裝爲另一個用戶(如果他們允許)的身份進行訪問。
10) Remember Me:記住我,這個是非常常見的功能,即一次登錄後,下次再來的話不用登錄了。

二、SpringBoot中集成Shiro

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-web</artifactId>
		    <version>1.4.0</version>
		</dependency>
		
		<dependency>
		    <groupId>org.apache.shiro</groupId>
		    <artifactId>shiro-spring</artifactId>
		    <version>1.4.0</version>
		</dependency>
		<!-- shiro -->

2、實現Realm需要繼承AuthorizingRealm

其中兩個對象長得很像,AuthenticationInfo與AuthorizationInfo ,前者用於認證登錄,後者用於權限控制的。

public class AuthRealm extends AuthorizingRealm{


	@Autowired
	private LoginService loginservice;
	
	
	//認證登錄
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		UsernamePasswordToken utoken=(UsernamePasswordToken) token;		//獲取用戶輸入的token
        String username = utoken.getUsername();
        String password = new String((char[]) utoken.getCredentials());
        char[] s = utoken.getPassword();
        ImMftAcc user = loginservice.userLogin(username, password);
        if(user!=null) {    //認證成功會將用戶信息放入到Session中,由Shiro來管理
        	Session session = SecurityUtils.getSubject().getSession();
        	session.setAttribute("SessionUser", user);
        	session.setAttribute("SeesionAccount", user.getAccount());
        	return new SimpleAuthenticationInfo(user, user.getPwd(),this.getClass().getName());
        }else {
        	throw new UnknownAccountException();//異常會在執行登錄時捕獲到
        }
	}
	
	//權限
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principal) {
		ImMftAcc user = (ImMftAcc) principal.fromRealm(this.getClass().getName()).iterator().next();//獲取session中的用戶
        List<String> permissions = new ArrayList<>();
        Set<Role> roles = user.getRoles();
        if(roles.size()>0) {
            for(Role role : roles) {
                Set<Module> modules = role.getModules();
                if(modules.size()>0) {
                    for(Module module : modules) {
                        permissions.add(module.getMname());
                    }
                }
            }
        }
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.addStringPermissions(permissions);
        return info;
	}

}

public class CredentialsMatcher extends SimpleCredentialsMatcher{
	
	public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {
        UsernamePasswordToken utoken=(UsernamePasswordToken) token;
        //用戶輸入的密碼
        String inPassword = new String(utoken.getPassword());
        //數據庫查詢的密碼
        String dbPassword=(String) info.getCredentials();
        return this.equals(inPassword, dbPassword);
    }
}

3、實現登錄

@Api(value="用戶登錄接口API",tags="用戶登錄")
@RestController
@RequestMapping("/user")
public class UserLoginController {

	
	@Autowired
	private LoginService loginService;
	
	@ApiOperation(value = "用戶登錄", notes = "用戶登錄")
	@ApiImplicitParams({
	    	@ApiImplicitParam(name = "UserInfo", value = "用戶對象", required = true, dataType = "UserInfo"),
	})
	@RequestMapping(value="/login",method=RequestMethod.POST)
	public String loginUser(@RequestBody UserInfo userInfo) {
		String accNo = userInfo.getAccount().trim();
		String pwd = userInfo.getPwd().trim();
		if(StringUtils.isEmpty(accNo)||StringUtils.isEmpty(pwd)) {
			return "-2";
		}
		 UsernamePasswordToken usernamePasswordToken=new UsernamePasswordToken(accNo, pwd);
	        Subject subject = SecurityUtils.getSubject();
	        try {
	            subject.login(usernamePasswordToken);
	            UserInfo user = (UserInfo) subject.getPrincipal();
	            return "0";
	        } catch(Exception e) {
	            return "-1";
	        }
	} 
	
	@ApiOperation(value = "註銷登錄", notes = "註銷登錄")
	@RequestMapping(value="/logout",method=RequestMethod.GET)
	public String logout(RedirectAttributes redirectAttributes ){
        SecurityUtils.getSubject().logout();   
        return "0";
    }

	
}








發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章