SpringBoot2.3.2整合SpringSecurity实现使用数据库登录

主要步骤

1、创建数据库表(user,role,user_role,permission,role_permission),这里为了测试方便只创建了前三个表
2、配置连接池和ORM框架,测试使用的时druid数据源和mybatis
3、配置SecurityConfig继承WebSecurityConfigurerAdapter,并添加@EnableWebSecurity(组合注解),重新configure方法
4、编写一个Service类并实现UserDetailsService接口,重写loadUserByUsername方法

1、数据库

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for role
-- ----------------------------
DROP TABLE IF EXISTS `role`;
CREATE TABLE `role` (
  `id` int(3) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of role
-- ----------------------------
INSERT INTO `role` VALUES ('1', 'VIP1');
INSERT INTO `role` VALUES ('2', 'VIP2');
INSERT INTO `role` VALUES ('3', 'VIP3');


-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
  `id` int(3) NOT NULL AUTO_INCREMENT,
  `username` varchar(20) DEFAULT NULL,
  `password` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of user  密码为:PasswordEncoderFactories.createDelegatingPasswordEncoder().encode("123");
-- ----------------------------
INSERT INTO `user` VALUES ('1', 'zhangsan', '{bcrypt}$2a$10$NhTcM87XJrKe8EbdtpaVqu/auoMIvVboBRWNXhCAsRCeOn6OIAUHG');
INSERT INTO `user` VALUES ('2', 'lisi', '{bcrypt}$2a$10$NhTcM87XJrKe8EbdtpaVqu/auoMIvVboBRWNXhCAsRCeOn6OIAUHG');
INSERT INTO `user` VALUES ('3', 'wangwu', '{bcrypt}$2a$10$NhTcM87XJrKe8EbdtpaVqu/auoMIvVboBRWNXhCAsRCeOn6OIAUHG');

-- ----------------------------
-- Table structure for user_role
-- ----------------------------
DROP TABLE IF EXISTS `user_role`;
CREATE TABLE `user_role` (
  `id` int(3) NOT NULL AUTO_INCREMENT,
  `userId` int(3) DEFAULT NULL,
  `roleId` int(3) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of user_role
-- ----------------------------
INSERT INTO `user_role` VALUES ('1', '1', '1');
INSERT INTO `user_role` VALUES ('2', '1', '2');
INSERT INTO `user_role` VALUES ('3', '2', '2');
INSERT INTO `user_role` VALUES ('4', '2', '3');
INSERT INTO `user_role` VALUES ('5', '3', '1');
INSERT INTO `user_role` VALUES ('6', '3', '3');

注意数据库user表密码使用的是:PasswordEncoderFactories.createDelegatingPasswordEncoder().encode("123");
SpringSecurity5升级后不支持明文密码,若不使用Encoder,会抛java.lang.IllegalArgumentException: There is no PasswordEncoder mapped for the id "null"异常
或者在明文密码前添加{noop},这样spring security就不会进行解密

2、配置druid数据源和mybatis

application.properties配置

spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/cache?useUnicode=true&characterEncoding=utf-8
spring.datasource.username=root
spring.datasource.password=xxxxxxx
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
#druid其他配置,需要在配置类中关联
spring.datasource.initialSize=5
spring.datasource.minIdle=5
spring.datasource.maxActive=20
spring.datasource.maxWait=60000
spring.datasource.timeBetweenEvictionRunsMillis=60000
spring.datasource.minEvictableIdleTimeMillis=300000
spring.datasource.validationQuery=SELECT 1 FROM DUAL
spring.datasource.testWhileIdle=true
spring.datasource.testOnBorrow=false
spring.datasource.testOnReturn=false
spring.datasource.poolPreparedStatements=true

spring.datasource.filters=stat,wall,log4j
spring.datasource.maxPoolPreparedStatementPerConnectionSize=20
spring.datasource.useGlobalDataSourceStat=true
spring.datasource.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500

Druid配置类:DruidConfig

//导入druid数据源
@Configuration
public class DruidConfig {

    //把yml中的配置生效
    @ConfigurationProperties(prefix = "spring.datasource")
    @Bean
    public DataSource druid(){
       return  new DruidDataSource();
    }

    //配置Druid的监控
    //1、配置一个管理后台的Servlet
    @Bean
    public ServletRegistrationBean statViewServlet(){
        ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
        /*Springboot 1.5 的写法*/
        //Map<String,String> initParams = new HashMap<>();  
        //initParams.put("loginUsername","admin");
        //initParams.put("loginPassword","123456");
        //initParams.put("allow","");
        //initParams.put("deny","192.168.15.21");
        //bean.setInitParameters(initParams);
        
        /*Springboot 2.1.9不需要再建HashMap*/
        bean.addInitParameter("loginUsername","admin");
        bean.addInitParameter("loginPassword","123456");
        bean.addInitParameter("allow",""); //默认就是允许所有访问
        bean.addInitParameter("deny","192.168.15.21");
        return bean;
    }


    //2、配置一个web监控的filter
    @Bean
    public FilterRegistrationBean webStatFilter(){
        FilterRegistrationBean bean = new FilterRegistrationBean();
        bean.setFilter(new WebStatFilter());
        /*Springboot 1.5 的写法*/
        //Map<String,String> initParams = new HashMap<>();
        //initParams.put("exclusions","*.js,*.css,/druid/*");
        //bean.setInitParameters(initParams);

        bean.addInitParameter("exclusions","*.js,*.css,/druid/*");
        bean.setUrlPatterns(Arrays.asList("/*"));

        return  bean;
    }
}

3、WebSecurityConfigurerAdapter子类(自定义)

SecurityConfig

@EnableWebSecurity  //改为@Configuration也可以
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/").permitAll()
                .antMatchers("/level1/**").hasRole("VIP1")
                .antMatchers("/level2/**").hasRole("VIP2")
                .antMatchers("/level3/**").hasRole("VIP3") //需要VIP3角色
                .antMatchers("/access").access("hasRole('VIP3')")  //需要VIP3
                .antMatchers("/user/**").hasAnyRole("VIP1","VIP2","VIP3") //只要有其中一个角色就可以
                .antMatchers("/hello/**").authenticated();  //只要认证就可以

        //开启自动配置的登陆功能,效果,如果没有登陆,没有权限就会来到登陆页面
        //1、默认post形式的 /login代表处理登陆
        //2、重定向到/login?error表示登陆失败
        //3、一但定制loginPage;那么 loginPage的post请求就是登陆
        http.formLogin()
                .usernameParameter("user")  //指定参数名 默认username
                .passwordParameter("pwd")   //指定参数名 默认password
                .loginPage("/userlogin")    //指定登录页面 默认post方式的/login
                .permitAll();
        //.successForwardUrl(String forwardUrl),.failureForwardUrl(String forwardUrl)指定登录成功/失败的跳转页面
        //.successHandler(AuthenticationSuccessHandler handler),.failureHandler(AuthenticationFailureHandler handler)  如果是前后的分离的项目可以用这个方法
        /*.successHandler(new AuthenticationSuccessHandler() {
            @Override
            public void onAuthenticationSuccess(HttpServletRequest req, HttpServletResponse resp, Authentication authentication) throws IOException, ServletException {
                resp.setContentType("application/json;charset=utf-8");
                PrintWriter out = resp.getWriter();
                Map<String,Object> map = new HashMap<>();
                map.put("status",200);
                map.put("msg","登录成功");
                map.put("data",authentication.getPrincipal());
                String result = new ObjectMapper().writeValueAsString(map);
                out.write(result);
                out.flush();
                out.close();
            }
        })
        .failureHandler(new AuthenticationFailureHandler() {
            @Override
            public void onAuthenticationFailure(HttpServletRequest req, HttpServletResponse resp, AuthenticationException exception) throws IOException, ServletException {
                resp.setContentType("application/json;charset=utf-8");
                PrintWriter out = resp.getWriter();
                Map<String,Object> map = new HashMap<>();
                map.put("status",400);
                Stirng msg = "登录失败";
                if (exception instanceof LockedException) {
                    msg = "账户被锁定,请联系管理员!";
                } else if (exception instanceof CredentialsExpiredException) {
                    msg = "密码过期,请联系管理员!";
                } else if (exception instanceof AccountExpiredException) {
                    msg = "账户过期,请联系管理员!";
                } else if (exception instanceof DisabledException) {
                   msg = "账户被禁用,请联系管理员!";
                } else if (exception instanceof BadCredentialsException) {
                    msg = "用户名或者密码输入错误,请重新输入!";
                }
                map.put("msg",msg);
                String result = new ObjectMapper().writeValueAsString(map);
                out.write(result);
                out.flush();
                out.close();
            }
        })*/

        //开启自动配置的注销功能。
        //1、访问 /logout 表示用户注销,清空session
        //2、默认注销成功会返回 /login?logout 页面;
        http.logout().logoutSuccessUrl("/");//注销成功以后来到首页
        /* 前后端分离的项目使用logoutSuccessHandler
      .logoutSuccessHandler(new LogoutSuccessHandler() {
                    @Override
                    public void onLogoutSuccess(HttpServletRequest req, HttpServletResponse resp, Authentication authentication) throws IOException, ServletException {
                        resp.setContentType("application/json;charset=utf-8");
                        PrintWriter out = resp.getWriter();
                        out.write(new ObjectMapper().writeValueAsString(RespBean.ok("注销成功!")));
                        out.flush();
                        out.close();
                    }
                })
        */
        
        //开启记住我功能
        http.rememberMe().rememberMeParameter("remeber");
        //登陆成功以后,将cookie发给浏览器保存,以后访问页面带上这个cookie,只要通过检查就可以免登录
        //点击注销会删除cookie

    }

    /*@Override  //用于添加内存中的用户、密码、权限
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //super.configure(auth);
        PasswordEncoder encoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();
        auth.inMemoryAuthentication()
                .withUser("zhangsan").password(encoder.encode("123")).roles("VIP1","VIP2")
                .and()
                .withUser("lisi").password(encoder.encode("123")).roles("VIP2,VIP3")
                .and()
                .withUser("wangwu").password(encoder.encode("123")).roles("VIP1","VIP3");

    }*/
}

