shiro use - integrate spring
1. Import related configuration
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.9.1</version>
</dependency>
2. The custom Realm class inherits AuthorizingRealm and overrides the corresponding method
- Get user identity information
- Call the business layer to obtain user information (database)
- Non-empty judgment, encapsulate the data and return
@Component
public class MyRealm extends AuthorizingRealm {
@Autowired
private UserMapper userMapper;
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
return null;
}
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
String name = authenticationToken.getPrincipal().toString();
User user = userMapper.selectById(name);
if (user != null){
SimpleAuthenticationInfo sai = new SimpleAuthenticationInfo(
name, user.getPassword(), ByteSource.Util.bytes("salt"), MyRealm.class.getName()
);
return sai;
}
return null;
}
}
3. Write shiro configuration class
Configure securityManager
- Create a defaultWebSecurityManager object
- Create a spanning object and set related attributes
2.1 Use md5 encryption
2.2 Iterative encryption times
- Store the plus object in myRealm
- Save myRealm as an AdefaultWebSecurityManager object
- return
Configure shiro's built-in filter interception range
- authentication required
- no authentication required
@Configuration
public class shiroConfig {
@Autowired
private MyRealm myRealm;
@Bean
public DefaultWebSecurityManager defaultWebSecurityManager() {
DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();
hashedCredentialsMatcher.setHashAlgorithmName("md5");
hashedCredentialsMatcher.setHashIterations(3);
myRealm.setCredentialsMatcher(hashedCredentialsMatcher);
defaultWebSecurityManager.setRealm(myRealm);
ThreadContext.bind(defaultWebSecurityManager);
return defaultWebSecurityManager;
}
@Bean
public DefaultShiroFilterChainDefinition shiroFilterChainDefinition(){
DefaultShiroFilterChainDefinition defaultShiroFilterChainDefinition = new DefaultShiroFilterChainDefinition();
defaultShiroFilterChainDefinition.addPathDefinition("/login","anon");
defaultShiroFilterChainDefinition.addPathDefinition("/user","anon");
defaultShiroFilterChainDefinition.addPathDefinition("/**","authc");
return defaultShiroFilterChainDefinition;
}
}
4. Go back to the business layer and verify the login through the subject.login() method
Subject subject = SecurityUtils.getSubject();
AuthenticationToken token = new UsernamePasswordToken(user.getUsername(),user.getPassword());
try {
subject.login(token);
}catch (Exception e){
e.printStackTrace();
return ComResult.error("登录失败");
}
return ComResult.success("登录成功");