授权过程
代码实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
| package com.ledao;
import org.apache.shiro.SecurityUtils; import org.apache.shiro.authc.AuthenticationException; import org.apache.shiro.authc.UsernamePasswordToken; import org.apache.shiro.authz.AuthorizationException; import org.apache.shiro.mgt.DefaultSecurityManager; import org.apache.shiro.realm.SimpleAccountRealm; import org.apache.shiro.subject.Subject;
public class Test {
public static void main(String[] args) { SimpleAccountRealm simpleAccountRealm = new SimpleAccountRealm(); simpleAccountRealm.addAccount("ledao", "123456", "admin", "teacher"); DefaultSecurityManager securityManager = new DefaultSecurityManager(); securityManager.setRealm(simpleAccountRealm); SecurityUtils.setSecurityManager(securityManager); Subject subject = SecurityUtils.getSubject(); subject.checkRoles("admin", "teacher1"); UsernamePasswordToken token = new UsernamePasswordToken("ledao", "123456"); try { subject.login(token); System.out.println(subject.isAuthenticated() ? "登录成功" : "登录失败"); try { subject.checkRoles("admin", "teacher1"); } catch (AuthorizationException e) { e.printStackTrace(); System.out.println("登录的用户与检查的角色不相符!!"); } } catch (AuthenticationException e) { e.printStackTrace(); System.out.println("用户名或密码错误!!"); } } }
|
测试
如果subject.checkRoles(“admin”, “teacher1”),那么程序会报错,提示没有teacher1这个角色;如果subject.checkRoles(“admin”, “teacher”),那么程序不会报错