4、UserDetailsService实现类(自定义)

MyUserDetailsService
SpringSecurity中Role和Authority区别,系统在添加Role时会添加ROLE_前缀,而Authority不会,所以在重写的loadUserByUsername中添加了前缀后,在SecurityConfig重写的configure方法中添加页面权限应该使用hasRole,在html中使用<sec:authorize="hasRole('VIP1')">或<sec:authorize="hasAuthority('ROLE_VIP1')">,若没有添加前缀,在SecurityConfig重写的configure方法中添加页面权限应该使用hasAuthority,html中使用<sec:authorize="hasAuthority('VIP1')">
Role和Authority区别参考https://www.cnblogs.com/Rocky_/p/11799772.html

@Service
public class MyUserDetailsService implements UserDetailsService {
    @Resource
    MyMapper myMapper;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Collection<GrantedAuthority> authorities = new ArrayList<>();
        User user = myMapper.getUserByUsername(username);  //这里也可以让User类去实现UserDetails类,实现里边的方法,然后直接返回这个User
        List<Role> roles = myMapper.getRolesByUserId(user.getId());
        for(Role role:roles){
            authorities.add(new SimpleGrantedAuthority("ROLE_"+role.getName()));
        }
        return new org.springframework.security.core.userdetails.User(username,user.getPassword(),authorities);
    }
}

