Spring boot support added shiro

Add dependencies in the project

       <!-- shiro spring. -->
	<dependency>
		<groupId>org.apache.shiro</groupId>
		<artifactId>shiro-spring</artifactId>
		<version>1.4.0</version>
	</dependency>
	<!-- shiro core -->
	<dependency>
		<groupId>org.apache.shiro</groupId>
		<artifactId>shiro-core</artifactId>
		<version>1.4.0</version>
	</dependency>

New spring folder under the profile directory, create a new folder in the spring-shiro.xml file

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:util="http://www.springframework.org/schema/util" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="
       http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
       http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">



	<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
		<-! Ref correspondence we write realm myRealm ->
		<property name="realm" ref="AuthRealm" />
		<! - the following configurations use Cache Manager ->
		<!-- <property name="cacheManager" ref="shiroEncacheManager" /> -->
	</bean>




	<-! Safety Certification Filter ->
	<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
		<! - call us configurable permissions manager ->
		<property name="securityManager" ref="securityManager" />
		<! - Configure the login request our address ->
		<property name="loginUrl" value="/toLogin" />
		<! - Configure jump address after our successful login on the login page, non / login if you access the address, skip to the address you visit ->
		<property name="successUrl" value="/" />
		<! - If you requested resources are no longer your purview, go to the / 403 requests address ->
		<property name="unauthorizedUrl" value="/html/403.html" />
		<property name="filterChainDefinitions">
			<value>
			<-! Anon authc is allowed to pass through the opposite ->
				/statics/**=anon
				/login=anon
				/** = authc
			</value>
		</property>
	</bean>


	<! - to ensure the realization of the bean lifecycle execution Shiro internal functions ->
	<bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor" />

	<-! AOP approach level permissions check ->
	<bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator" depends-on="lifecycleBeanPostProcessor">
		<property name="proxyTargetClass" value="true" />
	</bean>
	<bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
		<property name="securityManager" ref="securityManager" />
	</bean>




</beans>

Loading the primary inlet spring-shiro.xml

@ImportResource({ "classpath:spring/spring-shiro.xml" })

Log in to change Controller

		// constructor login parameters
		UsernamePasswordToken token = new UsernamePasswordToken(name, pwd);
		try {
			// class treatment to the Realm
			SecurityUtils.getSubject().login(token);
		} catch (UnknownAccountException uae) {
			map.put ( "msg", "unknown user");
			return "login";
		} catch (IncorrectCredentialsException ice) {
			map.put ( "msg", "password");
			return "login";
		} catch (AuthenticationException ae) {
			// unexpected condition? error?
			map.put ( "msg", "server busy");
			return "login";
		}
	 
		return "redirect:/toIndex";

Log in to see the five lines will know to deal with the Realm class, so we have a class Realm

In the main entrance where it can be scanned to create a new class and inherits AuthRealm AuthorizingRealm, rewriting doGetAuthenticationInfo (login logic), overwrite doGetAuthorizationInfo (authorization logic)

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

public class AuthRealm extends AuthorizingRealm {

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		// TODO Auto-generated method stub
		return null;
	}

}

Login authentication method is written in doGetAuthenticationInfo

		// Get Token
		UsernamePasswordToken token2 = (UsernamePasswordToken) token;
		// Get the user name
		String userName = token2.getUsername();
		// Get Password
		String pwd = new String(token2.getPassword());
		// Here I'm using MyBatis-puls3.0
		// query objects
		QueryWrapper<User> queryWrapper = new QueryWrapper();
		// query the user
		queryWrapper.eq("name", userName).or().eq("phone", userName);
		//Inquire
		User user = iUserService.getOne(queryWrapper);
		// check back object is empty
		if (CommonUtil.isBlank(user)) {
			// throw an exception unknown account
			throw new UnknownAccountException();
		}
		// check the back of the object code and password are not equal
		if (!CommonUtil.isEquals(user.getPwd(), pwd)) {
			// throw an exception credentials are incorrect
			throw new IncorrectCredentialsException();
		}
		// described above are passed on the user exists and the password is equal to
		// verify successful
		SecurityUtils.getSubject().getSession().setAttribute(Constant.SESSION_USER_KEY, user);
		// returns shiro User Information
		// token pass over the password authentication password must be used with the same information pass in, encrypted passwords must be encrypted pass over

		return new SimpleAuthenticationInfo(user, user.getPwd(), getName());

If you want to set permissions, in the corresponding method plus Controllerf

@RequiresPermissions("/system/user/list")

Within doGetAuthorizationInfo way to write

// Create a simple authorization information objects
SimpleAuthorizationInfo simpleAuthorizationInfo=new SimpleAuthorizationInfo();
//Granted permission
simpleAuthorizationInfo.addStringPermission("/system/user/list");

return simpleAuthorizationInfo;

  

When all Controller are added after the @RequiresPermissions notes, if access to unauthorized Controller error.

Guess you like

Origin www.cnblogs.com/mowen120/p/11908061.html