4.0.0
com.bobo
ShiroDemo01
1.0-SNAPSHOT
org.apache.shiro
shiro-core
1.1.0
org.slf4j
slf4j-simple
1.6.1
test
junit
junit
4.12
test
commons-logging
commons-logging
1.2
[users]
root=123456
# 账号是root,密码是123456
package com.bobo.shiro.test;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.Factory;
public class Test01 {
/**
* Shiro的入门案例
* 账号密码是定义在ini文件中的
* @param args
*/
public static void main(String[] args) {
// 1.获取一个SecurityManager工厂对象
Factory factory = new IniSecurityManagerFactory("classpath:shiro.ini");
// 2.通过SecurityManager工厂对象创建SecurityManager对象
SecurityManager securityManager = factory.getInstance();
// 3.将SecurityManager对象添加到当前的运行环境中去
SecurityUtils.setSecurityManager(securityManager);
// 4.获取Subject对象
Subject subject = SecurityUtils.getSubject();
// 5.获取用户提交的要认证的账号密码
String userName = "root";
String password = "1234561";
// 6.将用户提交的账号密码封装为一个Token对象
AuthenticationToken token = new UsernamePasswordToken(userName,password);
// 7.完成认证操作 login
subject.login(token);
// 8.获取认证状态
System.out.println(subject.isAuthenticated());
}
}
package com.bobo.shiro.test;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.Factory;
public class Test02 {
/**
* Shiro的入门案例
* 账号密码是定义在ini文件中的
* @param args
*/
public static void main(String[] args) {
// 1.获取一个SecurityManager工厂对象
Factory factory = new IniSecurityManagerFactory("classpath:shiro.ini");
// 2.通过SecurityManager工厂对象创建SecurityManager对象
SecurityManager securityManager = factory.getInstance();
// 3.将SecurityManager对象添加到当前的运行环境中去
SecurityUtils.setSecurityManager(securityManager);
// 4.获取Subject对象
Subject subject = SecurityUtils.getSubject();
// 5.获取用户提交的要认证的账号密码
String userName = "root1";
String password = "123456";
// 6.将用户提交的账号密码封装为一个Token对象
AuthenticationToken token = new UsernamePasswordToken(userName,password);
// 7.完成认证操作 login
try{
subject.login(token);
System.out.println("登录成功....");
}catch (UnknownAccountException e){
System.out.println("账号错误...");
}catch (IncorrectCredentialsException e){
System.out.println("密码错误...");
}
}
}
package com.bobo.shiro.realm;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
/**
* 自定义的Realm
*/
public class MyRealm extends AuthorizingRealm {
/**
* 认证操作
* @param authenticationToken
* @return
* @throws AuthenticationException
*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken)
throws AuthenticationException {
UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
String userName = token.getUsername();
String password = new String(token.getPassword());
System.out.println("登录的账号密码是:" + userName + " " + password);
// 通过JDBC操作和数据库中的账号密码匹配
if("zhang".equals(userName) ){
// 账号正确 假设查询出的zhang的密码是 123
AuthenticationInfo info =
new SimpleAuthenticationInfo(userName,"123","myrealm");
return info;
}
return null;
}
/**
* 授权操作
* @param principalCollection
* @return
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
return null;
}
}
[main]
# 自定义Realm
customeRealm=com.bobo.shiro.realm.MyRealm
# 将自定义的Realm设置到SecurityManager中
securityManager.realms=$customeRealm
package com.bobo.shiro.test;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.Factory;
public class Test02 {
/**
* Shiro的入门案例
* 账号密码是定义在ini文件中的
* @param args
*/
public static void main(String[] args) {
// 1.获取一个SecurityManager工厂对象
Factory factory = new IniSecurityManagerFactory("classpath:shiro.ini");
// 2.通过SecurityManager工厂对象创建SecurityManager对象
SecurityManager securityManager = factory.getInstance();
// 3.将SecurityManager对象添加到当前的运行环境中去
SecurityUtils.setSecurityManager(securityManager);
// 4.获取Subject对象
Subject subject = SecurityUtils.getSubject();
// 5.获取用户提交的要认证的账号密码
String userName = "zhang";
String password = "123";
// 6.将用户提交的账号密码封装为一个Token对象
AuthenticationToken token = new UsernamePasswordToken(userName,password);
// 7.完成认证操作 login
try{
subject.login(token);
System.out.println("登录成功....");
}catch (UnknownAccountException e){
System.out.println("账号错误...");
}catch (IncorrectCredentialsException e){
System.out.println("密码错误...");
}
}
}
public void login(AuthenticationToken token) throws AuthenticationException {
this.clearRunAsIdentities();
// 进入securityManager的login方法中
Subject subject = this.securityManager.login(this, token);
// 认证完成后的操作....
String host = null;
PrincipalCollection principals;
if (subject instanceof DelegatingSubject) {
DelegatingSubject delegating = (DelegatingSubject)subject;
principals = delegating.principals;
host = delegating.host;
} else {
principals = subject.getPrincipals();
}
if (principals != null && !principals.isEmpty()) {
this.principals = principals;
this.authenticated = true;
if (token instanceof HostAuthenticationToken) {
host = ((HostAuthenticationToken)token).getHost();
}
if (host != null) {
this.host = host;
}
Session session = subject.getSession(false);
if (session != null) {
this.session = this.decorate(session);
this.runAsPrincipals = this.getRunAsPrincipals(this.session);
} else {
this.session = null;
}
ThreadContext.bind(this);
} else {
String msg = "Principals returned from securityManager.login( token ) returned a null or empty value. This value must be non null and populated with one or more elements.";
throw new IllegalStateException(msg);
}
}
public Subject login(Subject subject, AuthenticationToken token) throws AuthenticationException {
AuthenticationInfo info;
try {
// 关键方法 认证方法
info = this.authenticate(token);
} catch (AuthenticationException var7) {
AuthenticationException ae = var7;
try {
this.onFailedLogin(token, ae, subject);
} catch (Exception var6) {
if (log.isInfoEnabled()) {
log.info("onFailedLogin method threw an exception. Logging and propagating original AuthenticationException.", var6);
}
}
throw var7;
}
Subject loggedIn = this.createSubject(token, info, subject);
this.bind(loggedIn);
this.onSuccessfulLogin(token, info, loggedIn);
return loggedIn;
}
public final AuthenticationInfo authenticate(AuthenticationToken token) throws AuthenticationException {
if (token == null) {
throw new IllegalArgumentException("Method argumet (authentication token) cannot be null.");
} else {
log.trace("Authentication attempt received for token [{}]", token);
AuthenticationInfo info;
try {
// 关键代码 完成认证
info = this.doAuthenticate(token);
if (info == null) {
String msg = "No account information found for authentication token [" + token + "] by this " + "Authenticator instance.Please check that it is configured correctly.";
throw new AuthenticationException(msg);
}
} catch (Throwable var8) {
AuthenticationException ae = null;
if (var8 instanceof AuthenticationException) {
ae = (AuthenticationException)var8;
}
if (ae == null) {
String msg = "Authentication failed for token submission [" + token + "]. Possible unexpected " + "error? (Typical or expected login exceptions should extend from AuthenticationException).";
ae = new AuthenticationException(msg, var8);
}
try {
this.notifyFailure(token, ae);
} catch (Throwable var7) {
if (log.isWarnEnabled()) {
String msg = "Unable to send notification for failed authentication attempt - listener error?. Please check your AuthenticationListener implementation(s). Logging sending exception and propagating original AuthenticationException instead...";
log.warn(msg, var7);
}
}
throw ae;
}
log.debug("Authentication successful for token [{}]. Returned account [{}]", token, info);
this.notifySuccess(token, info);
return info;
}
}
protected AuthenticationInfo doAuthenticate(AuthenticationToken authenticationToken) throws AuthenticationException {
this.assertRealmsConfigured();
// 获取到自定义的realm
Collection realms = this.getRealms();
// 判断是否进入单域还是多域验证
return realms.size() == 1 ?
this.doSingleRealmAuthentication((Realm)realms.iterator().next(),authenticationToken) : this.doMultiRealmAuthentication(realms,authenticationToken);
}
protected AuthenticationInfo doSingleRealmAuthentication(Realm realm,AuthenticationToken token) {
if (!realm.supports(token)) {
String msg = "Realm [" + realm + "] does not support authentication token [" + token + "]. Please ensure that the appropriate Realm implementation is " + "configured correctly or that the realm accepts AuthenticationTokens of this type.";
throw new UnsupportedTokenException(msg);
} else {
// 具体的验证操作
AuthenticationInfo info = realm.getAuthenticationInfo(token);
if (info == null) {
String msg = "Realm [" + realm + "] was unable to find account data for the " + "submitted AuthenticationToken [" + token + "].";
// 这是我们熟悉的异常,账号错误的异常信息
throw new UnknownAccountException(msg);
} else {
return info;
}
}
}
public final AuthenticationInfo getAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
// 其实就是会执行我们自定义的MyRealm中的认证方法
AuthenticationInfo info = this.doGetAuthenticationInfo(token);
if (info == null) {
if (log.isDebugEnabled()) {
String msg = "No authentication information found for submitted authentication token [" + token + "]. " + "Returning null.";
log.debug(msg);
}
return null;
} else {
CredentialsMatcher cm = this.getCredentialsMatcher();
if (cm != null) {
// 密码匹配
if (!cm.doCredentialsMatch(token, info)) {
String msg = "The credentials provided for account [" + token + "] did not match the expected credentials.";
// 密码错误 抛出的异常信息
throw new IncorrectCredentialsException(msg);
} else {
return info;
}
} else {
throw new AuthenticationException("A CredentialsMatcher must be configured in order to verify credentials during authentication. If you do not wish for credentials to be examined, you can configure an " + AllowAllCredentialsMatcher.class.getName() + " instance.");
}
}
}
package com.bobo.shiro.md5;
import org.apache.shiro.crypto.hash.Md5Hash;
public class Md5Demo01 {
/**
* MD5算法的使用
* @param args
*/
public static void main(String[] args) {
// 单个信息加密
Md5Hash md5Hash = new Md5Hash("123456");
System.out.println(md5Hash);
// 加密添加盐值 增大破解难度
md5Hash = new Md5Hash("123456","123");
System.out.println(md5Hash);
// 加密添加盐值 及增加迭代次数
md5Hash = new Md5Hash("123456","123",1024);
System.out.println(md5Hash);
}
}
e10adc3949ba59abbe56e057f20f883e
1e191d851b3b49a248f4ea62f6b06410
b2793335f43645fd8e00c7d18e14e05f
package com.bobo.shiro.realm;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.SimpleByteSource;
/**
* 自定义的Realm
*/
public class MyRealm extends AuthorizingRealm {
/**
* 认证操作
* @param authenticationToken
* @return
* @throws AuthenticationException
*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken)
throws AuthenticationException {
UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
String userName = token.getUsername();
String password = new String(token.getPassword());
System.out.println("登录的账号密码是:" + userName + " " + password);
// 通过JDBC操作和数据库中的账号密码匹配
if("zhang".equals(userName) ){
// 账号正确 假设查询出的zhang的密码是 123
String pwd = "b2793335f43645fd8e00c7d18e14e05f";
String salt = "123";
AuthenticationInfo info =
new SimpleAuthenticationInfo(userName
,pwd
,new SimpleByteSource(salt) // salt
,"myrealm" // 自定义的 this 名称
);
return info;
}
return null;
}
/**
* 授权操作
* @param principalCollection
* @return
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
return null;
}
}
[main]
# 定义凭证匹配器
credentialsMathcher=org.apache.shiro.authc.credential.HashedCredentialsMatcher
# 散列的算法
credentialsMathcher.hashAlgorithmName=md5
# 散列迭代的次数
credentialsMathcher.hashIterations=1024
# 自定义Realm
customeRealm=com.bobo.shiro.realm.MyRealm
customeRealm.credentialsMatcher=$credentialsMathcher
# 将自定义的Realm设置到SecurityManager中
securityManager.realms=$customeRealm
Subject subject = SecurityUtils.getSubject();
if(subject.hasRole(“admin”)) {
//有权限
} else {
//无权限
}
123456
@RequiresRoles("admin")
public void hello() {
//有权限
}
1234
123
[users]
root=123456,role1,role2
# 账号是root,密码是123456 具有的角色是 role1,role2
[roles]
# 角色role1具有的权限
role1=user:create,user:update
role2=user:query,user:create
role3=user:delete,user:query
package com.bobo.shiro.test;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.Factory;
import java.util.Arrays;
public class Test02 {
/**
* Shiro的入门案例
* 账号密码是定义在ini文件中的
* @param args
*/
public static void main(String[] args) {
// 1.获取一个SecurityManager工厂对象
Factory factory = new IniSecurityManagerFactory("classpath:shiro.ini");
// 2.通过SecurityManager工厂对象创建SecurityManager对象
SecurityManager securityManager = factory.getInstance();
// 3.将SecurityManager对象添加到当前的运行环境中去
SecurityUtils.setSecurityManager(securityManager);
// 4.获取Subject对象
Subject subject = SecurityUtils.getSubject();
// 5.获取用户提交的要认证的账号密码
String userName = "root";
String password = "123456";
// 6.将用户提交的账号密码封装为一个Token对象
AuthenticationToken token = new UsernamePasswordToken(userName,password);
// 7.完成认证操作 login
try{
subject.login(token);
System.out.println("登录成功....");
// 做角色的验证操作
System.out.println("认证状态:"+subject.isAuthenticated());
System.out.println("是否具有role1角色:"+subject.hasRole("role1"));
System.out.println("是否具有role3角色:"+subject.hasRole("role3"));
boolean[] types = subject.hasRoles(Arrays.asList("role1", "role2", "role3"));
System.out.println(Arrays.toString(types));
System.out.println(subject.getPrincipal()+"是否具有role1和role2两个角色:"
+ subject.hasAllRoles(Arrays.asList("role1","role2")));
System.out.println(subject.getPrincipal()+"是否具有role1和role3两个角色:"
+ subject.hasAllRoles(Arrays.asList("role1","role3")));
// check开头的方法校验不通过会抛出对应异常
subject.checkRole("role1");
// 做权限的验证
System.out.println(subject.getPrincipal()+"是否具有user:create权限:"+
subject.isPermitted("user:create"));
System.out.println(subject.getPrincipal()+"是否具有user:delete权限:"+
subject.isPermitted("user:delete"));
// check开头的校验方法不通过同样抛出异常信息
subject.checkPermission("user:delete");
}catch (UnknownAccountException e){
System.out.println("账号错误...");
}catch (IncorrectCredentialsException e){
System.out.println("密码错误...");
}
}
}
登录成功....
认证状态:true
是否具有role1角色:true
是否具有role3角色:false
[true, true, false]
root是否具有role1和role2两个角色:true
root是否具有role1和role3两个角色:false
root是否具有user:create权限:true
root是否具有user:delete权限:false
Exception in thread "main" org.apache.shiro.authz.UnauthorizedException: Subject does not have permission [user:delete]
at
org.apache.shiro.authz.ModularRealmAuthorizer.checkPermission(ModularRealmAuthorizer.java:321)
at
org.apache.shiro.mgt.AuthorizingSecurityManager.checkPermission(AuthorizingSecurityManager.java:137)
at
org.apache.shiro.subject.support.DelegatingSubject.checkPermission(DelegatingSubject.java:198)
at com.bobo.shiro.test.Test02.main(Test02.java:57)
/**
* 授权操作
* 认证成功后会执行的授权方法
* 要注意的是 doGetAuthorizationInfo方法的形参的实际数据是
* 认证方法中返回的 SimpleAuthenticationInfo中的第一个参数
* @param principalCollection
* @return
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
// 获取到当前登录的账号
String userName = principalCollection.getPrimaryPrincipal().toString();
System.out.println("当前登录的账号是:" + userName);
// 根据登录的账号去数据库中查询对应的角色和权限信息
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
info.addRole("role1");
info.addRole("role2");
info.addStringPermission("user:create");
info.addStringPermission("user:update");
return info;
}
[main]
# 自定义Realm
customeRealm=com.bobo.shiro.realm.MyRealm
# 将自定义的Realm设置到SecurityManager中
securityManager.realms=$customeRealm
package com.bobo.shiro.test;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.Factory;
import java.util.Arrays;
public class Test02 {
/**
* Shiro的入门案例
* 账号密码是定义在ini文件中的
* @param args
*/
public static void main(String[] args) {
// 1.获取一个SecurityManager工厂对象
Factory factory = new IniSecurityManagerFactory("classpath:shiro.ini");
// 2.通过SecurityManager工厂对象创建SecurityManager对象
SecurityManager securityManager = factory.getInstance();
// 3.将SecurityManager对象添加到当前的运行环境中去
SecurityUtils.setSecurityManager(securityManager);
// 4.获取Subject对象
Subject subject = SecurityUtils.getSubject();
// 5.获取用户提交的要认证的账号密码
String userName = "zhang";
String password = "123";
// 6.将用户提交的账号密码封装为一个Token对象
AuthenticationToken token = new UsernamePasswordToken(userName,password);
// 7.完成认证操作 login
try{
subject.login(token);
System.out.println("登录成功....");
// 做角色的验证操作
System.out.println("认证状态:"+subject.isAuthenticated());
System.out.println("是否具有role1角色:"+subject.hasRole("role1"));
System.out.println("是否具有role3角色:"+subject.hasRole("role3"));
boolean[] types = subject.hasRoles(Arrays.asList("role1", "role2", "role3"));
System.out.println(Arrays.toString(types));
System.out.println(subject.getPrincipal()+"是否具有role1和role2两个角色:"
+ subject.hasAllRoles(Arrays.asList("role1","role2")));
System.out.println(subject.getPrincipal()+"是否具有role1和role3两个角色:"
+ subject.hasAllRoles(Arrays.asList("role1","role3")));
// check开头的方法校验不通过会抛出对应异常
subject.checkRole("role1");
// 做权限的验证
System.out.println(subject.getPrincipal()+"是否具有user:create权限:"+
subject.isPermitted("user:create"));
System.out.println(subject.getPrincipal()+"是否具有user:delete权限:"+
subject.isPermitted("user:delete"));
// check开头的校验方法不通过同样抛出异常信息
subject.checkPermission("user:delete");
}catch (UnknownAccountException e){
System.out.println("账号错误...");
}catch (IncorrectCredentialsException e){
System.out.println("密码错误...");
}
}
}
登录的账号密码是:zhang 123
登录成功....
认证状态:true
当前登录的账号是:zhang
是否具有role1角色:true
当前登录的账号是:zhang
是否具有role3角色:false
当前登录的账号是:zhang
当前登录的账号是:zhang
当前登录的账号是:zhang
[true, true, false]
当前登录的账号是:zhang
当前登录的账号是:zhang
zhang是否具有role1和role2两个角色:true
当前登录的账号是:zhang
当前登录的账号是:zhang
zhang是否具有role1和role3两个角色:false
当前登录的账号是:zhang
当前登录的账号是:zhang
zhang是否具有user:create权限:true
当前登录的账号是:zhang
zhang是否具有user:delete权限:false
当前登录的账号是:zhang
Exception in thread "main" org.apache.shiro.authz.UnauthorizedException: Subject does not have permission [user:delete]
at
org.apache.shiro.authz.ModularRealmAuthorizer.checkPermission(ModularRealmAuthorizer.java:321)
at
org.apache.shiro.mgt.AuthorizingSecurityManager.checkPermission(AuthorizingSecurityManager.java:137)
at
org.apache.shiro.subject.support.DelegatingSubject.checkPermission(DelegatingSubject.java:198)
at com.bobo.shiro.test.Test02.main(Test02.java:58)
CREATE TABLE `t_user_new` (
`id` int NOT NULL AUTO_INCREMENT,
`username` varchar(30) NOT NULL,
`password` varchar(100) DEFAULT NULL,
`salt` varchar(100) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci
org.apache.shiro
shiro-spring
1.5.3
Archetype Created Web Application
contextConfigLocation
classpath:applicationContext-*.xml
org.springframework.web.context.ContextLoaderListener
springmvc
org.springframework.web.servlet.DispatcherServlet
contextConfigLocation
classpath:spring-mvc.xml
springmvc
/
encodingFilter
org.springframework.web.filter.CharacterEncodingFilter
encoding
UTF-8
forceRequestEncoding
true
forceResponseEncoding
true
encodingFilter
/*
default
*.html
default
*.css
default
*.js
default
*.jpg
default
*.png
shiroFilter
org.springframework.web.filter.DelegatingFilterProxy
targetFilterLifecycle
true
targetBeanName
shiro
shiroFilter
/*
/login.do=authc
/**=anon
package com.bobo.realm;
import com.bobo.pojo.User;
import com.bobo.service.IUserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.SimpleByteSource;
import org.springframework.beans.factory.annotation.Autowired;
public class MyRealm extends AuthorizingRealm {
@Autowired
private IUserService userService;
/***
* 认证方法
* @param authenticationToken
* @return
* @throws AuthenticationException
*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
User user = userService.login(token.getUsername());
if(user == null){
return null;
}
return new SimpleAuthenticationInfo(user
,user.getPassword()
,new SimpleByteSource(user.getSalt())
,"myRealm"
);
}
/**
* 授权方法
* @param principalCollection
* @return
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
User user = (User) principalCollection.getPrimaryPrincipal();
System.out.println("--->" + user.getUsername());
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
info.addRole("admin");
info.addRole("root");
return info;
}
}
package com.bobo.controller;
import com.bobo.pojo.User;
import com.bobo.service.IUserService;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
@Controller
public class UserController {
@Autowired
private IUserService service;
@GetMapping("/user/query")
@ResponseBody
public String query(){
return service.query(new User()).toString();
}
/**
* 本方法是Realm认证失败后会进入的方法
* @param model
* @param request
* @return
*/
@RequestMapping("/login.do")
public String login(Model model, HttpServletRequest request){
// 当认证失败的时候会将失败信息保存的request对应的属性中
Object obj = request.getAttribute(FormAuthenticationFilter.DEFAULT_ERROR_KEY_ATTRIBUTE_NAME);
System.out.println("错误信息:" + obj);
return "/login.jsp";
}
}
<%--
Created by IntelliJ IDEA.
User: dpb
Date: 2021/2/19
Time: 20:31
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
Title
@RequestMapping("/logout.do")
public void logout(){
SecurityUtils.getSubject().logout();
}
org.springframework
spring-aspects
${spring.version}
/**
* 授权方法
* @param principalCollection
* @return
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
User user = (User) principalCollection.getPrimaryPrincipal();
System.out.println("--->" + user.getUsername());
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
info.addRole("admin");
info.addRole("root");
return info;
}
package com.bobo.controller;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/order")
public class OrderController {
@RequiresRoles(value = {"admin"},logical = Logical.AND)
@GetMapping("/query")
public String query(){
return "query ... ";
}
@RequiresRoles(value = {"root","root1"},logical = Logical.AND)
@GetMapping("/add")
public String add(){
return "add ... ";
}
@RequiresRoles(value = {"root","root1"},logical = Logical.OR)
@GetMapping("/update")
public String update(){
return "update ... ";
}
@GetMapping("/delete")
public String delete(){
return "delete ... ";
}
}
<%--
Created by IntelliJ IDEA.
User: dpb
Date: 2021/2/21
Time: 14:06
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
Title
您没有访问当前请求的权限!请联系系统管理员:xxxxxxxxx
q
redirect:/unauthorized.jsp
<%@taglib prefix="shiro" uri="http://shiro.apache.org/tags" %>
<%--
Created by IntelliJ IDEA.
User: dpb
Date: 2021/2/21
Time: 14:16
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="shiro" uri="http://shiro.apache.org/tags" %>
Title
用户管理
查询用户
添加用户
更新用户
删除用户
123
请登录
123
123
123
123
123
123
123
退出
org.apache.shiro
shiro-spring
1.2.3
org.apache.shiro
shiro-ehcache
1.2.3
net.sf.ehcache
ehcache-core
2.5.0