MyMapper,为了简单直接写在了一个mapper里

@Mapper  //或者在配置类或springboot主程序上添加@MapperScan("自己的mapper包")
public interface MyMapper {
    @Select("select * from user where username=#{username}")
    User getUserByUsername(String username);

    @Select("select * from role where id in (select roleId from user_role where userId=#{userId})")
    List<Role> getRolesByUserId(int userId);
}

前端,需导入themeleaf及thymeleaf-extras-springsecurity5

KungfuController用于前端访问

@Controller
public class KungfuController {
    private final String PREFIX = "pages/";
    /**
     * 欢迎页
     * @return
     */
    @GetMapping("/")
    public String index() {
        return "welcome";
    }
    
    /**
     * 登陆页
     * @return
     */
    @GetMapping("/userlogin")
    public String loginPage() {
        return PREFIX+"login";
    }
    
    /**
     * level1页面映射
     * @param path
     * @return
     */
    @GetMapping("/level1/{path}")
    public String level1(@PathVariable("path")String path) {
        return PREFIX+"level1/"+path;
    }

    /**
     * level2页面映射
     * @param path
     * @return
     */
    @GetMapping("/level2/{path}")
    public String level2(@PathVariable("path")String path) {
        return PREFIX+"level2/"+path;
    }

    /**
     * level3页面映射
     * @param path
     * @return
     */
    @GetMapping("/level3/{path}")
    public String level3(@PathVariable("path")String path) {
        return PREFIX+"level3/"+path;
    }
}
前端目录结构

