spring security简单配置
spring security简单配置
- 主要集中在5个类里面配置
- 1,实现UserDetailsService
- 2,实现AuthenticationManager
- 3,登录成功与失败的处理
- 4,访问拒绝处理
- 5,核心配置
- POM文件内容添加
使用版本 jdk17,springboot 2.7.1
主要集中在5个类里面配置
1,实现UserDetailsService
@Configuration
public class MyUserDetailsService implements UserDetailsService {private final Map<String, String> users = Map.of("user1", "authority1", "user2", "authority2");@Overridepublic UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {// 省略在数据库查找用户,此时通用密码为123456String password = new BCryptPasswordEncoder().encode("123456");if (!users.containsKey(username)) {throw new UsernameNotFoundException("没有找到用户名!!");}List<GrantedAuthority> grantedAuthorities = AuthorityUtils.createAuthorityList(users.get(username));return new User(username, password, grantedAuthorities);}
}
2,实现AuthenticationManager
@Configuration
public class MyAuthenticationManager implements AuthenticationManager {@Autowiredprivate UserDetailsService userDetailsService;@Autowiredprivate PasswordEncoder passwordEncoder;@Overridepublic Authentication authenticate(Authentication authentication) throws AuthenticationException {UserDetails userDetails = userDetailsService.loadUserByUsername(authentication.getName());if (!passwordEncoder.matches((String) authentication.getCredentials(), userDetails.getPassword())) {throw new BadCredentialsException("用户名或密码错误");}System.out.println(userDetails);return new UsernamePasswordAuthenticationToken(authentication, authentication.getCredentials(),userDetails.getAuthorities());}
}
3,登录成功与失败的处理
@Configuration
public class AuthenticationHandleAdapter implements AuthenticationSuccessHandler, AuthenticationFailureHandler {@Autowiredprivate ObjectMapper objectMapper;private void write(HttpServletResponse response, Object object) {try {response.setContentType(MediaType.APPLICATION_JSON_VALUE);response.setCharacterEncoding("UTF-8");response.getWriter().print(objectMapper.writeValueAsString(object));response.getWriter().flush();} catch (IOException e) {e.printStackTrace();}}@Overridepublic void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,Authentication authentication) throws IOException, ServletException {write(response, Map.of("message", "ok"));}@Overridepublic void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,AuthenticationException exception) throws IOException, ServletException {write(response, Map.of("message", "failed: " + exception.getMessage()));}
}
4,访问拒绝处理
@Configuration
public class MyAccessDeniedHandler implements AccessDeniedHandler {private final ObjectMapper objectMapper;public MyAccessDeniedHandler(ObjectMapper objectMapper) {this.objectMapper = objectMapper;}@Overridepublic void handle(HttpServletRequest request,HttpServletResponse response,AccessDeniedException accessDeniedException) throws IOException, ServletException {try {response.setContentType(MediaType.APPLICATION_JSON_VALUE);response.setCharacterEncoding("UTF-8");response.getWriter().print(objectMapper.writeValueAsString(Map.of("message", "access deny: " + accessDeniedException.getMessage())));response.getWriter().flush();} catch (IOException e) {e.printStackTrace();}}
}
5,核心配置
@Configuration
public class WebSecurityConfig {@BeanPasswordEncoder bCryptPasswordEncoder() {return new BCryptPasswordEncoder();}@BeanSecurityFilterChain filterChain(HttpSecurity http,MyAuthenticationManager authenticationManager,MyAccessDeniedHandler accessDeniedHandler,AuthenticationHandleAdapter authenticationHandler) throws Exception {return http.formLogin(customizer -> customizer.loginPage("/loginPage").successHandler(authenticationHandler).failureHandler(authenticationHandler).loginProcessingUrl("/login")).authorizeRequests(authorizeRequests -> authorizeRequests.antMatchers("/hello").authenticated().antMatchers("/authority1").hasAuthority("authority1").antMatchers("/authority2").hasAuthority("authority2")).exceptionHandling(exceptionHandling -> exceptionHandling.accessDeniedHandler(accessDeniedHandler)).authenticationManager(authenticationManager).csrf().disable().build();}
}
POM文件内容添加
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-security</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency>
spring security简单配置相关推荐
- Spring Security 2 配置精讲
论坛上看了不少Spring Security的相关文章.这些文章基本上都还是基于Acegi-1.X的配置方式,而主要的配置示例也来自于SpringSide的贡献. 众所周知,Spring Securi ...
- SpringBoot + Spring Security 简单入门
这篇文章主要介绍了SpringBoot + Spring Security 简单入门 Spring Security 基本介绍 这里就不对Spring Security进行过多的介绍了,具体的可以参考 ...
- 让Downpour的Spring Security 2 配置精讲简单化,大家一起学习
申明:Spring Security 2 配置精讲 ,系Downpour原创 -------------------------Begin---------------------------- &q ...
- java取消 验证_使用Spring Security Java配置时禁用基本身份验证
我正在尝试使用Spring Security Java配置保护Web应用程序的安全. 这是配置的样子: @Configuration @EnableWebMvcSecurity public clas ...
- Spring Security——简单第三方OAuth2登录自动配置——GitHub登录DEMO
GitHub OAuth2 APP申请 https://github.com/settings/applications/new Maven <!--Spring Security-->& ...
- Spring boot+Spring Security 4配置整合实例
本例所覆盖的内容: 1. 使用Spring Security管理用户身份认证.登录退出 2. 用户密码加密及验证 3. 采用数据库的方式实现Spring Security的remember-me功能 ...
- spring security简单教程以及实现完全前后端分离
spring security是spring家族的一个安全框架,入门简单.对比shiro,它自带登录页面,自动完成登录操作.权限过滤时支持http方法过滤. 在新手入门使用时,只需要简单的配置,即可实 ...
- Spring Security简单SSO
问题 简单使用Spring Security实现简单单点登录. 思路 引入Spring Security ,Spring Session Redis相关库,简单配置Spring Security实现对 ...
- Spring Security简单增加短信验证码登录
查网上资料增加短信验证码登录都要增加一大推,要重头写Spring Security的实现,我呢,只想在原来的密码登录基础上简单实现一下短信验证码登录. 1.首先得先一个认证类,来认证验证码是否正确,这 ...
最新文章
- IntelliJ IDEA 自动编译功能无法使用,On 'update' action:选项里面没有update classes and resources这项...
- Android之SharedPreferences详解
- openlayers 根据style设置显示级别并在字体加背景框
- gcc动态链接库基本知识
- Redis 之(二) Redis的基本数据结构以及一些常用的操作
- 年度数据与月度数据转化_山东工会新媒体传播力指数2020年12月数据、年度数据出炉...
- C++什么是内存泄漏
- ionic更改端口号
- 用subline添加单引号和逗号,在sql中使用
- MySQL中使用CASE出错,如何在MySQL中正确使用CASE..WHEN
- 将整个表单设置为只读_如何将独立网站设置为制作中,阻止搜索引擎收录网站页面?...
- SpringBoot学习笔记(16)----SpringBoot整合Swagger2
- 360互联网技术训练营第18期——AIOps落地实践探索 火热报名中!
- set python_Python的set集合详解
- dos窗口启动mysql
- 必须收藏的文档:TIBCO Spotfire入门大全
- 如何将开发好的安卓应用程序发布到安卓市场或商店
- java 四舍六入五成双
- eclipse第十七课时
- MySQL 数据库 分组查询