shiro请求授权实现[springboot12]

shiro请求授权实现

项目结构:

shiro请求授权实现[springboot12]_第1张图片

pom.xml


<dependency>
     <groupId>org.projectlombokgroupId>
      <artifactId>lombokartifactId>
dependency>


<dependency>
     <groupId>mysqlgroupId>
     <artifactId>mysql-connector-javaartifactId>
     <scope>runtimescope>
      <version>5.1.39version>
dependency>


<dependency>
     <groupId>log4jgroupId>
     <artifactId>log4jartifactId>
     <version>1.2.17version>
dependency>


<dependency>
     <groupId>com.alibabagroupId>
     <artifactId>druidartifactId>
     <version>1.1.21version>
dependency>


<dependency>
     <groupId>org.mybatis.spring.bootgroupId>
     <artifactId>mybatis-spring-boot-starterartifactId>
     <version>2.1.1version>
dependency>




        
<dependency>
     <groupId>org.apache.shirogroupId>
     <artifactId>shiro-springartifactId>
     <version>1.4.1version>
dependency>



<dependency>
   <groupId>org.thymeleafgroupId>
   <artifactId>thymeleaf-spring5artifactId>
dependency>

<dependency>
     <groupId>org.thymeleaf.extrasgroupId>
      <artifactId>thymeleaf-extras-java8timeartifactId>
dependency>


application.properties

# 应用名称
spring.application.name=demo-shiro
# 应用服务 WEB 访问端口
server.port=8080
#整合mybatis
mybatis.type-aliases-package=com.example.demoshiro.pojo
mybatis.mapper-locations=classpath:mapper/*.xml




application.yaml

spring:
  datasource:
    username: root
    password: xxxxx
    url: jdbc:mysql://localhost:3306/test?serverTimezone=UTC&useUnicode=true&characterEncoding=UTF-8
    driver-class-name: com.mysql.jdbc.Driver
    type: com.alibaba.druid.pool.DruidDataSource

    #springBoot默认是不注入这些属性值的,需要自己绑定
    #druid数据源专有配置
    initialSize: 5
    minIdle: 5
    maxActive: 20
    maxWait: 60000
    timeBetweenEvictionRunsMillis: 60000
    minEvictableIdleTimeMillis: 300000
    validationQuery: SELECT 1 FROM DUAL
    testWhileIdle: true
    testOnBorrow: false
    testOnReturn: false
    poolPreparedStatements: true

    #配置监控统计拦截的filters,stat:监控统计,log4j:日志记录,wall:防止sql注入
    #如果允许报错时 java.lang.ClassNotFoundException:org.apache.log4j.Priority
    #则导入log4j依赖即可,Maven地址:https://mvnrepository.com/artifact/log4j/log4j
    filters: stat,wall,log4j
    maxPoolPreparedStatementPerConnectionSize: 20
    useGlobalDataSourceStat: true
    connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500

UserMapper.xml



<mapper namespace="com.example.demoshiro.mapper.UserMapper">
   <select id="queryUserByName" parameterType="String" resultType="User">
       select * from test.user where name = #{name }
   select>


mapper>

add.html


<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Titletitle>
head>
<body>
<h1>addh1>
body>
html>

update.html


<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Titletitle>
head>
<body>
<h1>updateh1>
body>
html>

index.html


<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Titletitle>
head>
<body>
<h1>首页h1>
<div th:text="${msg}">div>
<hr>

<a th:href="@{/user/add}">adda> | <a th:href="@{/user/update}">updatea>

body>
html>

login.html


<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Titletitle>
head>
<body>
<h1>登录h1>
<hr>
<p th:text="${msg}" style="color: red;">p>
<form th:action="@{/login}">
    <p>用户名:<input type="text" name="username"> p>
    <p>密码:<input type="text" name="password"> p>
    <p><input type="submit">p>
form>
body>
html>

ShiroConfig.java

@Configuration
public class ShiroConfig {
     

//    ShiroFilterFactoryBean:3
    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManager") DefaultWebSecurityManager defaultWebSecurityManager){
     
        ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
//        设置安全管理器
        bean.setSecurityManager(defaultWebSecurityManager);
//        添加shiro的内置过滤器
        /**
         * anon:无需认证就可以访问
         * authc:必须认证了才能访问
         * user:必须拥有 记住我 功能才能用
         * perms: 拥有对某个资源的权限才能访问
         * role :拥有某个角色权限才能访问
         */
