Spring Boot整合Spring Security
程序员文章站
2022-03-02 14:38:07
...
只开启了简单的登陆验证
添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
MyUserDetailService
@Override @Primary public UserDetails loadUserByUsername(String s)
throws UsernameNotFoundException {
User user = userMapper.selectByPrimaryKey(s);
if (user != null) {
List<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>();
grantedAuthorities.add(new SimpleGrantedAuthority(user.getRole()));
return new org.springframework.security.core.userdetails.User(user.getUsername(),
user.getPassword(), grantedAuthorities);
} else {
throw new UsernameNotFoundException("user<" + s + ">do not exist!");
}
}
WebSecurityConfig
@Configuration @EnableWebSecurity
//@EnableGlobalMethodSecurity(prePostEnabled = true) // 启用方法级别的权限认证
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired private MyUserDetailService myUserDetailService;
@Override protected void configure(HttpSecurity http) throws Exception {
//super.configure(http);
http.csrf().disable();
http.headers().frameOptions().disable();//允许使用frame
http.authorizeRequests().antMatchers("/css/**", "/js/**", "/img/**", "/cdn/**", "/diploma/**")
.permitAll().anyRequest().authenticated().and().formLogin()
.loginPage("/login")// 登录url请求路径 (3)
.defaultSuccessUrl("/").permitAll().and() // 登录成功跳转路径url(4)
.logout().permitAll();
// http.logout().logoutSuccessUrl("/"); // 退出默认跳转页面 (5)
}
@Override protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(myUserDetailService).passwordEncoder(passwordEncoder());
}
@Bean public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
上一篇: spring2.5注释型 + jpa + 数据库池的配置(4)
下一篇: 求职简历中一些常见的问题
推荐阅读
-
详解spring boot容器加载完后执行特定操作
-
Spring Boot + Kotlin整合MyBatis的方法教程
-
Spring Boot中使用RabbitMQ的示例代码
-
浅析Spring Boot中的spring-boot-load模块
-
spring-boot-klock-starter V1.1 主体功能重大更新内容介绍
-
spring boot 1.5.4 集成shiro+cas,实现单点登录和权限控制
-
详解Spring Boot 配置多个RabbitMQ
-
Spring Boot实现通用的接口参数校验
-
Spring Boot @Async 异步任务执行方法
-
spring整合kaptcha验证码的实现