Springboot整合Shiro
2021-02-08 00:17
标签:star ide def request auth manage router class extends 目录如下 com config ShiroConfig.java UserRealm.java controller RouterController.java SpringbootShrioApplication shiro有三个核心(配置时都必须装配成Bean): Realm(连接数据) 开始配置ShiroConfig,从底层开始配置(从下往上),Realm需要额外写一个类UserRealm,这个类便是shiro的核心 UserRealm只需继承AuthorizingRealm类即可,要实现如下两个方法,本类为shiro核心: 流程: controller接受请求代码(用户提交表单时用controller接收): getAuthenticationInfo()代码: Springboot整合Shiro 标签:star ide def request auth manage router class extends 原文地址:https://www.cnblogs.com/tianqiqing21du/p/12773539.htmlSpringboot整合Shiro
1、导入依赖
2、配置ShiroConfig
@Configuration
public class ShiroConfig{
//shriofilterbean
//这个方法名必须为shiroFilterFactoryBean,否则报错
@Bean
public ShiroFilterFactoryBean shiroFilterFactoryBean(@Qualifier("securityManager") DefaultWebSecurityManager securityManager){
System.out.println("subject@");
ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
//关联securityManager
bean.setSecurityManager(securityManager);
//给请求设置权限
//authc:需要认证才可访问
//anon:无需认证也能访问
Map
//自定义的realm
public class UserRealm extends AuthorizingRealm {
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
System.out.println("授权");
return null;
}
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
System.out.println("认证");
return null;
}
}
3、实现用户登陆认证
@RequestMapping("/login")
public String login(String usr, String pwd, Model model){
//获取当前用户
Subject subject = SecurityUtils.getSubject();
//封装用户的登陆数据,生成令牌
UsernamePasswordToken token = new UsernamePasswordToken(usr,pwd);
//用令牌登陆,如果没有异常则登陆成功
try{
subject.login(token);
//无异常则登陆成功
return "index";
}catch(UnknownAccountException e){
model.addAttribute("msg","用户名错误");
return "login";
}catch(IncorrectCredentialsException e){
model.addAttribute("msg","密码错误");
return "login";
}
}
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
System.out.println("认证");
//用户名,密码,应该从数据库取,此处仅测试
String usr="wagn";
String pwd="123";
//先取令牌
UsernamePasswordToken token = (UsernamePasswordToken)authenticationToken;
//验证用户名
if(!usr.equals(token.getUsername())){
return null;
}
//验证密码,Shiro自动验证,只需要把数据库的密码传过去就好了
return new SimpleAuthenticationInfo("",pwd,"");
}
上一篇:2020年,阿里内推Java后端面试题,文末附面试福利。
下一篇:Java继承