//        拦截
        Map<String, String> filterMap = new LinkedHashMap<>();
//        授权,正常的情况下,没有授权会跳转到未授权页面
        filterMap.put("/user/add","perms[user:add]");
        filterMap.put("/user/update","perms[user:update]");
//      user页面下的页面要认证了才能访问
        filterMap.put("/user/*","authc");

        bean.setFilterChainDefinitionMap(filterMap);

//        设置登录的请求
        bean.setLoginUrl("/toLogin");
//        设置未授权页面
        bean.setUnauthorizedUrl("/noauth");

        return bean;
    }


//    DefaultWebSecurityManager:2
    @Bean(name="securityManager")
    public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm){
     
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
//        关联UserRealm
        securityManager.setRealm(userRealm);
        return securityManager;
    }

//    创建realm对象,需要自定义类:1
    @Bean
    public UserRealm userRealm(){
     
        return new UserRealm();
    }

}

UserRealm.java

//自定义的UserRealm extends AuthorizingRealm
public class UserRealm extends AuthorizingRealm {
     
    @Autowired
    UserService userService;

//    授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
     
        System.out.println("执行了->授权doGetAuthorizationInfo");
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
//        info.addStringPermission("user:add");

//        拿到当前登录的这个对象
        Subject subject = SecurityUtils.getSubject();
        User currentUser = (User)subject.getPrincipal();//拿到User对象

//        设置当前用户的权限
        info.addStringPermission(currentUser.getPerms());

        return info;
    }

//    认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
     
        System.out.println("执行了->认证doGetAuthorizationInfo");
//        用户名,密码,数据中取
//        String name = "root";
//        String password = "123456";
        UsernamePasswordToken userToken = (UsernamePasswordToken) authenticationToken;
        //连接真实数据库
        User user = userService.queryUserByName(userToken.getUsername());
        if(user == null){
      //没有这个人
            return null; //UnknownAccountException
        }
        //可以加密, MD5加密,MD5盐值加密
        //密码认证,shiro做
        return new SimpleAuthenticationInfo(user,user.getPwd(),"");
    }
}

MyController.java

@Controller
public class MyController {
     

    @RequestMapping({
     "/","/index"})
    public String toIndex(Model model){
     
            model.addAttribute("msg","hello,shiro");
            return "index";
    }

    @RequestMapping("/user/add")
    public String add(){
     
        return "user/add";
    }

    @RequestMapping("/user/update")
    public String update(){
     
        return "user/update";
    }

    @RequestMapping("/toLogin")
    public String toLogin(){
     
        return "login";
    }

    @RequestMapping("/login")
    public String login(String username,String password,Model model){
     
//        获取当前的用户
        Subject subject = SecurityUtils.getSubject();
//        封装用户的登录数据
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        try{
     
//        执行登录方法,如果没有异常就说明ok了
            subject.login(token);
            return "index";
        }catch (UnknownAccountException e){
       //用户名不存在
            model.addAttribute("msg","用户名错误");
            return "login";
        }catch (IncorrectCredentialsException e){
     //密码不存在
            model.addAttribute("msg","密码错误");
            return "login";
        }
    }

    @RequestMapping("/noauth")
    @ResponseBody
    public String unauthorized(){
     
        return "未经授权无法访问此页面";
    }


}

UserMapper.java

@Repository
@Mapper
public interface UserMapper {
     
    public User queryUserByName(String name);
}

User.java

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
     
    private int id;
    private String name;
    private String pwd;
    private String perms;
}

UserSservice.java

public interface UserService {
     
    public User queryUserByName(String name);
}

UserServiceImpl.java

@Service
public class UserServiceImpl implements UserService{
     

    @Autowired
    UserMapper userMapper;


    @Override
    public User queryUserByName(String name) {
     
        return userMapper.queryUserByName(name);
    }
}

你可能感兴趣的:(shiro,java)