0.Shrio认证

Shrio认证流程图


image.png

  • 整合pom添加如下jar包

       org.apache.shiro
        shiro-core
        1.3.2
    
    
          org.slf4j
          slf4j-nop
          1.7.2
    
    
      junit
      junit
      4.12
    

  • java代码块
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.realm.SimpleAccountRealm;
import org.apache.shiro.subject.Subject;
import org.junit.Before;
import org.junit.Test;

public class AuthentiationTest {

    SimpleAccountRealm simpleAccountRealm = new SimpleAccountRealm();

    @Before
    public void addUser(){
        //模拟用户
        simpleAccountRealm.addAccount("gouDan","123456");
    }
    @Test
    public void testAuthentiation(){
        //构建SecurityManager环境
        DefaultSecurityManager defaultSecurityManager = new DefaultSecurityManager();
        //添加认证凭证
        defaultSecurityManager.setRealm(simpleAccountRealm);
        //主体提交认证请求
        SecurityUtils.setSecurityManager(defaultSecurityManager);
        Subject subject = SecurityUtils.getSubject();

        UsernamePasswordToken token = new UsernamePasswordToken("gouDan","123456");
        //登入
        subject.login(token);
        System.out.println(subject.isAuthenticated());
        //登出
        subject.logout();
        System.out.println(subject.isAuthenticated());
    }
}

需要注意

  • 用户名不正确会抛出
    UnknownAccountException
  • 密码不正确会抛出
    IncorrectCredentialsException

你可能感兴趣的:(0.Shrio认证)