博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Spring boot for Eclipse 开发指南第四节 Spring-Security
阅读量:6257 次
发布时间:2019-06-22

本文共 4967 字,大约阅读时间需要 16 分钟。

hot3.png

使用自己的数据库中的用户进行验证

1.User 表结构

CREATE TABLE `user` (  `id` int(11) NOT NULL AUTO_INCREMENT,  `username` varchar(18) DEFAULT NULL,  `password` varchar(18) DEFAULT 'zzz123',  `sex` varchar(2) DEFAULT NULL,  `age` int(11) DEFAULT NULL,  `disabled` bit(1) NOT NULL,  PRIMARY KEY (`id`)) ENGINE=InnoDB AUTO_INCREMENT=22 DEFAULT CHARSET=utf8;

2. 引用依赖 POM.XML

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

3. User.java

@Entitypublic class User implements UserDetails {		@Transient	List
list = new ArrayList
(); @Transient private String name; @Id @GeneratedValue private Long id; @Column(nullable = false) private String username; @Column(nullable = false) private String password; @Column(nullable = false) private Integer age; private boolean disabled; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } @Override public Collection
getAuthorities() { return list; } public void setAuthorities(List
list) { this.list = list; } @Override public String getPassword() { // TODO Auto-generated method stub return password; } public void setPassword(String password) { // TODO Auto-generated method stub this.password = password; } @Override public String getUsername() { // TODO Auto-generated method stub return username; } public void setUsername(String username){ this.username = username; } @Override public boolean isAccountNonExpired() { // TODO Auto-generated method stub return true; } @Override public boolean isAccountNonLocked() { // TODO Auto-generated method stub return true; } @Override public boolean isCredentialsNonExpired() { // TODO Auto-generated method stub return true; } @Override public boolean isEnabled() { // TODO Auto-generated method stub return true; }}

 

4. UserRepository.java

public interface UserRepository extends JpaRepository
{ List
findByUsername(String username);}

 

6. UserServiceImpl.java

@Servicepublic class UserServiceImpl implements IUserService {		private static final Log logger = LogFactory.getLog(UserServiceImpl.class);		@Autowired	UserRepository dao;	@Override	public void AddUser(User user) {		// TODO Auto-generated method stub		dao.save(user);		logger.info("add user");	}	@Override	public List
findUserByUsername(String username) { // TODO Auto-generated method stub return dao.findByUsername(username); }}

 

7. SecurityConfig.java 主要配置文件

@Configuration@EnableWebSecurity@EnableGlobalMethodSecuritypublic class SecurityConfig extends WebSecurityConfigurerAdapter {  			@Autowired	@Qualifier("customUserDetailService")	private UserDetailsService userDetailsService;          /**定义认证用户信息获取来源,密码校验规则等*/      @Override      protected void configure(AuthenticationManagerBuilder auth) throws Exception {          //auth.inMemoryAuthentication().withUser("shili").password("zzz123").roles("USER");          //auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());    	auth.userDetailsService(userDetailsService);    }            /**定义安全策略*/      @Override      protected void configure(HttpSecurity http) throws Exception {          http.authorizeRequests()//配置安全策略              .antMatchers("/css/**","/js/**","/img/**","/sayhello").permitAll()//不需要权限的URL             .anyRequest().authenticated()//其他任意URL都需要验证权限            .and()          .logout()              .permitAll()             .and()          .formLogin();      }        @Bean      public BCryptPasswordEncoder passwordEncoder(){      	BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();          return encoder;      }              }

 

8.CustomUserDetailService 使用自己的数据库中的用户

@Service("customUserDetailService")public class CustomUserDetailService implements UserDetailsService {		@Autowired   	private IUserService userService;	@Override	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {		// TODO Auto-generated method stub		List
users = userService.findUserByUsername(username); if(users==null||users.size()==0){ throw new UsernameNotFoundException(""); } User user = users.get(0); List
authorities = new ArrayList<>(); authorities.add(new SimpleGrantedAuthority("ROLE_USER")); user.setAuthorities(authorities); return user; }}

 

 

随便写一个控制器测试一下

@RestControllerpublic class HelloSecurity {		@RequestMapping("/security")      public String security() {          return "hello world security";      }  }

 

转载于:https://my.oschina.net/u/659068/blog/1549186

你可能感兴趣的文章
Spring Boot中使用MyBatis注解配置详解
查看>>
linux下文件的一些文件颜色的含义
查看>>
跨域iframe高度自适应(兼容IE/FF/OP/Chrome)
查看>>
如何花更少的时间学习更多的知识
查看>>
学习鸟哥的Linux私房菜笔记(8)——文件查找与文件管理2
查看>>
升级fedora 18到fedora 19
查看>>
【代码小记】无
查看>>
11月20日学习内容整理:jquery插件
查看>>
Redis客户端集群
查看>>
javascript基础篇:函数
查看>>
SVN与TortoiseSVN实战:补丁详解
查看>>
java一些面试题
查看>>
干货型up主
查看>>
获取页面中所有dropdownlist类型控件
查看>>
读《淘宝数据魔方技术架构解析》有感
查看>>
[转载]如何破解Excel VBA密码
查看>>
【BZOJ】2563: 阿狸和桃子的游戏
查看>>
redis 中文字符显示
查看>>
国内外MD5在线解密网站
查看>>
【OC语法要闻速览】一、方法调用
查看>>