Springboot Shiro Certification Authority

Source: Internet
Author: User
Tags stack trace

Shiro Essentials Table: User, role, permissions 1:1:n one (variable)

------------------------------------------------------------------

Shiro configuration (similar to XML configuration in SSM)

Package Cn.xydata.config.shiro;

Import cn.xydata.entity.system.Permission;
Import Cn.xydata.service.impl.system.PermisssionServiceImpl;
Import Cn.xydata.service.system.PermissionService;
Import Org.apache.shiro.cache.ehcache.EhCacheManager;
Import Org.apache.shiro.spring.LifecycleBeanPostProcessor;
Import Org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
Import Org.apache.shiro.spring.web.ShiroFilterFactoryBean;
Import Org.apache.shiro.web.mgt.DefaultWebSecurityManager;
Import Org.slf4j.Logger;
Import Org.slf4j.LoggerFactory;
Import Org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
Import Org.springframework.context.annotation.Bean;
Import org.springframework.context.annotation.Configuration;

Import Java.util.LinkedHashMap;
Import java.util.List;
Import Java.util.Map;

@Configuration
public classShiroconfig{
private static final Logger Logger = Loggerfactory.getlogger (Shiroconfig.class);

@Bean (name= "Permissionservice")
Public Permissionservice Getpermissionservice () {
return new Permisssionserviceimpl ();
}


@Bean (name = "Shiroehcachemanager")
Public Ehcachemanager Getehcachemanager () {
Ehcachemanager em = new Ehcachemanager ();
Em.setcachemanagerconfigfile ("Classpath:ehcache.xml");
return em;
}

@Bean (name = "Myshirorealm")
Public Myshirorealm Getshirorealm () {
Myshirorealm realm = new Myshirorealm ();
Realm.setcachemanager (Getehcachemanager ());
return realm;
}
@Bean (name = "Lifecyclebeanpostprocessor")
Public Lifecyclebeanpostprocessor Getlifecyclebeanpostprocessor () {
return new Lifecyclebeanpostprocessor ();
}

@Bean
Public Defaultadvisorautoproxycreator Getdefaultadvisorautoproxycreator () {
Defaultadvisorautoproxycreator Daap = new Defaultadvisorautoproxycreator ();
Daap.setproxytargetclass (TRUE);
return DAAP;
}

@Bean (name = "SecurityManager")
Public Defaultwebsecuritymanager Getdefaultwebsecuritymanager () {
Defaultwebsecuritymanager DWSM = new Defaultwebsecuritymanager ();
Dwsm.setrealm (Getshirorealm ());
Dwsm.setcachemanager (Getehcachemanager ());

return DWSM;
}

@Bean
Public Authorizationattributesourceadvisor Getauthorizationattributesourceadvisor () {
Authorizationattributesourceadvisor Aasa = new Authorizationattributesourceadvisor ();
Aasa.setsecuritymanager (Getdefaultwebsecuritymanager ());
return AASA;
}

private void Loadshirofilterchain (Shirofilterfactorybean shirofilterfactorybean) {
Associating database Permissions
list<permission> Permissions=getpermissionservice (). GetPermissions ();

Logger.info (string.valueof (Permissions.size ()));
map<string, string> filterchaindefinitionmap = new linkedhashmap<string, string> ();
For (Permission permission:permissions) {
Filterchaindefinitionmap.put (Permission.getpageurl (), "authc,perms[" +permission.getid () + "]");
}
Releasing static resources and landing interfaces
Filterchaindefinitionmap.put ("/login", "anon");
Filterchaindefinitionmap.put ("/css/**", "anon");
Filterchaindefinitionmap.put ("/js/**", "anon");
Filterchaindefinitionmap.put ("/bootstrap/**", "anon");
Filterchaindefinitionmap.put ("/img/**", "anon");
Filterchaindefinitionmap.put ("/dist/**", "anon");
Filterchaindefinitionmap.put ("/plugins/**", "anon");
Filterchaindefinitionmap.put ("/**", "authc");
Shirofilterfactorybean.setfilterchaindefinitionmap (FILTERCHAINDEFINITIONMAP);
}
//shiro Intercept
@Bean (name = "Shirofilter")
Public Shirofilterfactorybean Getshirofilterfactorybean () {
Shirofilterfactorybean Shirofilterfactorybean=null;
try {
Shirofilterfactorybean = new Myshirofilterfactorybean ();

Shirofilterfactorybean.setsecuritymanager (Getdefaultwebsecuritymanager ());

Shirofilterfactorybean.setloginurl ("/login");

Shirofilterfactorybean.setsuccessurl ("/index.html");
Shirofilterfactorybean.setunauthorizedurl ("/403");

Loadshirofilterchain (Shirofilterfactorybean);

} catch (Exception e) {

E.printstacktrace ();
}
return Shirofilterfactorybean;
}

}
-----------------------------------------------------------------------------------------------------------
Customizing Shirorealm to implement actions on custom data tables
Package Cn.xydata.config.shiro;