welcome.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
      xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1 align="center">欢迎光临武林秘籍管理系统</h1>
<div sec:authorize="!isAuthenticated()">
    <h2 align="center">游客您好,如果想查看武林秘籍 <a th:href="@{/userlogin}">请登录</a></h2>
</div>
<div sec:authorize="isAuthenticated()">
    <h2><span sec:authentication="name"></span>,您好,您的角色有:
        <span sec:authentication="principal.authorities"></span></h2>
    <form th:action="@{/logout}" method="post">
        <input type="submit" value="注销"/>
    </form>
</div>
<hr>
<div sec:authorize="hasRole('VIP1')"><!--注意使用的是hasRole,需要在MyUserDetailsService重写的loadUserByUsername方法中Collection<GrantedAuthority> authorities中添加的rolename添加ROLE_前缀-->
    <h3>普通武功秘籍</h3>
    <ul>
        <li><a th:href="@{/level1/1}">罗汉拳</a></li>
        <li><a th:href="@{/level1/2}">武当长拳</a></li>
        <li><a th:href="@{/level1/3}">全真剑法</a></li>
    </ul>
</div>
<div sec:authorize="hasRole('VIP2')"> 
    <h3>高级武功秘籍</h3>
    <ul>
        <li><a th:href="@{/level2/1}">太极拳</a></li>
        <li><a th:href="@{/level2/2}">七伤拳</a></li>
        <li><a th:href="@{/level2/3}">梯云纵</a></li>
    </ul>
</div>
<div sec:authorize="hasRole('VIP3')">
    <h3>绝世武功秘籍</h3>
    <ul>
        <li><a th:href="@{/level3/1}">葵花宝典</a></li>
        <li><a th:href="@{/level3/2}">龟派气功</a></li>
        <li><a th:href="@{/level3/3}">独孤九剑</a></li>
    </ul>
</div>
</body>
</html>

login.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
    <h1 align="center">欢迎登陆武林秘籍管理系统</h1>
    <hr>
    <div align="center">
        <form th:action="@{/userlogin}" method="post">
            用户名:<input name="user"/><br>
            密码:<input name="pwd"><br/>
            <input type="checkbox" name="remeber"> 记住我<br/>
            <input type="submit" value="登陆">
        </form>
    </div>
</body>
</html>

pom文件

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.1.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.crsbg</groupId>
    <artifactId>cache</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>cache</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-amqp</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.3</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.38</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.23</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>log4j-over-slf4j</artifactId>
        </dependency>
        <dependency>
            <groupId>org.thymeleaf.extras</groupId>
            <artifactId>thymeleaf-extras-springsecurity5</artifactId>
        </dependency>


        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

开启方法级别的安全注解

1、在SecurityConfig配置类添加@EnableGlobalMethodSecutiry注解

@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true,securedEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

2、在Service的方法上添加@PreAuthorize或@Secured注解(prePostEnabled=true开启preAuthorize和postAuthorize注解,securedEnabled = true开启Secured注解)

@PreAuthorize("hasRole('admin')")
public String admin(){
    return "admin";
}
@Secured("ROLE_user")
public String user(){
    return "user";
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 205,132评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 87,802评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 151,566评论 0 338
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,858评论 1 277
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,867评论 5 368
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,695评论 1 282
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,064评论 3 399
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,705评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 42,915评论 1 300
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,677评论 2 323
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,796评论 1 333
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,432评论 4 322
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,041评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,992评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,223评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,185评论 2 352
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,535评论 2 343