Shiro Official website: http://shiro.apache.org/ Project Structure
Single Sign-on address configuration
Biz.properties
biz.ldapurl=***-ad-01.ymt.corp
Springboot Loading
Application.java
Configuration
Import Org.springframework.beans.factory.annotation.Value;
Import org.springframework.stereotype.Component;
@Component public class Bizconfig {@Value ("${biz.ldapurl}") Private String Ldapurl;
@Value ("${stress.clientip}") Private String Stressip;
@Value ("${sit.clientip}") Private String Sitip;
@Value ("${uat.clientip}") Private String Uatip;
@Value ("${clientport}") Private String clientport;
@Value ("${isenablesend}") Private Boolean isenablesend;
@Value ("${alarm.cron}") Private String Alarmcron;
Public String Getldapurl () {return ldapurl;
} public void Setldapurl (String ldapurl) {this.ldapurl = Ldapurl;
} public String Getstressip () {return stressip;
} public void Setstressip (String stressip) {this.stressip = Stressip;
} public String Getsitip () {return sitip;
} public void Setsitip (String sitip) {this.sitip = Sitip;
} Public String Getuatip () {return uatip;
} public void Setuatip (String uatip) {this.uatip = Uatip;
} public String Getclientport () {return clientport;
} public void Setclientport (String clientport) {this.clientport = ClientPort;
} public boolean isenablesend () {return isenablesend;
The public void Setenablesend (Boolean enablesend) {isenablesend = Enablesend;
} public String Getalarmcron () {return alarmcron;
} public void Setalarmcron (String alarmcron) {This.alarmcron = Alarmcron; }
}
Import Com.ymatou.envmanagement.shiro.AdminAuthorizationFilter;
Import Com.ymatou.envmanagement.shiro.MyAuthorizingRealm;
Import Com.ymatou.envmanagement.shiro.SecurityFilterChainDefinitionSource;
Import Org.apache.commons.logging.Log;
Import Org.apache.commons.logging.LogFactory;
Import Org.apache.shiro.realm.AuthorizingRealm;
Import Org.apache.shiro.spring.LifecycleBeanPostProcessor;
Import Org.apache.shiro.spring.web.ShiroFilterFactoryBean;
Import Org.apache.shiro.web.mgt.DefaultWebSecurityManager;
Import Org.springframework.context.annotation.Bean;
Import org.springframework.context.annotation.Configuration;
Import Javax.servlet.Filter;
Import Java.util.HashMap;
Import Java.util.Map;
@Configuration public class Shiroconfig {private static Log logger = Logfactory.getlog (Shiroconfig.class); @Bean public Shirofilterfactorybean Shirofilter () throws Exception {map<string, filter> filters = new
Hashmap<string, filter> (); Filters.put ("admin", new Adminauthorizationfilter ());
Shirofilterfactorybean Shirofilterfactorybean = new Shirofilterfactorybean ();
Shirofilterfactorybean.setfilters (filters);
Shirofilterfactorybean.setsecuritymanager (SecurityManager ());
Shirofilterfactorybean.setfilterchaindefinitionmap (Filterchaindefinitionsource (). GetObject ());
return Shirofilterfactorybean; } @Bean (name = "SecurityManager") public Org.apache.shiro.mgt.SecurityManager SecurityManager () {Defaul
Twebsecuritymanager SecurityManager = new Defaultwebsecuritymanager ();
Securitymanager.setrealm (Myrealm ());
return SecurityManager;
} @Bean Public Authorizingrealm Myrealm () {return new Myauthorizingrealm (); } @Bean Public Lifecyclebeanpostprocessor lifecyclebeanpostprocessor () {return new Lifecyclebeanpostproc
Essor (); } @Bean Public Securityfilterchaindefinitionsource Filterchaindefinitionsource () {RETurn new Securityfilterchaindefinitionsource (); }
Custom Code
Import Com.ymatou.envmanagement.model.User;
Import Com.ymatou.envmanagement.util.CurrentUserUtil;
Import Org.apache.shiro.web.filter.authz.AuthorizationFilter;
Import Javax.servlet.ServletRequest;
Import Javax.servlet.ServletResponse;
public class Adminauthorizationfilter extends Authorizationfilter {
@Override
protected Boolean isaccessallowed (ServletRequest request, servletresponse response, Object mappedvalue) throws Exception {
User user = Currentuserutil.getcurrentuser ();
if (user! = null) {
return true;
}
return false;
}
}
Import Com.ymatou.envmanagement.config.BizConfig;
Import com.ymatou.envmanagement.exception.BaseRunTimeException;
Import Com.ymatou.envmanagement.util.LdapHelper;
Import Org.apache.commons.lang3.StringUtils;
Import Org.apache.commons.logging.Log;
Import Org.apache.commons.logging.LogFactory;
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.springframework.beans.factory.annotation.Autowired; public class Myauthorizingrealm extends Authorizingrealm {private static Log logger = Logfactory.getlog (Myauthorizin
Grealm.class);
@Autowired private Bizconfig Bizconfig;
@Override protected Authorizationinfo Dogetauthorizationinfo (principalcollection principals) {return null; } @Override protected AuthenticationInfo dogetauthenticationinfo (Authenticationtoken token) throws Authenticat ionexception {UsErnamepasswordtoken Authctoken = (usernamepasswordtoken) token;
String userName = Authctoken.getusername ();
String password = string.valueof (Authctoken.getpassword ());
Logger.info ("Login userName:" + userName);
String Ldapurl = Bizconfig.getldapurl (); if (ldaphelper.authenticate (userName, password, ldapurl)) {return new Simpleauthenticationinfo (UserName, pass
Word, getName ()); } else {if (Stringutils.isnotblank (userName) && stringutils.isnotblank (password)) {//
Password = cipherutil.encryptmd5 (password);
User user = Userservice.getuser (userName, password); /**//* Re-put to prevent Shiro error org.apache.shiro.authc.IncorrectCredentialsException:// * submitted credentials for Token [org.apache.shiro.authc.usernamepasswordtoken-admin, rememberme=true]//
* did not match the expected credentials. //*///Authctoken.setpassword (Password.tochararray ()); if (user! = null) {//return new Simpleauthenticationinfo (User.getusername (), User.get
Password (), GetName ());
}else {//throw new Baseruntimeexception ("Username or password error");//} throw new Baseruntimeexception (String.Format ("Authenticate Failed.
UserName:%s ", UserName));
}} return null;
}
}
Import Org.apache.shiro.config.Ini;
Import org.apache.shiro.web.config.IniFilterChainResolverFactory;
Import Org.springframework.beans.factory.FactoryBean;
public class Securityfilterchaindefinitionsource implements factorybean<ini.section> {
@Override
Public Ini.section GetObject () throws Exception {
return loadsection ();
@Override public
class<?> Getobjecttype () {
return this.getclass ();
}
@Override Public
Boolean Issingleton () {
return true;
}
Private Ini.section loadsection () {
ini ini = ini.fromresourcepath ("Classpath:shiro.ini");
Ini.section section = ini.getsection (inifilterchainresolverfactory.urls);
return section;
}
}
using the example
Import Com.ymatou.envmanagement.model.User;
Import Com.ymatou.envmanagement.util.SessionUtil;
Import Com.ymatou.envmanagement.util.WapperUtil;
Import Org.apache.commons.lang3.StringUtils;
Import Org.apache.shiro.SecurityUtils;
Import org.apache.shiro.authc.AuthenticationException;
Import Org.apache.shiro.authc.UsernamePasswordToken;
Import Org.apache.shiro.subject.Subject;
Import Org.slf4j.Logger;
Import Org.slf4j.LoggerFactory;
Import org.springframework.web.bind.annotation.RequestMapping;
Import Org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping ("") public class Logincontroller {private final static Logger Logger = Loggerfactory
. GetLogger (Logincontroller.class); @RequestMapping ("/auth") Public Object auth (string username, string password) {string errormessage = "Unknown error.
"; if (Stringutils.isnotblank (username) && Stringutils.isnotblank (password)) {//Get subject and create username/password Authentication
Token (i.e. User ID/voucher) Subject CurrentUser = Securityutils.getsubject (); If the user is already logged on if (currentuser.isauthenticated ()) {return wapperutil.success ("The user is already logged in.
"); } if (Username.equals ("admin") && password.equals ("admin")) {//Get authenticated user us
ER user user = new user ();
User.setusername (username);
User.setpassword (password);
Increase the user's relevant data into session adduserinfotosession (user);
return wapperutil.success ("login Successful");
}//Login token to verify Usernamepasswordtoken token = new Usernamepasswordtoken (username, password, true);
try {currentuser.login (token);
Determine if the user has been authenticated if (currentuser.isauthenticated ()) {//Get Authenticated Users user
User user = new user ();
User.setusername (username); User.setpassword (password);
Increase the user's relevant data into session adduserinfotosession (user);
return wapperutil.success ("login Successful"); }} catch (Authenticationexception e) {//Login Failed errormessage = E.getcause ()! = null? E.getcau
Se (). GetMessage (): E.getmessage ();
Logger.info ("Login Failed", e); } catch (Exception e) {errormessage = "Unknown error.
";
Logger.info ("Login Failed", e); }} else {errormessage = "The user name or password is empty.
";
} return Wapperutil.error (errormessage); }/** * Add user information to session */private void adduserinfotosession (user user) {//Set user's information to session
Sessionutil.put (sessionutil.session_key_user_id, User.getusername ());
Sessionutil.put (Sessionutil.session_key_user, USER); } @RequestMapping ("/logout") public Object logout () {Subject subjECT = Securityutils.getsubject ();
if (subject.isauthenticated ()) {subject.logout ();
return wapperutil.success (); } return Wapperutil.error ("You are not logged in yet.
");
} @RequestMapping ("/version") public String version () {return ' 2017-03-09-1 ';
} @RequestMapping ("/warmup") public String status () {return "OK";
}
}
Specific principle Reference: http://blog.csdn.net/catoop/article/details/50520958