我是靠谱客的博主 清秀烤鸡,最近开发中收集的这篇文章主要介绍spring security快速入门 (无多余额外功能) ps:情人节不得学一手认证鉴权压压惊,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

 ps:情人节不得学一手认证鉴权压压惊

1.导入依赖

 <dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.1</version>
</dependency>
</dependencies>

配置数据库连接 yml

server:
port: 8080
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/easymybatis?serverTimezone=GMT%2B8
username: root
password: 123456

2.实现UserDetailsServic接口(自行创建mapper接口)

数据库结构:

@Service
public class MyUserDetailService implements UserDetailsService {
@Autowired
private UserMapper userMapper;
@Override
public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
QueryWrapper<MemberUser> queryWrapper=new QueryWrapper<>();
queryWrapper.eq("name",s);
MemberUser memberUser = userMapper.selectOne(queryWrapper);
if (memberUser==null){
throw new UsernameNotFoundException("验证失败");
}
List<GrantedAuthority> auths= AuthorityUtils.commaSeparatedStringToAuthorityList("role");
return new User(memberUser.getName(),new BCryptPasswordEncoder().encode(memberUser.getPassword()),auths);
}
}

3.编写相关配置类 继承WebSecurityConfigurerAdapter

@SpringBootConfiguration
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private MyUserDetailService userDetailService;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//super.configure(auth);
//用DetailService 方式鉴权
auth.userDetailsService(userDetailService).passwordEncoder(passwordEncoder());
}
//老版不分离自定义登录方案
/* @Override
protected void configure(HttpSecurity http) throws Exception {
http.formLogin()
.loginPage("index.html") //登录页面
.successForwardUrl("success.html")
//登录成功跳转
.loginProcessingUrl("/user/login").permitAll()
//请求服务器路径
.and().authorizeRequests()
.antMatchers("/","index/html").permitAll() //不需要认证
.antMatchers("/test").hasAnyAuthority("role") //拥有权限才能访问
.anyRequest().authenticated()
.and().csrf().disable();
}
*/
//加密措施
@Bean
PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
}

4.测试

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

最后

以上就是清秀烤鸡为你收集整理的spring security快速入门 (无多余额外功能) ps:情人节不得学一手认证鉴权压压惊的全部内容,希望文章能够帮你解决spring security快速入门 (无多余额外功能) ps:情人节不得学一手认证鉴权压压惊所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(32)

评论列表共有 0 条评论

立即
投稿
返回
顶部