1、创建maven项目,添加依赖
<dependencies>
<dependency>
<groupId>org
.apache
.shiro
</groupId
>
<artifactId>shiro
-core
</artifactId
>
<version>1.4.0</version
>
</dependency
>
<dependency>
<groupId>junit
</groupId
>
<artifactId>junit
</artifactId
>
<version>4.12</version
>
</dependency
>
<dependency>
<groupId>org
.slf4j
</groupId
>
<artifactId>slf4j
-api
</artifactId
>
<version>1.7.5</version
>
</dependency
>
<dependency>
<groupId>org
.slf4j
</groupId
>
<artifactId>slf4j
-simple
</artifactId
>
<version>1.7.5</version
>
</dependency
>
</dependencies
>
2、创建自定义类,继承AuthorizingRealm
有两个方法需要重写,第一个方法用来做授权(给用户授权一些角色信息 ,权限信息),第二个方法用来做认证(登录使用)
2、实现认证方法
Map
<String,Object> map
=new HashMap<String,Object>();
{
map
.put("zhangsan","123456");
super.setName("reol");
}
@Override
protected AuthenticationInfo
doGetAuthenticationInfo(AuthenticationToken authenticationToken
) throws AuthenticationException
{
String username
= (String
) authenticationToken
.getPrincipal();
String password
=this.getPassWordByName(username
);
if(password
==null
){
return null
;
}
SimpleAuthenticationInfo authenticationInfo
=new SimpleAuthenticationInfo(username
,password
,"reol");
return authenticationInfo
;
}
private String
getPassWordByName(String username
) {
return (String
) map
.get(username
);
}
3、创建测试类测试登录功能
public class MyRealmTest {
@Test
public void Authentication(){
MyRealm jdbcRealm
=new MyRealm();
DefaultSecurityManager defaultSecurityManager
=new DefaultSecurityManager();
defaultSecurityManager
.setRealm(jdbcRealm
);
SecurityUtils
.setSecurityManager(defaultSecurityManager
);
Subject subject
=SecurityUtils
.getSubject();
UsernamePasswordToken Token
=new UsernamePasswordToken("zhangsan","123456");
subject
.login(Token
);
System
.out
.println(subject
.isAuthenticated());
}
执行测试类即可,当控制台输出true时,表示已经认证成功。 当用户名输入错位时,控制台会出现这个错误 当秘密错误时,控制台会报这个错误
4、实现授权方法
@Override
protected AuthorizationInfo
doGetAuthorizationInfo(PrincipalCollection principalCollection
) {
String username
= (String
) principalCollection
.getPrimaryPrincipal();
Set
<String> roles
=getRolesName(username
);
SimpleAuthorizationInfo simpleAuthenticationInfo
=new SimpleAuthorizationInfo();
simpleAuthenticationInfo
.setRoles(roles
);
return simpleAuthenticationInfo
;
}
public Set
<String> getRolesName(String username
) {
Set
<String> set
=new HashSet<>();
set
.add("admin");
set
.add("user");
return set
;
}
5、验证用户角色信息
只需要在刚才的测试类中添加以下代码即可
subject
.checkRoles("admin");
当输入不存在的角色名称时会报以下错误