栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

spring security 入门

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

spring security 入门

基本环境搭建

1、创建spring boot项目,导入依赖


        
            org.springframework.boot
            spring-boot-starter-security
        
        
            org.springframework.boot
            spring-boot-starter-web
        

        
            org.springframework.boot
            spring-boot-devtools
            runtime
            true
        
        
            org.springframework.boot
            spring-boot-configuration-processor
            true
        
        
            org.springframework.boot
            spring-boot-starter-test
            test
        
        
            org.springframework.security
            spring-security-test
            test
        
    

2、创建测试controller

@RestController
@RequestMapping("test")
public class TestController {
    @RequestMapping("hello")
    public String hello(){
        return "hello";
    }
}

3、自动创建启动类

@SpringBootApplication
public class SpringSecurityApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringSecurityApplication.class, args);
    }

}

4、application.properties文件设置端口

server.port=8081

5、启动

6、网页测试http://localhost:8081/test/hello

输出user和控制台的密码

通过配置文件为Spring Security设定用户名和密码
spring.security.user.name=zhangsan
spring.security.user.password=123456

这时只有配置文件的账号密码可用

通过内存设置账号密码
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter
{
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String password = passwordEncoder.encode("123"); //加密密码
        auth.inMemoryAuthentication().withUser("lucy").password(password).roles("admin");
        auth.inMemoryAuthentication().withUser("jack").password(password).roles("user");
    }

    @Bean
    PasswordEncoder password(){
        return new BCryptPasswordEncoder();
    }
}
通过数据库进行验证

1、添加依赖

		
            org.springframework.boot
            spring-boot-starter-data-jpa
        
        
            org.projectlombok
            lombok
        
        
            mysql
            mysql-connector-java
        

2、配置数据库

# 数据源
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://47.94.143.161:3306/SpringSecurity?characterEncoding=utf8&useUnicode=true&useSSL=false
spring.datasource.username=spring_security
spring.datasource.password=@Springsecurity1
#jpa配置
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true

3、mysql表结构

CREATE TABLE `user` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `username` varchar(255) DEFAULT NULL,
  `password` varchar(255) DEFAULT NULL,
  `role` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;

4、model,repository,service
这里是使用spring data JPA技术,没有使用mybatis
model

@Entity
@Table(name = "user")
@Setter
@Getter
@ToString
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;
    private String username;
    private String password;
    private String role;
}

repository

@Repository
public interface UserRepository extends JpaRepository {
    User findByUsername(String username);
}

sevice

@Service
public class UserService implements UserDetailsService {
    @Resource
    private UserRepository userRepository;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        try {
            User user = userRepository.findByUsername(username);
            if(null==user){
                throw new UsernameNotFoundException("用户不存在");
            }
            System.out.println("查找用户"+user);
            List authorities = new ArrayList<>();
            if(!StringUtils.isNullOrEmpty(user.getRole())){
                String[] roles = user.getRole().split(",");
                for (String role : roles) {
                    authorities.add(new SimpleGrantedAuthority(role.trim()));
                }
            }
            //这里可以对密码加密,相应的需要在认证阶段对密码进行解密
            return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), authorities);
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }
}

5、config设置

@Configuration
public class SecurityConfig2 extends WebSecurityConfigurerAdapter {
    @Resource
    UserService userService;

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userService).passwordEncoder(passwordEncoder());
    }
    @Bean
    public PasswordEncoder passwordEncoder(){
        return NoOpPasswordEncoder.getInstance();// 使用非加密算法保持密码
        //return new BCryptPasswordEncoder();
    }
}

6、controller测试

@RestController
@RequestMapping("test")
@Secured("ROLE_USER")  //只有ROLE_USER角色权限才能访问
public class TestController {
    @RequestMapping("hello")
    public String hello(){
        return "hello";
    }
}

这里使用注解在进行角色权限限定,需要在启动类上开启权限注解功能,

@SpringBootApplication
@EnableGlobalMethodSecurity(securedEnabled = true)
public class SpringSecurityApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringSecurityApplication.class, args);
    }
}

所以登录时,只有user用户拥有ROLE_USER角色,也只有user才能访问test/hello

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/489835.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号