这篇文章主要讲解了spring boot整合scurity如何实现简单的登录校验,内容清晰明了,对此有兴趣的小伙伴可以学习一下,相信大家阅读完之后会有帮助。
成都创新互联公司主打移动网站、成都网站建设、成都网站制作、网站改版、网络推广、网站维护、国际域名空间、等互联网信息服务,为各行业提供服务。在技术实力的保障下,我们为客户承诺稳定,放心的服务,根据网站的内容与功能再决定采用什么样的设计。最后,要实现符合网站需求的内容、功能与设计,我们还会规划稳定安全的技术方案做保障。
开发环境:springboot
maven引入:
<dependency> <groupId>org.springframework.security.oauth</groupId> <artifactId>spring-security-oauth3</artifactId> <version>2.2.1.RELEASE</version> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-jwt</artifactId> <version>1.0.10.RELEASE</version> </dependency>
1、先在数据库创建用户表,用户名为username,密码名为password。下面是我用户表的实体
private Integer id; /** * 昵称 */ private String name; /** * 职位 */ private String code; /** * 密码 */ private String passwd; /** * 用户名 */ private String username; /** * 手机号 */ private String phone; /** * 创建时间 */ private Date createdTime;
2、看项目是JPA、还是mybatis。我这边项目使用的是mybatis。需要有一个方法通过用户名获取用户信息。
3、创建一个用户验证类实现 UserDetails 继承用户实体
public class SecurityUser extends SysUser implements UserDetails { private static final long serialVersiongUID = 1l; public SecurityUser(SysUser sysUser) { if (null != sysUser) { this.setCode(sysUser.getCode()); this.setCreatedTime(sysUser.getCreatedTime()); this.setId(sysUser.getId()); this.setName(sysUser.getName()); this.setPasswd(sysUser.getPasswd()); this.setPhone(sysUser.getPhone()); this.setUsername(sysUser.getUsername()); } } @Override public Collection<? extends GrantedAuthority> getAuthorities() { Collection<GrantedAuthority> authorities = new ArrayList<>(); String username = this.getUsername(); if (username != null) { SimpleGrantedAuthority authority = new SimpleGrantedAuthority(username); authorities.add(authority); } return authorities; } @Override public String getPassword() { return super.getPasswd(); } //账户是否未过期,过期无法验证 @Override public boolean isAccountNonExpired() { return true; } //指定用户是否解锁,锁定的用户无法进行身份验证 @Override public boolean isAccountNonLocked() { return true; } //指示是否已过期的用户的凭据(密码),过期的凭据防止认证 @Override public boolean isCredentialsNonExpired() { return true; } //是否可用 ,禁用的用户不能身份验证 @Override public boolean isEnabled() { return true; } }
4、重点!创建一个scurity config配置类
@Configuration @EnableWebSecurity public class UiSecurityConfig extends WebSecurityConfigurerAdapter { private static final Logger logger = LoggerFactory.getLogger(UiSecurityConfig.class); @Override protected void configure(HttpSecurity http) throws Exception { //配置策略 http.csrf().disable(); http.authorizeRequests(). antMatchers("/static/**").permitAll().anyRequest().authenticated(). and().formLogin().loginPage("/login").permitAll().successHandler(loginSuccessHandler()). and().logout().permitAll().invalidateHttpSession(true). deleteCookies("JSESSIONID").logoutSuccessHandler(logoutSuccessHandler()). and().sessionManagement().maximumSessions(10).expiredUrl("/login"); } @Bean public BCryptPasswordEncoder passwordEncoder() { //密码加密 return new BCryptPasswordEncoder(4); } @Bean public LogoutSuccessHandler logoutSuccessHandler() { //登出处理 return new LogoutSuccessHandler() { @Override public void onLogoutSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException { try { SecurityUser user = (SecurityUser) authentication.getPrincipal(); logger.info("USER : " + user.getUsername() + " LOGOUT SUCCESS ! "); } catch (Exception e) { logger.info("LOGOUT EXCEPTION , e : " + e.getMessage()); } httpServletResponse.sendRedirect("/login"); } }; } @Bean public SavedRequestAwareAuthenticationSuccessHandler loginSuccessHandler() { //登入处理 return new SavedRequestAwareAuthenticationSuccessHandler() { @Override public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException { SysUser userDetails = (SysUser) authentication.getPrincipal(); logger.info("USER : " + userDetails.getUsername() + " LOGIN SUCCESS ! "); // 登录成功后重定向路径 response.sendRedirect("/"); } }; } //用户登录实现 @Bean public UserDetailsService userDetailsService() { return new UserDetailsService() { @Autowired private SysUserDao sysUserDao;//这里是引入数据库连接dao @Override public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException { SysUser userNmae = new SysUser(); userNmae.setUsername(s); List<SysUser> listUser = sysUserDao.queryAll(userNmae);//通过用户名获取个用户信息 SysUser user = null; if (listUser.size() > 0) { user = listUser.get(0); } if (user == null) throw new UsernameNotFoundException("Username " + s + " not found"); return new SecurityUser(user); } }; } }
5、基础工作准备完成开始写controller
@Controller public class LoginController { @Resource private SessionTool sessionTool; // 获取登录页面 @RequestMapping(value = "/login", method = RequestMethod.GET) public String login() { return "login"; } @RequestMapping("/") public String login(ModelMap map){ SysUser sysUser = sessionTool.getUser(); map.addAttribute("sysUser", sysUser); return "index"; } }
6、从session获取用户信息
@Component public class SessionTool { public SysUser getUser() { //为了session从获取用户信息,可以配置如下 SysUser user = new SysUser(); SecurityContext ctx = SecurityContextHolder.getContext(); Authentication auth = ctx.getAuthentication(); if (auth.getPrincipal() instanceof UserDetails) user = (SysUser) auth.getPrincipal(); return user; } public HttpServletRequest getRequest() { return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest(); } }
7、login.html页面(登录路径为login 请求方式为post,scurity自带的登录路径)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="/login" method="post"> 用户名 : <input type="text" name="username"/> 密码 : <input type="password" name="password"/> <input type="submit" value="登录"> </form> </body> </html>
总结一下思路:
引入依赖包-》创建用户表-》创建用户表数据库查询接口-》创建用户校验类实现UserDetails接口-》创建scurity配置类继承 WebSecurityConfigurerAdapter 方法configure为配置校验策略-》创建controller配置登录页面跳转接口-》创建登陆页面用户名必须为username 密码为password 登录路径为'/login' 请求方式为post
由于scurity配置的密码检验是加密的为了测试可以在Test模块中获取加密后的密码然后存到用户表的password字段中。
@Test public void encoder() { String password = "123123"; BCryptPasswordEncoder encoder = new BCryptPasswordEncoder(4); String enPassword = encoder.encode(password); System.out.println(enPassword); }
看完上述内容,是不是对spring boot整合scurity如何实现简单的登录校验有进一步的了解,如果还想学习更多内容,欢迎关注创新互联行业资讯频道。
网站标题:springboot整合scurity如何实现简单的登录校验
分享地址:https://www.cdcxhl.com/article18/iiogdp.html
成都网站建设公司_创新互联,为您提供建站公司、微信小程序、网站导航、电子商务、网站策划、品牌网站设计
声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联