Import Cn.xydata.entity.system.User;
Import Cn.xydata.mapper.system.UserMapper;
Import Org.apache.commons.lang3.builder.ReflectionToStringBuilder;
Import Org.apache.commons.lang3.builder.ToStringStyle;
Import Org.apache.shiro.SecurityUtils;
Import org.apache.shiro.authc.*;
Import Org.apache.shiro.authc.credential.HashedCredentialsMatcher;
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.subject.Subject;
Import Org.slf4j.Logger;
Import Org.slf4j.LoggerFactory;
Import org.springframework.beans.factory.annotation.Autowired;
Import Tk.mybatis.mapper.entity.Example;

Import javax.annotation.PostConstruct;
Import Java.util.Set;


public class Myshirorealm extends Authorizingrealm {

private static final Logger Logger = Loggerfactory.getlogger (Myshirorealm.class);
Private static final String algorithm = "MD5";

@Autowired
Private Usermapper Usermapper;

@PostConstruct
public void Initcredentialsmatcher () {
Hashedcredentialsmatcher matcher = new Hashedcredentialsmatcher (algorithm);
Setcredentialsmatcher (Matcher);
}
@Override
Protected Authorizationinfo Dogetauthorizationinfo (PrincipalCollection principalcollection) {
logger.info ("################# #执行Shiro授权 ##################");
String Username= (String) Super.getavailableprincipal (principalcollection);
Simpleauthorizationinfo authorizationinfo = new Simpleauthorizationinfo ();
set<string> roles = Usermapper.finduserroles (username);
Authorizationinfo.setroles (roles);
set<string> permissions = usermapper.finduserpermissions (username);
Authorizationinfo.setstringpermissions (permissions);

return authorizationinfo;
}
@Override
Protected AuthenticationInfo Dogetauthenticationinfo (
Authenticationtoken Authenticationtoken) throws Authenticationexception {
//Certification
Usernamepasswordtoken token= (Usernamepasswordtoken) Authenticationtoken;
Logger.info ("Get to token when validating current subject:" + reflectiontostringbuilder.tostring (token, tostringstyle.multi_line_style)) ;
String username = (string) token.getprincipal ();
User User=usermapper.findbyusername (username);
if (user==null) {
throw new Unknownaccountexception ();//No account found
}
Subject CurrentUser = Securityutils.getsubject ();
Currentuser.getsession (). SetAttribute ("userid", User.getid ());
Currentuser.getsession (). SetAttribute ("ISAdmin", User.getadmin ());
Currentuser.getsession (). SetAttribute ("username", username);

if (Boolean.TRUE.equals (user.getlocked ())) {
throw new Lockedaccountexception (); Account lockout
}
Simpleauthenticationinfo AuthenticationInfo = new Simpleauthenticationinfo (
User.getusercode (),
USER.GETPASSWD (),
GetName ()
);
/* Simplebytesource sbs=new Simplebytesource (User.getusercode (). GetBytes ());
Authenticationinfo.setcredentialssalt (SBS); */
return authenticationinfo;
}

}

-----------------------------------------------------------------------------------------------------------
Custom Interception Factory
Package Cn.xydata.config.shiro;

Import Org.apache.shiro.mgt.SecurityManager;
Import Org.apache.shiro.spring.web.ShiroFilterFactoryBean;
Import Org.apache.shiro.web.filter.mgt.FilterChainManager;
Import Org.apache.shiro.web.filter.mgt.FilterChainResolver;
Import Org.apache.shiro.web.filter.mgt.PathMatchingFilterChainResolver;
Import Org.apache.shiro.web.mgt.WebSecurityManager;
Import Org.apache.shiro.web.servlet.AbstractShiroFilter;
Import org.springframework.beans.factory.BeanInitializationException;

Import Javax.servlet.FilterChain;
Import javax.servlet.ServletException;
Import Javax.servlet.ServletRequest;
Import Javax.servlet.ServletResponse;
Import Javax.servlet.http.HttpServletRequest;
Import java.io.IOException;
Import Java.util.HashSet;
Import Java.util.Set;

