SpringBoot - shiro 作登录认证和拦截
Controller
@Api (tags = "管理系统登录页面", value = "账号密码认证")
@RestController
public class LoginController {
@Autowired
private LoginService loginService;
@PostMapping("/login")
public BaseResponseUtil login(@RequestParam("userName") String userName, @RequestParam ("password") String password){
Subject subject = SecurityUtils.getSubject();
UsernamePasswordToken token = new UsernamePasswordToken(userName, password);
try {
subject.login(token);
return DataResponseUtil.success(CodeEnum.SUCCESS,"登录成功");
}catch (UnknownAccountException e){
return DataResponseUtil.error (CodeEnum.BAD_REQUEST, "用户名或密码错误");
}catch (IncorrectCredentialsException e){
return DataResponseUtil.error(CodeEnum.BAD_REQUEST,"用户名或密码错误");
}
}
}
ShiroConfig
@Configuration
public class ShiroConfig {
@Bean
public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManager") DefaultWebSecurityManager defaultWebSecurityManager){
ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager);
Map<String, String> filterChainDefinitionMap = new LinkedHashMap<>();
filterChainDefinitionMap.put("*/login","anon");
shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
shiroFilterFactoryBean.setLoginUrl("/login");
return shiroFilterFactoryBean;
}
@Bean(name = "securityManager")
public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm){
DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
defaultWebSecurityManager.setRealm(userRealm);
return defaultWebSecurityManager;
}
@Bean(name = "userRealm")
public UserRealm userRealm(){
return new UserRealm();
}
}
UserRealm
public class UserRealm extends AuthorizingRealm {
@Autowired
private LoginService loginService;
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
return null;
}
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
String username = ((UsernamePasswordToken) token).getUsername();
Login login = loginService.selectUserByName(username);
if (login==null){
return null;
}
String password = login.getPassword();
String realmName = getName();
ByteSource credentialsSalt = ByteSource.Util.bytes(username);
SimpleAuthenticationInfo authcInfo = new SimpleAuthenticationInfo(username, password,credentialsSalt,realmName);
return authcInfo;
}
}