public class Myshirofilterfactorybean extends Shirofilterfactorybean {

Private set<string> Ignoreext;

Public Myshirofilterfactorybean () {
Super ();
Ignoreext = new hashset<> ();
Ignoreext.add (". jpg");
Ignoreext.add (". png");
Ignoreext.add (". gif");
Ignoreext.add (". bmp");
Ignoreext.add (". js");
Ignoreext.add (". css");
}

@Override
Protected Abstractshirofilter CreateInstance () throws Exception {

SecurityManager SecurityManager = getSecurityManager ();
if (SecurityManager = = null) {
String msg = "SecurityManager property must is set.";
throw new Beaninitializationexception (msg);
}

if (! ( SecurityManager instanceof Websecuritymanager)) {
String msg = "The Security Manager does not implement the Websecuritymanager interface.";
throw new Beaninitializationexception (msg);
}

Filterchainmanager manager = Createfilterchainmanager ();

Pathmatchingfilterchainresolver chainresolver = new Pathmatchingfilterchainresolver ();
Chainresolver.setfilterchainmanager (manager);

return new Mspringshirofilter ((Websecuritymanager) SecurityManager, chainresolver);
}

Private Final class Mspringshirofilter extends Abstractshirofilter {

Protected Mspringshirofilter (Websecuritymanager Websecuritymanager, Filterchainresolver resolver) {
Super ();
if (Websecuritymanager = = null) {
throw new IllegalArgumentException ("Websecuritymanager property cannot is null.");
}
Setsecuritymanager (Websecuritymanager);
if (resolver! = null) {
Setfilterchainresolver (resolver);
}
}

@Override
protected void Dofilterinternal (ServletRequest servletrequest, Servletresponse servletresponse,
Filterchain chain) throws Servletexception, IOException {
HttpServletRequest request = (httpservletrequest) servletrequest;
String str = Request.getrequesturi (). toLowerCase ();
Boolean flag = true;
int idx = 0;
if (idx = Str.indexof (".")) > 0) {
str = str.substring (IDX);
if (Ignoreext.contains (Str.tolowercase ()))
Flag = false;
}
if (flag) {
Super.dofilterinternal (ServletRequest, Servletresponse, chain);
}else{
Chain.dofilter (ServletRequest, servletresponse);
}
}

}
}
-----------------------------------------------------------------------------------------
Example Application of Shiro
@ResponseBody ()
@RequestMapping (value = "/login", method = Requestmethod.post)
Public Response Login (
@RequestParam (value= "UserName", required=false,defaultvalue= "") String UserName,
@RequestParam (value= "PassWord", required=false,defaultvalue= "") String PassWord,
@RequestParam (value= "RememberMe", required=false,defaultvalue= "false") Boolean rememberme,
Redirectattributes redirectattributes) {
Usernamepasswordtoken token = new Usernamepasswordtoken (UserName, password,rememberme);
Subject CurrentUser = Securityutils.getsubject ();
try {
Logger.info ("User [" + userName + "] Login verification: Validation Start ");
Currentuser.login (token);
Logger.info ("User [" + userName + "] Login verification: Verified by ");
}catch (unknownaccountexception UAE) {
Logger.info ("User [" + userName + "] Login verification: Verification failed, unknown account ");
Redirectattributes.addflashattribute ("message", "User name does not exist");
return new Response (exceptionmsg.loginnamenotexists);
}catch (Incorrectcredentialsexception ice) {
Logger.info ("User [" + userName + "] Login verification: Verification failed, wrong voucher ");
Redirectattributes.addflashattribute ("message", "Password is incorrect");
return new Response (Exceptionmsg.passworderror);
}catch (Lockedaccountexception Lae) {
Logger.info ("User [" + userName + "] Login verification: Verification failed, account locked ");
Redirectattributes.addflashattribute ("message", "Account Locked");
return new Response (Exceptionmsg.userlock);
}catch (Excessiveattemptsexception Eae) {
Logger.info ("User [" + userName + "] Login verification: Validation failed, excessive number of errors ");
Redirectattributes.addflashattribute ("message", "User name or password error too many times");
return new Response (Exceptionmsg.loginnameorpassworderror);
}catch (Authenticationexception ae) {
Logger.info ("User [" + userName + "] Login verification: Validation failed, stack trace is as follows ");
Ae.printstacktrace ();
Redirectattributes.addflashattribute ("message", "User name or password is incorrect");
return new Response (Exceptionmsg.loginnameorpassworderror);
}
if (currentuser.isauthenticated ()) {
Httpsession.setattribute ("username", Currentuser.getprincipal ());
return new Response (exceptionmsg.success);
}else{
return new Response (exceptionmsg.failed);
}

}

Springboot Shiro Certification Authority

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.